public async Task RecaptchaWithValidRecaptchaAnswer_WithAnswerAsAcrValue_ShouldNotChallenge()
        {
            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                var identityServerBuilder = new IdentityServerWithRecaptcha()
                                            .WithProtectedGrantType("password")
                                            .WithPrivateKey("private_key")
                                            .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                            .WithNumberOfAllowedLoginFailuresPerIpAddress(1);

                using (var server = identityServerBuilder.Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithRecaptchaResponseAsAcrValue("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().Be(HttpStatusCode.OK);
                    var tokenResponse = await response.Content.ReadAsAsync <TokenResponseModel>();

                    tokenResponse.AccessToken.Should().NotBeNullOrEmpty();

                    identityServerBuilder.RecaptchaMonitor.HasIssuedChallenge.Should().BeFalse();
                }
            }
        }
        public async Task RecaptchaWithValidCredentials_WithTooManyFailedLogins_ShouldPass()
        {
            const int NumberOfAllowedLoginFailures = 1;

            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(NumberOfAllowedLoginFailures)
                                    .WithFailuresForIpAddress("192.168.1.101", NumberOfAllowedLoginFailures + 1)
                                    .WithChallengeAsBadRequest()
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(NumberOfAllowedLoginFailures).Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithGrantType("password")
                                   .WithHttpHeaderRecaptchaResponseRaw("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().NotBe(HttpStatusCode.BadRequest);
                }
            }
        }
        public async Task FakeServer_ExpectGetWithRequestHeadersSpecified_WhenRequestHeadersProvided_ResponseMatchesExpection()
        {
            const string expectedResult = "Some String Data";

            var port = Ports.GetFreeTcpPort();

            var baseAddress = "http://localhost:" + port;

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(port))
            {
                var expectedRequestHeaders = new WebHeaderCollection
                {
                    {"X-Dummy1", "dummy1val"},
                    {"X-Dummy2", "dummy2val"},
                    {"X-Dummy3", "dummy3val"}
                };

                fakeServer.Expect.Get(url, expectedRequestHeaders).Returns(expectedResult);
                fakeServer.Start();

                var client = new HttpClient { BaseAddress = new Uri(baseAddress) };

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy1", "dummy1val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy2", "dummy2val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy3", "dummy3val");

                var result = await client.GetAsync(url);

                result.StatusCode.Should().Be(HttpStatusCode.OK);
                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
            }
        }
