Esempio n. 1
0
        public void NockedResponseCorrectlyRespondsBasedOnFunctionBodyFiltersIfFunctionReturnsTrue()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Post("/api/v2/action/", (body) => { return(true); })
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("fish", "chips");
            request.Method = "POST";

            var postData = "{\"Action\":\"AddFunds\",\"FirstName\":\"Joe\",\"Surname\":\"Bloggs\",\"Amount\":50.95}";
            var bytes    = Encoding.UTF8.GetBytes(postData);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.True);
        }
Esempio n. 2
0
        public void WhenANockHasBeenDefinedForOneRequestAndTwoRequestsAreMadeTheSecondWillFail()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.True);

            var errorMessage = "";

            try
            {
                request             = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;
                request.ContentType = "application/json; encoding='utf-8'";
                request.Method      = "GET";
                response            = request.GetResponse();
            }
            catch (WebException ex)
            {
                errorMessage = ex.Message;
            }

            Assert.That(errorMessage, Is.EqualTo("The remote server returned an error: (417) Expectation Failed."));
        }
Esempio n. 3
0
        public void NockedResponseCorrectlyRespondsBasedOnStringHeaderFiltersExactMatch()
        {
            var headers = new NameValueCollection();

            headers.Add("fish", "chips");
            headers.Add("peas", "beans");

            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .MatchHeaders(headers, true)
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("peas", "beans");
            request.Headers.Add("fish", "chips");
            request.Method = "GET";

            var errorMessage = "";

            try
            {
                var response = request.GetResponse();
            }
            catch (WebException ex)
            {
                errorMessage = ex.Message;
            }

            Assert.That(nock.Done(), Is.False);
            Assert.That(errorMessage, Is.EqualTo("The remote server returned an error: (417) Expectation Failed."));
        }
Esempio n. 4
0
        public void Test301Redirects()
        {
            var nock = new nock("http://domain-name.com")
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.TemporaryRedirect, "", new NameValueCollection {
                { "Location", "http://blahasdfasdf.com/test" }
            });

            var nock2 = new nock("http://blahasdfasdf.com")
                        .Get("/test")
                        .Reply(HttpStatusCode.OK, "OhYeh");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType       = "application/json; encoding='utf-8'";
            request.Method            = "Get";
            request.AllowAutoRedirect = true;

            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            Console.WriteLine(bodyOne);

            Assert.That(nock.Done(), Is.True);
            Assert.That(bodyOne, Is.EqualTo("OhYeh"));
        }
Esempio n. 5
0
        public void NockedResponseCorrectlyRespondsBasedOnStringBodyFilters()
        {
            var postData =
                "{" +
                "Action: \"AddFunds\"," +
                "FirstName: \"Joe\"," +
                "Surname: \"Bloggs\"" +
                "Amount: 50.95" +
                "}";

            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Post("/api/v2/action/", postData)
                       .Reply(HttpStatusCode.OK, "The body");

            var bytes = Encoding.UTF8.GetBytes(postData);

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType   = "application/json; encoding='utf-8'";
            request.ContentLength = bytes.Length;
            request.Method        = "POST";

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.True);
        }
Esempio n. 6
0
        public void NockedResponseCorrectlyRespondsBasedOnResponseCreatorFunctionWithQueryString()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/api/v2/action/")
                       .Query(true)
                       .Reply(HttpStatusCode.OK, (requestDetails) =>
            {
                var query = "";

                foreach (var key in requestDetails.Query.AllKeys)
                {
                    query += string.Format("{0}:{1}", key, requestDetails.Query[key]);
                }

                return(new WebResponse(string.Format("0:{0},1:{1},2:{2}", requestDetails.Url, query, requestDetails.Body)));
            });

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/?test=1") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "Get";

            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            Console.WriteLine(bodyOne);

            Assert.That(nock.Done(), Is.True);
            Assert.That(bodyOne, Is.EqualTo("0:http://domain-name.com/api/v2/action/,1:test:1,2:"));
        }
Esempio n. 7
0
        public void WhenANockHasBeenDefinedForTwoRequestsAndTwoRequestsAreMadeBothWillPass()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body")
                       .Times(2);

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            request             = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;
            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            response            = request.GetResponse();
            var bodyTwo = ReadResponseBody(response);

            Assert.That(nock.Done(), Is.True);
            Assert.That(bodyOne, Is.EqualTo("The body"));
            Assert.That(bodyTwo, Is.EqualTo("The body"));
        }
