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); } }
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); } }
public IBucket GetBucketForKey(string key) { var config = new ClientConfiguration(); var fakeServer = new FakeServer(_connectionPool, null, null, _endPoint, new FakeIOService(_endPoint, _connectionPool, false)); var mockVBucket = new Mock<IVBucket>(); mockVBucket.Setup(x => x.LocatePrimary()).Returns(fakeServer); var mockKeyMapper = new Mock<IKeyMapper>(); mockKeyMapper.Setup(x => x.MapKey(key, It.IsAny<uint>())).Returns(mockVBucket.Object); var mockConfigInfo = new Mock<IConfigInfo>(); mockConfigInfo.Setup(x => x.GetKeyMapper()).Returns(mockKeyMapper.Object); mockConfigInfo.Setup(x => x.BucketConfig).Returns(_bucketConfig); mockConfigInfo.Setup(x => x.GetServer()).Returns(fakeServer); mockConfigInfo.Setup(x => x.IsDataCapable).Returns(true); mockConfigInfo.Setup(x => x.ClientConfig).Returns(new ClientConfiguration()); var mockController = new Mock<IClusterController>(); mockController.Setup(x => x.Configuration).Returns(config); mockController.Setup(x => x.CreateBucket("default", "", null)) .Returns(new CouchbaseBucket(mockController.Object, "default", _converter, _transcoder, null)); var cluster = new Cluster(config, mockController.Object); var bucket = cluster.OpenBucket("default", ""); //simulate a config event ((IConfigObserver)bucket).NotifyConfigChanged(mockConfigInfo.Object); return bucket; }
public IBucket GetBucketForKey(string key) { var config = new ClientConfiguration(); var fakeServer = new FakeServer(_connectionPool, null, null, _endPoint, new FakeIOStrategy(_endPoint, _connectionPool, false)); var mappedNode = new Mock<IMappedNode>(); mappedNode.Setup(x => x.LocatePrimary()).Returns(fakeServer); var mockKeyMapper = new Mock<IKeyMapper>(); mockKeyMapper.Setup(x => x.MapKey(key)).Returns(mappedNode.Object); var mockConfigInfo = new Mock<IConfigInfo>(); mockConfigInfo.Setup(x => x.GetKeyMapper()).Returns(mockKeyMapper.Object); mockConfigInfo.Setup(x => x.BucketConfig).Returns(_bucketConfig); mockConfigInfo.Setup(x => x.GetServer()).Returns(fakeServer); var mockController = new Mock<IClusterController>(); mockController.Setup(x => x.Configuration).Returns(config); mockController.Setup(x => x.CreateBucket("memcached", "")) .Returns(new MemcachedBucket(mockController.Object, "memcached", _converter, _transcoder)); var cluster = new Cluster(config, mockController.Object); var bucket = cluster.OpenBucket("memcached", ""); //simulate a config event ((IConfigObserver) bucket).NotifyConfigChanged(mockConfigInfo.Object); return bucket; }
public void EmptyStringExpr() { // Setup string input = "\'\' LIKE Map"; var filter = new Filter<FakeServer>(input); var s1 = new FakeServer() { Map = "" }; var s2 = new FakeServer() { Map = "ą" }; Assert.AreEqual(true, filter.Function(s1)); Assert.AreEqual(false, filter.Function(s2)); }
public void InvalidPropertyExpr() { // Setup string input = "\'tr-_ala%lala\' LIKE Kabanos"; var filter = new Filter<FakeServer>(input); var s1 = new FakeServer() { Map = "" }; var s2 = new FakeServer() { Map = "ą" }; Assert.AreEqual(true, filter.Function(s1)); Assert.AreEqual(true, filter.Function(s2)); }
public void InvalidPropertyGroupExpr() { // Setup string input = "(\'tr-_ala%lala\' LIKE Kabanos) OR (Map Like \'a\')"; var filter = new Filter<FakeServer>(input); var s1 = new FakeServer() { Map = "" }; var s2 = new FakeServer() { Map = "ą" }; var s3 = new FakeServer() { Map = "a" }; Assert.AreEqual(false, filter.Function(s1)); Assert.AreEqual(false, filter.Function(s2)); Assert.AreEqual(true, filter.Function(s3)); }
public void StringExprComplexPattern() { // Setup string input = @"(Map LIKE '\%\^%\_')"; var filter = new Filter<FakeServer>(input); var s1 = new FakeServer() { Map = "kabanosnos" }; var s2 = new FakeServer() { Map = @"%^_" }; var s3 = new FakeServer() { Map = "a" }; Assert.AreEqual(false, filter.Function(s1)); Assert.AreEqual(true, filter.Function(s2)); Assert.AreEqual(false, filter.Function(s3)); }
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 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.results.Length, 1); Assert.AreEqual(result.site.results[0].status, "ok"); Assert.AreEqual(result.site.results[0].data.getInfo.Name, "sub.ppu12-5.demo.pp.plesk.ru"); } }
public void NoLimit() { var query = new Query { Offset = 5 }; var server = new FakeServer(11); var streamer = new QueryStreamer(new RunQueryRequest { Query = query }, server.CreateApiCall(), null); AssertEntities(streamer, 5, 15); AssertLimits(server, null, null); AssertOffsets(server, 5, 0); }
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() }); } } }
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 void SetupFakeServer() { var sqliteDB = Create.TemporarySQLiteDB(); sqliteDB.RegisterDataObject(typeof(DBCraftedItem)); sqliteDB.RegisterDataObject(typeof(DBCraftedXItem)); sqliteDB.RegisterDataObject(typeof(ItemTemplate)); var fakeServer = new FakeServer(); fakeServer.SetDatabase(sqliteDB); GameServer.LoadTestDouble(fakeServer); AddOneCompleteRecipeToDatabase(); }
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); } }
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); } }
public void SimpleStringExpr() { // Setup string input = "\'%%ho sama\' LIKE Map"; var filter = new Filter<FakeServer>(input); // Go var s1 = new FakeServer(){ Map = "ho sama" }; var s2 = new FakeServer() { Map = "asdho sama" }; var s3 = new FakeServer() { Map = "asdHo samA" }; var s4 = new FakeServer() { Map = "Ho samĄ" }; Assert.AreEqual(true, filter.Function(s1)); Assert.AreEqual(true, filter.Function(s2)); Assert.AreEqual(true, filter.Function(s3)); Assert.AreEqual(false, filter.Function(s4)); }
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"); } }
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 void LimitAndOffset() { var query = new Query { Limit = 7, Offset = 5 }; var server = new FakeServer(4); var streamer = new QueryStreamer(new RunQueryRequest { Query = query }, server.CreateApiCall(), null); AssertEntities(streamer, 5, 7); AssertLimits(server, 7, 7, 4); AssertOffsets(server, 5, 1, 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); } }
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); } }
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); } }
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); } }
void BindView() { StartBtn = transform.Find("Button").GetComponent <Button>(); StartBtn.onClick.AddListener(delegate() { if (NetManager.USE_FAKE_SERVER) { FakeServer.GetInstance().StartGame(); } else { GameMain.GetInstance().netManager.TestConnect(); GameMain.GetInstance().netManager.SendLoginReq(); } }); }
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); } }
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 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); } }
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_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_ExpectGetToAnEndpointWithAFiveSecondResponseTime_ResponseTimeIsGreaterThanFiveSeconds() { var expectedResult = new { ResourceId = 1234 }; var expectedResponseTime = TimeSpan.FromSeconds(1); using (var fakeServer = new FakeServer()) { fakeServer.Expect.ResponseTime = expectedResponseTime; fakeServer.Expect.Get("/some-path").Returns(expectedResult).RespondsIn(TimeSpan.FromSeconds(5)).WithHttpStatus(HttpStatusCode.OK); fakeServer.Start(); // Do not use stopwatch: var elapsedTime = await CallFakeServerWithAccurateUtcTimer(fakeServer); elapsedTime.Should().BeGreaterOrEqualTo(expectedResponseTime); } }
public async Task TestNoAckFlow() { const string data = "The cuiqk brwon fox jumps over the zaly god."; var server = new FakeServer(SimulationMode.Success); var connection = new Connection(server.EndPoint, Connection.DefaultSocketFactory, BPool, RPool, 16, 16); const int correlationId = 379821; const byte ack = 1; var buffer = new ReusableMemoryStream(null); BigEndianConverter.Write(buffer, 4 + 4 + 1 + data.Length - 4); BigEndianConverter.Write(buffer, correlationId); buffer.WriteByte(ack); var s = Encoding.UTF8.GetBytes(data); buffer.Write(s, 0, s.Length); var bdata = buffer.ToArray(); var p = new TaskCompletionSource <Response>(); connection.Response += (con, cor, b) => p.SetResult(new Response { Connection = con, CorrelationId = cor, Data = b }); await connection.ConnectAsync(); buffer.Position = 8; buffer.WriteByte(0); await connection.SendAsync(correlationId, buffer, false); buffer = new ReusableMemoryStream(null); buffer.Write(bdata, 0, bdata.Length); buffer.Position = 8; buffer.WriteByte(1); await connection.SendAsync(correlationId, buffer, true); var r = await p.Task; server.Stop(); Assert.AreSame(connection, r.Connection); Assert.AreEqual(correlationId, r.CorrelationId); Assert.AreEqual(data, Encoding.UTF8.GetString(r.Data.ToArray())); }
public async Task FakeServer_ExpectGetWithResponseHeadersSpecifiedFluently_ResponseMatchesExpectionAndHasHeaders() { const string expectedResult = "Some String Data"; const string path = "/some-path"; using (var fakeServer = new FakeServer()) { fakeServer.Expect.Get(path).Returns(expectedResult).WithHeader("Content-Language", "es").WithHeader("Some-Header", "Header-McHeaderFace"); fakeServer.Start(); var result = await fakeServer.Client.GetAsync(path); result.Content.ReadAsStringAsync().Result.Should().Be(expectedResult); result.Headers.Should().ContainSingle(x => x.Key == "Some-Header"); } }
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); } }
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); } }
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 async Task TelemetryWorksWithConcurrentRequests() { this.MockHttpClientFixture.Reset(); var fakeServer = FakeServer.ForMockHandler(this.MockHttpClientFixture.MockHandler); fakeServer.Delay = TimeSpan.FromMilliseconds(20); var service = new BalanceService(this.StripeClient); // the first 2 requests will not contain telemetry await Task.WhenAll(service.GetAsync(), service.GetAsync()); // the following 2 requests will contain telemetry await Task.WhenAll(service.GetAsync(), service.GetAsync()); this.MockHttpClientFixture.MockHandler.Protected() .Verify( "SendAsync", Times.Exactly(2), ItExpr.Is <HttpRequestMessage>(m => !m.Headers.Contains("X-Stripe-Client-Telemetry")), ItExpr.IsAny <CancellationToken>()); this.MockHttpClientFixture.MockHandler.Protected() .Verify( "SendAsync", Times.Once(), ItExpr.Is <HttpRequestMessage>(m => TelemetryHeaderMatcher( m.Headers, (s) => s == "req_1", (d) => d >= 15)), ItExpr.IsAny <CancellationToken>()); this.MockHttpClientFixture.MockHandler.Protected() .Verify( "SendAsync", Times.Once(), ItExpr.Is <HttpRequestMessage>(m => TelemetryHeaderMatcher( m.Headers, (s) => s == "req_2", (d) => d >= 15)), ItExpr.IsAny <CancellationToken>()); }
public async Task 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 uri = new Uri(baseAddress + url); var result = await new HttpClient().PutAsync(uri, new StringContent(String.Empty)); result.StatusCode.Should().Be(HttpStatusCode.Created); } }
public void FakeServer_ExpectGetWithMismatchingMethod_Returns404() { const string expectedResult = "Some String Data"; const string baseAddress = "http://localhost:12354"; const string path = "/some-url"; using (var fakeServer = new FakeServer(12354)) { fakeServer.Expect.Get(path).Returns(expectedResult); fakeServer.Start(); var uri = new Uri(baseAddress + path); var ex = Assert.Throws <WebException>(() => new WebClient().UploadString(uri, string.Empty)); ((HttpWebResponse)ex.Response).StatusCode.Should().Be(HttpStatusCode.NotFound); } }
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); } }
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"); } }
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); } }
public async Task FakeServer_ExpectPutWithComplexBodyReturnsComplexObject() { const string expectedResult = "{\"Complex\":{\"Property1\":1,\"Property2\":true}}"; const string body = "{\"Complex\":1}"; using (var fakeServer = new FakeServer()) { fakeServer.Expect.Put("/some-path", body).Returns(HttpStatusCode.Created, expectedResult); fakeServer.Start(); var result = await fakeServer.Client.PutAsync("/some-path", new StringContent(body)); var content = await result.Content.ReadAsStringAsync(); result.StatusCode.Should().Be(HttpStatusCode.Created); content.Should().Be(expectedResult); } }
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); } }
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("*****@*****.**"); } }
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"); } }
public void issue12693_repro() { var recordCount = 50; var random = new Random(); var memoryStream = new MemoryStream(); var csvWriter = new CsvWriter(memoryStream); // create some dummy data to work with for (var record = 0; record < recordCount; ++record) { var dataRecord = new DataRecord(null); for (var value = 0; value < random.Next(100, 200); ++value) { dataRecord.Add("value" + random.Next(0, 100000)); } csvWriter.WriteRecord(dataRecord); } memoryStream.Position = 0; // create a fake server that will feed us our dummy data in dribs and drabs using (var fakeServer = new FakeServer(memoryStream)) using (var connectionToServer = new TcpClient("localhost", FakeServer.Port)) using (var csvReader = new CsvReader(connectionToServer.GetStream())) { while (csvReader.HasMoreRecords) { csvReader.ReadDataRecord(); } // when the bug manifests itself, the parser may stop parsing prematurely so the record counts won't match // see below for an explanation of how the bug is triggered Assert.Equal(recordCount, csvReader.RecordNumber); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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_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); } }