Esempio n. 4
0
        public async Task FakeServer_ExpectGetWithResponseHeadersSpecified_ResponseMatchesExpectionAndHasHeaders()
        {
            const string expectedResult = "Some String Data";

            var port = Ports.GetFreeTcpPort();

            var baseAddress = "http://localhost:" + port;

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(port))
            {
                fakeServer.Expect.Get(url).Returns(expectedResult, new WebHeaderCollection {
                    { "foo", "bar" }
                });
                fakeServer.Start();

                var client = new HttpClient {
                    BaseAddress = new Uri(baseAddress)
                };
                var result = await client.GetAsync(url);

                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
                result.Headers.Should().ContainSingle(x => x.Key == "foo");
            }
        }
        public async Task RecaptchaWithValidCredentials_WhenEveryoneIsChallenged()
        {
            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithChallengeAsBadRequest()
                                    .WithPlatformSecurityShieldsUp()
                                    .Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithGrantType("password")
                                   .WithHttpHeaderRecaptchaResponseRaw("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().NotBe(HttpStatusCode.BadRequest);
                }
            }
        }
        public async Task FakeServer_ExpectGetWithRequestHeadersSpecified_WhenRequestHeadersNotProvided_ResponseIsBadRequest()
        {
            const string expectedResult = "X-Dummy1 header value not as expected.\r\n\tExpected: dummy1val\r\n\tProvided: other1val\r\nX-Dummy2 header was not provided.\r\n";


            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                var expectedRequestHeaders = new WebHeaderCollection
                {
                    { "X-Dummy1", "dummy1val" },  // will have different value
                    { "X-Dummy2", "dummy2val" },  // will be missing
                    { "X-Dummy3", "dummy3val" }   // will match
                };

                fakeServer.Expect.Get(path, expectedRequestHeaders).Returns(expectedResult);
                fakeServer.Start();

                var client = fakeServer.Client;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy1", "other1val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy3", "dummy3val");

                var result = await client.GetAsync(path);

                result.StatusCode.Should().Be(HttpStatusCode.BadRequest);
                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
            }
        }
        public async Task RecaptchaWithValidRecaptchaAnswer_WithLongAnswerAsAcrValue_AndAllTheTrimmings_ShouldNotChallenge()
        {
            const string longAnswer = "03ACgFB9vknGtsjy3YCRubfh4Nk4_9j4jIaJ8q5nPO6AOu391yoMxeQctcw6-OPt5HyBGjm8B25-xrQUDD-kQjoJOrY3IBiFa5fh__YC9RVbRTPxNrGdhdUjyJxVzQE5obPE1AUPScn3gyS6iaIOxgW_wB-ttxB-0_ybk7GP6Dz-QFnrXQaYYGZEEQxLHQReku_wwiOIWV40HFEpMx_Z-LwPBKOWO3fk2p3fQsnZGCcAhnszi6DfdYJWKdBmfra6BjcJ4Tfx2Xvyn75a4CmDwS7FYp6kg_dmzN1BaLPSA26DKndbrjL3lW2ghKsaat6TTcIx23M5jvcUlzsh5QxHWd3YhmmokS_QfZa0dyuWMUJ1TisYrVOGsg6p2tCiPIm5qLLaWl1scXMgA5PLBR3cx0fNy7Q72gbkfLOQ";

            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=" + longAnswer)
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(1).Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithRecaptchaResponseAsAcrValue(longAnswer)
                                   .WithEncodedDevice("id", "type", "name", "token")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().Be(HttpStatusCode.OK);
                    var tokenResponse = await response.Content.ReadAsAsync <TokenResponseModel>();

                    tokenResponse.AccessToken.Should().NotBeNullOrEmpty();
                }
            }
        }
        public async Task FakeServer_ExpectGetWithRequestHeadersSpecified_WhenRequestHeadersProvided_ResponseMatchesExpection()
        {
            const string expectedResult = "Some String Data";


            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                var expectedRequestHeaders = new WebHeaderCollection
                {
                    { "X-Dummy1", "dummy1val" },
                    { "X-Dummy2", "dummy2val" },
                    { "X-Dummy3", "dummy3val" }
                };

                fakeServer.Expect.Get(path, expectedRequestHeaders).Returns(expectedResult);
                fakeServer.Start();

                var client = fakeServer.Client;

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy1", "dummy1val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy2", "dummy2val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy3", "dummy3val");

                var result = await client.GetAsync(path);

                result.StatusCode.Should().Be(HttpStatusCode.OK);
                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
            }
        }
Esempio n. 9
0
        public void FakeServer_CapturesAllRequests()
        {
            using (var fakeServer = new FakeServer())
            {
                fakeServer.Start();
                var baseAddress = fakeServer.BaseUri;

                Action<Action, int> repeat = (a, times) =>
                {
                    for (var i = 0; i < times; i++)
                        a();
                };

                var url1 = "/request1";
                var url2 = "/request2";
                var url3 = "/request3";
                var url4 = "/request4";

                var httpClient = new HttpClient();
                httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait();
                repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2);
                repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3);
                repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4);

                fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4);
            }
        }
Esempio n. 10
0
        public async Task RecaptchaWithInvalidRecaptchaAnswer_WithAnswerAsAcrValue_ShouldChallenge()
        {
            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = false
                }));

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(1)
                                    .WithFailuresForIpAddress("192.168.1.101", 1).Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithRecaptchaResponseAsAcrValue("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
                    response.Headers.WwwAuthenticate.Should().Contain(h => h.Scheme == "recaptcha");
                    response.Headers.WwwAuthenticate.Should().Contain(h => h.Parameter == @"url=""/recaptcha/platform""");
                }
            }
        }