Esempio n. 8
0
        public void QueryFunctionCorrectlyCreatesFuncMatch()
        {
            var nock = new nock("http://www.google.co.uk").Get("/").Query((queryDetails) => { return(true); }).Reply(HttpStatusCode.OK, "");

            Assert.That(nock.NockedRequests.Count, Is.EqualTo(1));
            Assert.That(nock.NockedRequests[0].QueryMatcher, Is.EqualTo(QueryMatcher.Func));
            Assert.That(nock.NockedRequests[0].QueryFunc != null, Is.EqualTo(true));
        }
Esempio n. 9
0
        public void QueryFunctionCorrectlyCreatesBooleanMatch()
        {
            var nock = new nock("http://www.google.co.uk").Get("/").Query(true).Reply(HttpStatusCode.OK, "");

            Assert.That(nock.NockedRequests.Count, Is.EqualTo(1));
            Assert.That(nock.NockedRequests[0].QueryMatcher, Is.EqualTo(QueryMatcher.Bool));
            Assert.That(nock.NockedRequests[0].QueryResult, Is.EqualTo(true));
        }
Esempio n. 10
0
        public void QueryFunctionCorrectlyCreatesNameValueCollectionMatchExact()
        {
            var nvc = new NameValueCollection();

            var nock = new nock("http://www.google.co.uk").Get("/").Query(nvc, true).Reply(HttpStatusCode.OK, "");

            Assert.That(nock.NockedRequests.Count, Is.EqualTo(1));
            Assert.That(nock.NockedRequests[0].QueryMatcher, Is.EqualTo(QueryMatcher.NameValueExact));
            Assert.That(nock.NockedRequests[0].Query, Is.EqualTo(nvc));
        }
Esempio n. 11
0
        public void ReplyWillThrowAnExceptionIfNockHasAlreadyBeenBuilt()
        {
            var nock = new nock("http://www.google.co.uk")
                       .Get("/")
                       .Reply(HttpStatusCode.OK, "");

            var exception = Assert.Catch <Exception>(() => nock.Reply(HttpStatusCode.OK, ""));

            Assert.That(exception.Message, Is.EqualTo("The nock has already been built"));
        }
        public async Task InitIsSuccessfulWhenValidDataIsProvided()
        {
            var responseHeaders = new NameValueCollection()
            {
                { "x-access-token", "8363999c-bdc2-45a7-afe6-b0af9ad44aca" }
            };

            var nockOne = new nock("http://localhost:8080")
                          .Head("/config")
                          .MatchHeaders((headers) =>
            {
                return(MatchAuthorizationHeader(headers["Authorization"], "/config", "head", true));
            })
                          .Reply(HttpStatusCode.OK, string.Empty, responseHeaders);

            var nockTwo = new nock("http://localhost:8080")
                          .Get("/config/proj/prod/1.1.1")
                          .MatchHeaders((headers) =>
            {
                return(MatchAuthorizationHeader(headers["Authorization"], "/config/proj/prod/1.1.1", "get") &&
                       headers["x-access-token"] == "8363999c-bdc2-45a7-afe6-b0af9ad44aca");
            })
                          .Reply(HttpStatusCode.OK, GetEmbeddedResource("ElencyConfig.Tests.ValidConfigurationBody.json"));

            try
            {
                var config = new ElencyConfiguration()
                {
                    Uri                  = "http://localhost:8080",
                    AppId                = "proj",
                    AppVersion           = "1.1.1",
                    Environment          = "prod",
                    HMACAuthorizationKey = HMACAuthorizationKey,
                    ConfigEncryptionKey  = EncryptionKey
                };

                var client = new ElencyConfigClient();
                await client.Init(config);

                Assert.IsTrue(nockOne.Done());
                Assert.IsTrue(nockTwo.Done());
                Assert.AreEqual(2, client.GetAllKeys().Count);
                Assert.AreEqual("KeyOneValue", client.Get("KeyOne"));
                Assert.AreEqual("KeyTwoValue", client.Get("KeyTwo"));
                Assert.AreEqual("1.1.1", client.AppVersion);
                Assert.AreEqual("prod", client.Environment);
                Assert.AreEqual("9b386d19-fa7a-40ba-b794-f961e56ffe07", client.ConfigurationId);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail("An error was defined");
            }
        }
        public async Task GetReturnsNullIfKeyDoesNotExist()
        {
            var responseHeaders = new NameValueCollection()
            {
                { "x-access-token", "8363999c-bdc2-45a7-afe6-b0af9ad44aca" }
            };

            var nockOne = new nock("http://localhost:8080")
                          .Head("/config")
                          .MatchHeaders((headers) =>
            {
                return(MatchAuthorizationHeader(headers["Authorization"], "/config", "head", true));
            })
                          .Reply(HttpStatusCode.OK, string.Empty, responseHeaders);


            var nockTwo = new nock("http://localhost:8080")
                          .Get("/config/proj/prod/1.1.1")
                          .MatchHeaders((headers) =>
            {
                return(MatchAuthorizationHeader(headers["Authorization"], "/config/proj/prod/1.1.1", "get") &&
                       headers["x-access-token"] == "8363999c-bdc2-45a7-afe6-b0af9ad44aca");
            })
                          .Reply(HttpStatusCode.OK, GetEmbeddedResource("ElencyConfig.Tests.ValidConfigurationBody.json"));

            try
            {
                var config = new ElencyConfiguration()
                {
                    Uri                  = "http://localhost:8080",
                    AppId                = "proj",
                    AppVersion           = "1.1.1",
                    Environment          = "prod",
                    HMACAuthorizationKey = HMACAuthorizationKey,
                    ConfigEncryptionKey  = EncryptionKey
                };

                var client = new ElencyConfigClient();
                await client.Init(config);

                Assert.IsTrue(nockOne.Done());
                Assert.IsTrue(nockTwo.Done());
                Assert.AreEqual(null, client.Get("Cheese"));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail("An error was defined");
            }
        }