Esempio n. 11
0
        public async Task RecaptchaWithInvalidRecaptchaAnswer_WithAnswerAsHeaderValue_ShouldChallenge(HttpStatusCode returnedStatusCode)
        {
            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(returnedStatusCode, string.Empty);

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(1).Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithHttpHeaderRecaptchaResponseBase64("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().Be(HttpStatusCode.OK);
                }
            }
        }
        public async Task RecaptchaWithValidRecaptchaAnswer_WithLongAnswerAsAcrValue_ShouldNotChallenge()
        {
            const string longAnswer = "sHPqR2vXe1Gvena4WLtGvpslvmQjQrrFVTQDUpTPJ05IAsEpxeuGuuWI4bpOE0fqVgk3GGSjZS3ZbAPwXJhpeZuEaQhg6Vyp8PqYKD1906snU6aWgphMtSpo4QLOgyzRbAtGV6km58lBWKvrzrzEzYUerm44QXngw0meLTmryh33X0xHMzTSm7DGueATSlSO2lCv9E9xKomDpOZVp8tDYEL5bJflNvB3fMD2P2kUftlb8iv6VON6flwMLYrCuweFPQZ61FizEJGwJ4zpS1Mfgw5hV9BEkHhYbmuYBoLniKkB4KwPrYOHFw9IwFyKTiqIQC70RVWODc4hpjVsLsP4xeNuIASjDKj33Np4XiocvEYv8JIYTWuEffot0SKWVE8OgNQH5BL77FkLjERV";

            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=" + longAnswer)
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                using (var server = new IdentityServerWithRecaptcha()
                                    .WithProtectedGrantType("password")
                                    .WithPrivateKey("private_key")
                                    .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                    .WithNumberOfAllowedLoginFailuresPerIpAddress(1).Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername("jeuser")
                                   .WithPassword("Passw0rd")
                                   .WithRecaptchaResponseAsAcrValue(longAnswer)
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().Be(HttpStatusCode.OK);
                    var tokenResponse = await response.Content.ReadAsAsync <TokenResponseModel>();

                    tokenResponse.AccessToken.Should().NotBeNullOrEmpty();
                }
            }
        }
Esempio n. 13
0
        public void FakeServer_NewWebClientCreated_ProxyShouldBeConfigured()
        {
            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Start();

                var wc = new WebClient();
                var defaultWebProxyForUri = WebRequest.DefaultWebProxy.GetProxy(new Uri("http://www.google.com/some-url2"));

                defaultWebProxyForUri.Should().Be(fakeServer.BaseUri);
                ((WebProxy)wc.Proxy).Address.Should().Be(fakeServer.BaseUri);
            }
        }
Esempio n. 14
0
        public void Get_Site_Informations_Test()
        {
            using (var fakeServer = new FakeServer(BASE_PORT))
            {
                fakeServer.Expect.Post("/enterprise/control/agent.php", "").Returns(System.Net.HttpStatusCode.OK, GET_SITE_INFORMATIONS_RESULT_XML);
                fakeServer.Start();

                var result = client.GetSite("domain.com");

                Assert.AreEqual(result.site.receive.result.status, "ok");
                Assert.AreEqual(result.site.receive.result.data.getInfo.Name, "sub.ppu12-5.demo.pp.plesk.ru");
            }
        }
Esempio n. 15
0
        public void Add_Alias_to_Site_Test()
        {
            using (var fakeServer = new FakeServer(BASE_PORT))
            {
                fakeServer.Expect.Post("/enterprise/control/agent.php", "").Returns(System.Net.HttpStatusCode.OK, ADD_ALIAS_RESULT_XML);
                fakeServer.Start();

                var result = client.CreateAlias(10, "demo.net");

                Assert.AreEqual(result.status, "ok");
                Assert.AreEqual(result.Id, "34");
            }
        }
Esempio n. 16
0
        public void FakeServer_RequestingAUriThatHasNotBeenModified_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get("/123").Returns(expectedResult);
                fakeServer.Start();

                var result = new WebClient().DownloadString(new Uri("http://www.bing.com/123"));

                result.Should().Be(expectedResult);
            }
        }
        public void ApiClientFailedRequestReturnsWebException()
        {
            using (var fakeServer = new FakeServer(12354))
            {
                var    client = new ApiClient(GetConfig());
                string json   = GetFakeResponse();
                fakeServer.Expect.Get("LG5").Returns(HttpStatusCode.BadRequest);
                fakeServer.Start();

                Action a = () => client.GetFromApi("LG5");

                a.ShouldThrow <WebException>();
            }
        }
        public void APiClientInvalidPostCodeReturnsInvalidPostCodeException()
        {
            using (var fakeServer = new FakeServer(12354))
            {
                var    client = new ApiClient(GetConfig());
                string json   = GetFakeResponse();
                fakeServer.Expect.Get("/123").Returns(json);
                fakeServer.Start();

                Action a = () => client.GetFromApi("123");

                a.ShouldThrow <InvalidPostCodeException>();
            }
        }
        public async Task RecaptchaWithValidCredentials_WithTooManyFailedLogins_ShouldPass()
        {
            const int NumberOfAllowedLoginFailures = 1;

            using (var fakeRecaptchaServer = new FakeServer())
            {
                fakeRecaptchaServer.Start();
                fakeRecaptchaServer.Expect.Get("/?secret=private_key&response=correct_response")
                .Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(new RecaptchaVerificationResponse
                {
                    Succeeded = true
                }));

                var ipAddress = "192.168.1.101";
                var username  = "******";

                var identityServerBuilder = new IdentityServerWithRecaptcha()
                                            .WithProtectedGrantType("password")
                                            .WithPrivateKey("private_key")
                                            .WithVerificationUri(fakeRecaptchaServer.BaseUri)
                                            .WithNumberOfAllowedLoginFailuresPerIpAddress(NumberOfAllowedLoginFailures)
                                            .WithFailuresForIpAddress(ipAddress, NumberOfAllowedLoginFailures + 1)
                                            .WithChallengeAsBadRequest()
                                            .WithNumberOfAllowedLoginFailuresPerIpAddress(NumberOfAllowedLoginFailures);

                using (var server = identityServerBuilder.Build())
                {
                    var response = await server.CreateNativeLoginRequest()
                                   .WithUsername(username)
                                   .WithPassword("Passw0rd")
                                   .WithGrantType("password")
                                   .WithHttpHeaderRecaptchaResponseRaw("correct_response")
                                   .Build()
                                   .PostAsync();

                    response.StatusCode.Should().NotBe(HttpStatusCode.BadRequest);

                    identityServerBuilder.RecaptchaMonitor.HasCompletedChallenge.Should().BeTrue();
                    identityServerBuilder.RecaptchaMonitor.ChallengeCompletedInvokeCount.Should().Be(1);
                    identityServerBuilder.RecaptchaMonitor.ResponseContext.State.Should().Be(RecaptchaState.ChallengeSucceeded);
                    identityServerBuilder.RecaptchaMonitor.UserContext.ShouldBeEquivalentTo(new RecaptchaUserContext
                    {
                        Username  = username,
                        IpAddress = ipAddress,
                        Device    = new RecaptchaUserDevice()
                    });
                }
            }
        }
Esempio n. 20
0
        public async Task FakeServer_ExpectGetReturnsString_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);
                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);
                result.Should().Be(expectedResult);
            }
        }
        public async Task FakeServer_ExpectGetWithMismatchingPath_Returns404()
        {
            const string expectedResult = "Some String Data";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get("/some-jibberish-path").Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.GetAsync("/home");

                resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 22
0
        public void Add_WebSpace_Test()
        {
            using (var fakeServer = new FakeServer(BASE_PORT))
            {
                fakeServer.Expect.Post("/enterprise/control/agent.php", "").Returns(System.Net.HttpStatusCode.OK, WEBSPACE_RESULT);
                fakeServer.Start();

                var result = client.CreateWebSpace("domain.com", "192.168.0.1", "ftplogin", "password", "username", "password");

                Debug.WriteLine(result.ErrorText);

                Assert.AreEqual(result.status, "ok");
                Assert.AreEqual(result.Id, "4");
                Assert.AreEqual(result.guid, "5ff343c1-a40b-4305-8986-2f27c240db7e");
            }
        }
Esempio n. 23
0
        public async Task FakeServer_ExpectPutWithObjectBodyReturns201_Returns201()
        {
            var expectedResult = new { RestaurantId = 1234 };

            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Put(path, string.Empty).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var result = await fakeServer.Client.PutAsync(path, new StringContent(string.Empty));

                result.StatusCode.Should().Be(HttpStatusCode.Created);
            }
        }