Esempio n. 14
0
        public void CallingDoneOnANockReturnsTrueIfTheNockResponseWasUsedWhenUsingWebClient()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body");


            var client = new WebClient();

            client.Headers[HttpRequestHeader.ContentType] = "application/json; encoding='utf-8'";
            var body = client.DownloadString("http://domain-name.com/api/v2/action/");

            Assert.That(nock.Done(), Is.True);
            Assert.That(body, Is.EqualTo("The body"));
        }
Esempio n. 15
0
        public void CallingDoneOnANockReturnsTrueIfTheNockResponseWasUsed()
        {
            var nock1 = new nock("http://domain-name.com")
                        .ContentType("application/json; encoding='utf-8'")
                        .Get("/api/v2/action/")
                        .Log(Console.WriteLine)
                        .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock1.Done(), Is.True);
        }
Esempio n. 16
0
        public void WhenANockHasBeenDefinedForTwoRequestsButOnlyOneRequestHasMadeCallingDoneWillReturnFalse()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body")
                       .Times(2);

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.False);
        }
        public async Task InitThrowsAnExcpetionWhenANon200StatusCodeIsReturnedFromElencyConfigServer()
        {
            var responseHeaders = new NameValueCollection()
            {
                { "x-access-token", "8363999c-bdc2-45a7-afe6-b0af9ad44aca" }
            };

            var nockOne = new nock("http://localhost:8080")
                          .Head("/config")
                          .MatchHeaders((headers) =>
            {
                return(MatchAuthorizationHeader(headers["Authorization"], "/config", "head", true));
            })
                          .Reply(HttpStatusCode.OK, string.Empty, responseHeaders);

            var nockTwo = new nock("http://localhost:8080")
                          .Get("/config/proj/prod/1.1.1")
                          .MatchHeaders((headers) =>
            {
                return(headers["x-access-token"] == "8363999c-bdc2-45a7-afe6-b0af9ad44aca");
            })
                          .MatchHeader("x-access-token", "8363999c-bdc2-45a7-afe6-b0af9ad44aca")
                          .Reply(HttpStatusCode.Unauthorized, string.Empty);

            try
            {
                var config = new ElencyConfiguration()
                {
                    Uri                  = "http://localhost:8080",
                    AppId                = "proj",
                    AppVersion           = "1.1.1",
                    Environment          = "prod",
                    HMACAuthorizationKey = HMACAuthorizationKey,
                    ConfigEncryptionKey  = EncryptionKey,
                    RequestTimeout       = 500
                };

                var client = new ElencyConfigClient();
                await client.Init(config);

                Assert.Fail("An error was defined");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 18
0
        public void NockedResponseCorrectlyRespondsBasedOnFunctionHeaderFiltersIfFunctionReturnsTrue()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .MatchHeaders((headers) => { return(headers["fish"] == "chips"); })
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("fish", "chips");
            request.Method = "GET";
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.True);
        }