Esempio n. 24
0
        public async Task FakeServer_ExpectPutWithNoBodyReturns2011_Returns201()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Put(path, string.Empty).Returns(expectedResult).WithHttpStatus(HttpStatusCode.Created);
                fakeServer.Start();

                var result = await fakeServer.Client.PutAsync(path, new StringContent(string.Empty));

                result.StatusCode.Should().Be(HttpStatusCode.Created);
            }
        }
Esempio n. 25
0
        public void FakeServer_ExpectGetWithMismatchingPath_Returns404()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress    = "http://localhost:12354";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get("/some-jibberish-url").Returns(expectedResult);

                fakeServer.Start();

                var ex = Assert.Throws <WebException>(() => new WebClient().DownloadString(new Uri(baseAddress + "/home")));

                ((HttpWebResponse)ex.Response).StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 26
0
        public void Add_Site_Test()
        {
            using (var fakeServer = new FakeServer(BASE_PORT))
            {
                fakeServer.Expect.Post("/enterprise/control/agent.php", "").Returns(System.Net.HttpStatusCode.OK, PleskClientTest.ADD_SITE_RESULT);
                fakeServer.Start();

                var result = client.CreateSite(1, "domain.com", null);

                Debug.WriteLine(result.ErrorText);

                Assert.AreEqual(result.status, "ok");
                Assert.AreEqual(result.Id, "57");
                Assert.AreEqual(result.guid, "ed5de3a1-2d73-4dfa-9cee-4609afaccf6a");
            }
        }
        public async Task FakeServer_ExpectGetWithoutSlashAtTheStartOfUrl_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";

            const string path = "some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);
                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);

                result.Should().Be(expectedResult);
            }
        }
        public async Task FakeServer_ExpectGetWithMismatchingMethod_Returns404()
        {
            const string expectedResult = "Some String Data";
            const string path           = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.PostAsync(path, new StringContent(string.Empty));

                resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 29
0
        public async Task FakeServer_ShouldExecuteResponseExpectationCallback_ReturnExpectedData()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path?id=1234";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Callback(() => new HttpResponseExpectation(HttpStatusCode.OK, expectedResult));

                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);

                result.Should().Be(expectedResult);
            }
        }
        public void FakeServer_ExpectGetReturnsString_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(url).Returns(expectedResult);
                fakeServer.Start();

                var baseAddress = fakeServer.BaseUri;
                var result = new WebClient().DownloadString(new Uri(baseAddress + url));

                result.Should().Be(expectedResult);
            }
        }
Esempio n. 31
0
        public async Task FakeServer_IgnoredParameterInRestfulpath_Returns200()
        {
            var expectedResult = new { ResourceId = 1234 };

            const string fakepath   = "/some-resource/{ignore}/some-method";
            const string actualpath = "/some-resource/1234/some-method";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(fakepath).Returns(HttpStatusCode.Accepted, expectedResult);
                fakeServer.Start();

                var result = await fakeServer.Client.GetAsync(actualpath);

                result.StatusCode.Should().Be(HttpStatusCode.Accepted);
            }
        }
        public async Task FakeServer_ExpectPostWithBodyAndPostWithNullBody_ResponseIsNotFound()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Post(path, "jiberish").Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.PostAsync(path, null);

                resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
        public async Task FakeServer_ExpectGetWithQueryParametersReturnsString_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path?id=1234";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);

                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);

                result.Should().Be(expectedResult);
            }
        }
Esempio n. 34
0
        public void FakeServer_ExpectDeleteReturnsString_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Delete(url).Returns(expectedResult);
                fakeServer.Start();

                var result = new WebClient().UploadString(new Uri(baseAddress + url), "DELETE", string.Empty);

                result.Should().Be(expectedResult);
            }
        }
Esempio n. 35
0
        public async Task FakeServer_IgnoredParameterWithoutSlashAtTheStartOfUrlInRequest_Returns200()
        {
            var expectedResult = new { ResourceId = 1234 };

            const string fakepath   = "/some-resource/{ignore}/some-resource?date={ignore}&type={ignore}";
            const string actualpath = "some-resource/1234/some-resource?date=2015-02-06T09:52:10&type=1";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(fakepath).Returns(HttpStatusCode.Accepted, expectedResult);
                fakeServer.Start();

                var result = await fakeServer.Client.GetAsync(actualpath);

                result.StatusCode.Should().Be(HttpStatusCode.Accepted);
            }
        }
Esempio n. 36
0
        public async Task FakeServer_ExpectGetWithResponseHeadersSpecified_ResponseMatchesExpectionAndHasHeaders()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult, new WebHeaderCollection { { "foo", "bar" } });
                fakeServer.Start();

                var result = await fakeServer.Client.GetAsync(path);

                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
                result.Headers.Should().ContainSingle(x => x.Key == "foo");
            }
        }
        public async Task FakeServer_ExpectGetReturnsFileContent_ResponseMatchesExpectation()
        {
            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path)
                    .ReturnsFromFile(@"TestData\TestResponse.json");

                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);

                dynamic deserialised = JsonConvert.DeserializeObject(result);

                ((string)deserialised.name).Should().Be("Mick Hucknall");
            }
        }
Esempio n. 38
0
        public async Task FakeServer_ExpectGetReturnsObject_ResponseMatchesExpectation()
        {
            var expectedResult = new { RestaurantId = 1234 };

            const string path = "/restaurant/1234";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.GetStringAsync(path);
                var result = JsonConvert.DeserializeObject<dynamic>(resp);

                Assert.Equal(expectedResult.RestaurantId, (int)result.RestaurantId);
            }
        }
Esempio n. 39
0
        public void FakeServer_ExpectGetReturnsObject_ResponseMatchesExpectation()
        {
            var expectedResult = new { RestaurantId = 1234 };
            const string baseAddress = "http://localhost:12354";

            const string url = "/restaurant/1234";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(url).Returns(expectedResult);

                fakeServer.Start();

                var result = JsonConvert.DeserializeObject<dynamic>(new WebClient().DownloadString(new Uri(baseAddress + url)));

                Assert.Equal(expectedResult.RestaurantId, (int)result.RestaurantId);
            }
        }
Esempio n. 40
0
        public void FakeServer_ExpectGetWithQueryParametersReturnsString_ResponseMatchesExpectation()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";
            
            const string url = "/some-url?id=1234";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(url).Returns(expectedResult);

                fakeServer.Start();

                var uri = new Uri(baseAddress + url);
                var result = new WebClient().DownloadString(uri);

                result.Should().Be(expectedResult);
            }
        }
        public async Task FakeServer_ExpectPostWithPartialExpectedJsonBodyWithNestedElements_ResponseMatchesExpected()
        {
            const string expectedResult = "Some String Data";

            const string path = "/some-path";

            var content = new StringContent(@"{ Key: ""Value"", key2: { NestedKey1: ""NestedValue1"", NestedKey2: ""NestedValue2"" }, Key3: ""Value"" }");
            var expectedContent = @"{ Key: ""Value"", key2: { NestedKey1: ""NestedValue1"" } }";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Post(path, expectedContent).WithPartialJsonMatching().Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.PostAsync(path, content);
                var result = await resp.Content.ReadAsStringAsync();

                result.Should().Be(expectedResult);
            }
        }
        public async Task FakeServer_ExpectGetReturnsGeneratedTemplateFromPath_ResponseMatchesTemplate()
        {
            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path)
                    .ReturnsFromTemplate(@"TestData\TestTemplate.json", new { Id = 2343, UserId = 2343, UserEmail = "*****@*****.**" })
                    .RespondsIn(TimeSpan.FromSeconds(1))
                    .WithHttpStatus(HttpStatusCode.Accepted);

                fakeServer.Start();

                var result = await fakeServer.Client.GetStringAsync(path);

                dynamic deserialised = JsonConvert.DeserializeObject(result);

                ((int)deserialised.id).Should().Be(2343);
                ((int)deserialised.userId).Should().Be(2343);
                ((string)deserialised.userEmail).Should().Be("*****@*****.**");
            }
        }
Esempio n. 43
0
        public async Task FakeServer_ExpectGetWithHeadersSpecified_ResponseMatchesExpectionAndHasHeaders()
        {
            const string expectedResult = "Some String Data";

            var port = Ports.GetFreeTcpPort();

            var baseAddress = "http://localhost:" + port;

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(port))
            {
                fakeServer.Expect.Get(url).Returns(expectedResult, new WebHeaderCollection { { "foo", "bar" } });
                fakeServer.Start();

                var client = new HttpClient {BaseAddress = new Uri(baseAddress)};
                var result = await client.GetAsync(url);

                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
                result.Headers.Should().ContainSingle(x => x.Key == "foo");
            }
        }