Esempio n. 19
0
        public void NockedPostRequestsWorkCorrectlyWithBodyFilterAndCustomResponse()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .MatchHeader("cheese", "gravy")
                       .Post("/api/v2/action/", (body) => { return(body.Contains("AddFunds")); })
                       .Reply(HttpStatusCode.OK, (requestDetails) =>
            {
                var requestBody = requestDetails.Body;
                var firstName   = requestBody.Substring(requestBody.IndexOf("FirstName") + 12);
                firstName       = firstName.Substring(0, firstName.IndexOf("\""));
                var surname     = requestBody.Substring(requestBody.IndexOf("Surname") + 10);
                surname         = surname.Substring(0, surname.IndexOf("\""));

                var headers = new NameValueCollection();
                headers.Add("firstname", firstName);

                return(new WebResponse(headers, surname));
            });

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("cheese", "gravy");
            request.Method = "POST";

            var postData = "{\"Action\":\"AddFunds\",\"FirstName\":\"Joe\",\"Surname\":\"Bloggs\",\"Amount\":50.95}";
            var bytes    = Encoding.UTF8.GetBytes(postData);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            Assert.That(nock.Done(), Is.True);
            Assert.That(response.Headers["firstname"], Is.EqualTo("Joe"));
            Assert.That(bodyOne, Is.EqualTo("Bloggs"));
        }
Esempio n. 20
0
        public void NockedResponseCorrectlyRespondsBasedOnFunctionBodyFiltersIfFunctionReturnsFalse()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Post("/api/v2/action/", (body) => { return(false); })
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("fish", "chips");
            request.Method = "POST";

            var postData = "{\"Action\":\"AddFunds\",\"FirstName\":\"Joe\",\"Surname\":\"Bloggs\",\"Amount\":50.95}";
            var bytes    = Encoding.UTF8.GetBytes(postData);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            Assert.That(nock.Done(), Is.False);

            var errorMessage = "";

            try
            {
                request             = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;
                request.ContentType = "application/json; encoding='utf-8'";
                request.Method      = "GET";
                var response = request.GetResponse();
            }
            catch (WebException ex)
            {
                errorMessage = ex.Message;
            }

            Assert.That(errorMessage, Is.EqualTo("The remote server returned an error: (417) Expectation Failed."));
        }
Esempio n. 21
0
        public void NockedResponseCorrectlyRespondsBasedOnStringHeaderFilters()
        {
            var headers = new NameValueCollection();

            headers.Add("fish", "chips");
            headers.Add("peas", "beans");

            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .MatchHeaders(headers)
                       .Get("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("peas", "beans");
            request.Headers.Add("fish", "chips");
            request.Method = "GET";
            System.Net.WebResponse response = request.GetResponse();

            Assert.That(nock.Done(), Is.True);
        }
Esempio n. 22
0
        public void NockedResponsesCorrectlyRespondWhenContentTypeDiffers()
        {
            var xmlResponse  = "<somexml />";
            var jsonResponse = "{ a:\"\"}";

            var nockOne = new nock("http://www.nock-fake-domain.co.uk")
                          .ContentType("application/xml; encoding='utf-8'")
                          .Get("/")
                          .Reply(HttpStatusCode.OK, xmlResponse);

            var nockTwo = new nock("http://www.nock-fake-domain.co.uk")
                          .ContentType("application/json; encoding='utf-8'")
                          .Get("/")
                          .Reply(HttpStatusCode.OK, jsonResponse);

            var request = WebRequest.Create("http://www.nock-fake-domain.co.uk") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";

            System.Net.WebResponse response = request.GetResponse();
            var body = ReadResponseBody(response);

            Assert.That(nockOne.Done(), Is.False);
            Assert.That(nockTwo.Done(), Is.True);
            Assert.That(body, Is.EqualTo(jsonResponse));

            request             = WebRequest.Create("http://www.nock-fake-domain.co.uk") as HttpWebRequest;
            request.ContentType = "application/xml; encoding='utf-8'";
            request.Method      = "GET";

            response = request.GetResponse();
            body     = ReadResponseBody(response);

            Assert.That(nockOne.Done(), Is.True);
            Assert.That(body, Is.EqualTo(xmlResponse));
        }
Esempio n. 23
0
        public void WhenANockHasBeenDefinedWithWildcardUrlForTwoRequestsAndTwoRequestsAreMadeBothWillPass()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .Get("/*/?location=true")
                       .Reply(HttpStatusCode.OK, (requestDetails) =>
            {
                var responseHeaders = new NameValueCollection();
                responseHeaders.Add("Location", requestDetails.Url);

                return(new WebResponse(responseHeaders, "{ \"src\": \"" + requestDetails.Url + "\" }"));
            })
                       .Times(2);

            var request = WebRequest.Create("http://domain-name.com/one/?location=true") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            Assert.That(nock.Done(), Is.False);
            Assert.That(bodyOne, Is.EqualTo("{ \"src\": \"http://domain-name.com/one/\" }"));
            Assert.That(response.Headers["Location"], Is.EqualTo("http://domain-name.com/one/"));


            request             = WebRequest.Create("http://domain-name.com/two/?location=true") as HttpWebRequest;
            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";
            response            = request.GetResponse();
            var bodyTwo = ReadResponseBody(response);

            Assert.That(nock.Done(), Is.True);
            Assert.That(bodyTwo, Is.EqualTo("{ \"src\": \"http://domain-name.com/two/\" }"));
            Assert.That(response.Headers["Location"], Is.EqualTo("http://domain-name.com/two/"));
        }
Esempio n. 24
0
        public void CallingDoneOnANockReturnsFalseIfTheNockResponseWasNotUsed()
        {
            var nock1 = new nock("http://domain-name.com")
                        .ContentType("application/json; encoding='utf-8'")
                        .Get("/api/v2/action/")
                        .Reply(HttpStatusCode.OK, "The body");

            var request = WebRequest.Create("http://domain-name.com/api/v2/action2/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Method      = "GET";

            System.Net.WebResponse response;
            try
            {
                response = request.GetResponse();
            }
            catch (WebException err)
            {
                Assert.AreEqual(err.Message, "The remote server returned an error: (417) Expectation Failed.");
            }

            Assert.That(nock1.Done(), Is.False);
        }
Esempio n. 25
0
        public void NockedResponseCorrectlyRespondsBasedOnResponseCreatorFunction()
        {
            var nock = new nock("http://domain-name.com")
                       .ContentType("application/json; encoding='utf-8'")
                       .MatchHeader("cheese", "gravy")
                       .Post("/api/v2/action/")
                       .Reply(HttpStatusCode.OK, (requestDetails) =>
            {
                var headers = new NameValueCollection();
                headers.Add("crowe", "man");

                return(new WebResponse(headers, "yum yum"));
            });

            var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest;

            request.ContentType = "application/json; encoding='utf-8'";
            request.Headers.Add("cheese", "gravy");
            request.Method = "POST";

            var postData = "{\"Action\":\"AddFunds\",\"FirstName\":\"Joe\",\"Surname\":\"Bloggs\",\"Amount\":50.95}";
            var bytes    = Encoding.UTF8.GetBytes(postData);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            System.Net.WebResponse response = request.GetResponse();
            var bodyOne = ReadResponseBody(response);

            Assert.That(nock.Done(), Is.True);
            Assert.That(response.Headers["crowe"], Is.EqualTo("man"));
            Assert.That(bodyOne, Is.EqualTo("yum yum"));
        }
Esempio n. 26
0
 public void TestMethod1()
 {
     var blah = new nock("");
 }
        public async Task TimeredRefreshCorrectlyUpdatesTheConfiguration()
        {
            var responseHeaders = new NameValueCollection()
            {
                { "x-access-token", "8363999c-bdc2-45a7-afe6-b0af9ad44aca" }
            };

            var nockOne = new nock("http://localhost:8080")
                          .Head("/config")
                          .MatchHeaders((headers) =>
            {
                var match = MatchAuthorizationHeader(headers["Authorization"], "/config", "head", true);
                return(match);
            })
                          .Reply(HttpStatusCode.OK, string.Empty, responseHeaders);

            var nockTwo = new nock("http://localhost:8080")
                          .Get("/config/proj/prod/1.1.1")
                          .MatchHeaders((headers) =>
            {
                var match = MatchAuthorizationHeader(headers["Authorization"], "/config/proj/prod/1.1.1", "get") &&
                            headers["x-access-token"] == "8363999c-bdc2-45a7-afe6-b0af9ad44aca";
                return(match);
            })
                          .Reply(HttpStatusCode.OK, GetEmbeddedResource("ElencyConfig.Tests.ValidConfigurationBody.json"));

            var nockThree = new nock("http://localhost:8080")
                            .Head("/config/proj/prod/1.1.1")
                            .MatchHeaders((headers) =>
            {
                var match = MatchAuthorizationHeader(headers["Authorization"], "/config/proj/prod/1.1.1", "head") &&
                            headers["x_version_hash"] == "Re10aakOhCrz488W6ws5/A==";
                return(match);
            })
                            .Reply(HttpStatusCode.OK, string.Empty);

            var responseHeaders2 = new NameValueCollection()
            {
                { "x-access-token", "7363999c-bdc2-45a7-afe6-b0af9ad44acb" }
            };

            var nockFour = new nock("http://localhost:8080")
                           .Head("/config")
                           .MatchHeaders((headers) =>
            {
                var match = MatchAuthorizationHeader(headers["Authorization"], "/config", "head", true);
                return(match);
            })
                           .Reply(HttpStatusCode.OK, string.Empty, responseHeaders2);

            var nockFive = new nock("http://localhost:8080")
                           .Get("/config/proj/prod/1.1.1")
                           .MatchHeaders((headers) =>
            {
                var match = MatchAuthorizationHeader(headers["Authorization"], "/config/proj/prod/1.1.1", "get") &&
                            headers["x-access-token"] == "7363999c-bdc2-45a7-afe6-b0af9ad44acb";
                return(match);
            })
                           .Reply(HttpStatusCode.OK, GetEmbeddedResource("ElencyConfig.Tests.ValidConfigurationBodyTwo.json"));

            try
            {
                var config = new ElencyConfiguration()
                {
                    Uri                  = "http://localhost:8080",
                    AppId                = "proj",
                    AppVersion           = "1.1.1",
                    Environment          = "prod",
                    HMACAuthorizationKey = HMACAuthorizationKey,
                    ConfigEncryptionKey  = EncryptionKey,
                    RefreshInterval      = 100
                };

                var client = new ElencyConfigClient();
                await client.Init(config);

                Assert.IsTrue(nockOne.Done(), "1");
                Assert.IsTrue(nockTwo.Done(), "2");
                Assert.AreEqual(2, client.GetAllKeys().Count, "3");
                Assert.AreEqual("KeyOneValue", client.Get("KeyOne"), "4");
                Assert.AreEqual("KeyTwoValue", client.Get("KeyTwo"), "5");
                Assert.AreEqual("1.1.1", client.AppVersion, "6");
                Assert.AreEqual("prod", client.Environment, "7");
                Assert.AreEqual("9b386d19-fa7a-40ba-b794-f961e56ffe07", client.ConfigurationId, "8");

                try
                {
                    while (true)
                    {
                        try
                        {
                            Assert.IsTrue(nockThree.Done(), "9");
                            Assert.IsTrue(nockFour.Done(), "10");
                            Assert.IsTrue(nockFive.Done(), "11");
                            Assert.AreEqual(3, client.GetAllKeys().Count, "12");
                            Assert.AreEqual("KeyOneValue", client.Get("KeyOne"), "13");
                            Assert.AreEqual("KeyTwoValueUpdated", client.Get("KeyTwo"), "14");
                            Assert.AreEqual("KeyThreeValue", client.Get("KeyThree"), "15");
                            Assert.AreEqual("1.1.1", client.AppVersion, "16");
                            Assert.AreEqual("prod", client.Environment, "17");
                            Assert.AreEqual("9b386d19-fa7a-40ba-b794-f961e56ffe07", client.ConfigurationId, "18");
                            break;
                        }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Assert.Fail("An error was defined");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail("An error was defined");
            }
        }
Esempio n. 28
0
 public void PutWillNotThrowAnExeptionIfStringTypeBodyMatcherFunctionIsDefinedWhichIsStatic()
 {
     var nock = new nock("http://www.google.co.uk").Put("/Test", FilterStringStatic);
 }
Esempio n. 29
0
 public void PutWillNotThrowAnExeptionIfCustomTypeBodyMatcherFunctionIsDefinedWhichIsStatic()
 {
     var nock = new nock("http://www.google.co.uk").Put <Fish>("/Test", FilterTypedStatic);
 }