Esempio n. 44
0
        public void FakeServer_IgnoredParameter_Returns200()
        {
            var expectedResult = new { ResourceId = 1234 };
            const string baseAddress = "http://localhost:12354";

            const string fakeurl = "/some-resource/{ignore}/some-resource?date={ignore}&type={ignore}";
            const string actualurl = "/some-resource/1234/some-resource?date=2015-02-06T09:52:10&type=1";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.Accepted, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().GetAsync(new Uri(baseAddress + actualurl));
                t.Wait();
                var result = t.Result;

                result.StatusCode.Should().Be(HttpStatusCode.Accepted);
            }
        }
Esempio n. 45
0
        public void FakeServer_ExpectPutWithObjectBodyReturns201_Returns201()
        {
            var expectedResult = new {RestaurantId = 1234};
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Put(url, string.Empty).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().PutAsync(new Uri(baseAddress + url), new StringContent(String.Empty));
                t.Wait();
                var result = t.Result;

                result.StatusCode.Should().Be(HttpStatusCode.Created);
            }
        }
Esempio n. 46
0
        public void FakeServer_ExpectPutWithComplexBodyReturnsComplexObject()
        {
            const string expectedResult = "{\"Complex\":{\"Property1\":1,\"Property2\":true}}";
            const string body = "{\"Complex\":1}";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Put("/some-url", body).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().PutAsync(new Uri("http://localhost:12354" + "/some-url"), new StringContent(body));
                t.Wait();
                var result = t.Result;

                var resultTask = result.Content.ReadAsStringAsync();
                resultTask.Wait();

                result.StatusCode.Should().Be(HttpStatusCode.Created);
                resultTask.Result.Should().Be(expectedResult);
            }
        }
Esempio n. 47
0
        public void FakeServer_ExpectPostWithMismatchingBody_Returns404()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Post(url, "jibberish").Returns(expectedResult);

                fakeServer.Start();

                var ex = Assert.Throws<WebException>(() => new WebClient().UploadString(new Uri(baseAddress + url), string.Empty));

                ((HttpWebResponse)ex.Response).StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 48
0
        public void FakeServer_ExpectGetWithMismatchingPath_Returns404()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get("/some-jibberish-url").Returns(expectedResult);

                fakeServer.Start();

                var ex = Assert.Throws<WebException>(() => new WebClient().DownloadString(new Uri(baseAddress + "/home")));

                ((HttpWebResponse)ex.Response).StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 49
0
        public void FakeServer_ShouldHandleMultipleRegistrationOnSameEndPoint_WithDifferentBodies_ReturnExpectedData()
        {
            var expectedResultA = "1234";
            var expectedResultB = "5678";

            const string baseAddress = "http://localhost:12354";
            const string fakeurl = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Post(fakeurl, "messageA").Returns(HttpStatusCode.OK, expectedResultA);
                fakeServer.Expect.Post(fakeurl, "messageB").Returns(HttpStatusCode.OK, expectedResultB);

                fakeServer.Start();

                var resultA = new WebClient().UploadString(new Uri(baseAddress + fakeurl), "POST", "messageA");
                var resultB = new WebClient().UploadString(new Uri(baseAddress + fakeurl), "POST", "messageB");

                resultA.Should().Be(expectedResultA);
                resultB.Should().Be(expectedResultB);
            }
        }
        public async Task FakeServer_ExpectGetWithRequestHeadersSpecified_WhenRequestHeadersNotProvided_ResponseIsBadRequest()
        {
            const string expectedResult = "X-Dummy1 header value not as expected.\r\n\tExpected: dummy1val\r\n\tProvided: other1val\r\nX-Dummy2 header was not provided.\r\n";

            var port = Ports.GetFreeTcpPort();

            var baseAddress = "http://localhost:" + port;

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(port))
            {
                var expectedRequestHeaders = new WebHeaderCollection
                {
                    {"X-Dummy1", "dummy1val"},  // will have different value
                    {"X-Dummy2", "dummy2val"},  // will be missing
                    {"X-Dummy3", "dummy3val"}   // will match
                };

                fakeServer.Expect.Get(url, expectedRequestHeaders).Returns(expectedResult);
                fakeServer.Start();

                var client = new HttpClient { BaseAddress = new Uri(baseAddress) };

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy1", "other1val");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-Dummy3", "dummy3val");

                var result = await client.GetAsync(url);

                result.StatusCode.Should().Be(HttpStatusCode.BadRequest);
                result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult);
            }
        }
Esempio n. 51
0
        public async Task FakeServer_ExpectPutWithNoBodyReturns201_Returns201()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Put(url, string.Empty).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var uri = new Uri(baseAddress + url);
                var result = await new HttpClient().PutAsync(uri, new StringContent(String.Empty));
                
                result.StatusCode.Should().Be(HttpStatusCode.Created);
            }
        }
Esempio n. 52
0
        public async Task FakeServer_CapturesAllRequests()
        {
            using (var fakeServer = new FakeServer())
            {
                fakeServer.Start();
                var baseAddress = fakeServer.BaseUri;
                
                var url1 = "/request1";
                var url2 = "/request2";
                var url3 = "/request3";
                var url4 = "/request4";

                var httpClient = new HttpClient();
                await httpClient.DeleteAsync(baseAddress + url1);
                await Repeat(() => httpClient.GetAsync(baseAddress + url2), 2);
                await Repeat(() => httpClient.PostAsync(baseAddress + url3, new StringContent(url3)), 3);
                await Repeat(() => httpClient.PutAsync(baseAddress + url4, new StringContent(url4)), 4);

                fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4);
            }
        }
Esempio n. 53
0
        public void FakeServer_ShouldExecuteResponseExpectationCallback_ReturnExpectedData()
        {
            const string expectedResult = "Some String Data";
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url?id=1234";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(url).Callback(() => new HttpResponseExpectation(HttpStatusCode.OK, expectedResult));

                fakeServer.Start();

                var result = new WebClient().DownloadString(new Uri(baseAddress + url));

                result.Should().Be(expectedResult);
            }
        }
Esempio n. 54
0
        public async Task FakeServer_ExpectGetWithMismatchingPath_Returns404()
        {
            const string expectedResult = "Some String Data";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get("/some-jibberish-path").Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.GetAsync("/home");

                resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 55
0
        public void FakeServer_ExpectGetToAnEndpointWithAFiveSecondResponseTime_ResponseTimeIsGreaterThanFiveSeconds()
        {
            var expectedResult = new { ResourceId = 1234 };
            const string baseAddress = "http://localhost:12354";
            var expectedResponseTime = TimeSpan.FromSeconds(5);

            const string fakeurl = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.ResponseTime = expectedResponseTime;
                fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.OK, expectedResult);
                fakeServer.Start();

                var stopwatch = Stopwatch.StartNew();

                var t = new HttpClient().GetAsync(new Uri(baseAddress) + fakeurl);
                t.Wait();

                stopwatch.Stop();

                stopwatch.Elapsed.Should().BeGreaterOrEqualTo(expectedResponseTime);
            }
        }
Esempio n. 56
0
        public async Task FakeServer_ExpectGetWithMismatchingMethod_Returns404()
        {
            const string expectedResult = "Some String Data";
            const string path = "/some-path";

            using (var fakeServer = new FakeServer())
            {
                fakeServer.Expect.Get(path).Returns(expectedResult);

                fakeServer.Start();

                var resp = await fakeServer.Client.PostAsync(path, new StringContent(string.Empty));

                resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
            }
        }
Esempio n. 57
0
        public async Task FakeServer_IgnoredParameterInRestfulUrl_Returns200()
        {
            var expectedResult = new { ResourceId = 1234 };
            const string baseAddress = "http://localhost:12354";

            const string fakeUrl = "/some-resource/{ignore}/some-method";
            const string actualUrl = "/some-resource/1234/some-method";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(fakeUrl).Returns(HttpStatusCode.Accepted, expectedResult);
                fakeServer.Start();

                var uri = new Uri(baseAddress + actualUrl);
                var result = await new HttpClient().GetAsync(uri);

                result.StatusCode.Should().Be(HttpStatusCode.Accepted);
            }            
        }