private static MockHttpClient<object> PerformGenericApiRequest(Action<HttpChannel> action) { var client = new MockHttpClient<object>(HttpStatusCode.OK); var channel = new HttpChannel(TestContext.Configuration, client); action(channel); return client; }
public void DiscoveredDevice_GetDeviceInfo_DoesNotMakeHttpRequestIfDataCached() { var publishedDevice = new SsdpRootDevice() { Location = new Uri("http://192.168.1.100:1702/description"), CacheLifetime = TimeSpan.FromMinutes(1), DeviceType = "TestDeviceType", Uuid = System.Guid.NewGuid().ToString() }; var discoveredDevice = new DiscoveredSsdpDevice(); discoveredDevice.Usn = "test usn"; discoveredDevice.AsAt = DateTimeOffset.Now; discoveredDevice.CacheLifetime = publishedDevice.CacheLifetime; discoveredDevice.DescriptionLocation = publishedDevice.Location; var client = new MockHttpClient(publishedDevice.ToDescriptionDocument()); var device = discoveredDevice.GetDeviceInfo(client).GetAwaiter().GetResult(); client = new MockHttpClient(publishedDevice.ToDescriptionDocument()); device = discoveredDevice.GetDeviceInfo(client).GetAwaiter().GetResult(); Assert.IsNull(client.LastRequest); Assert.AreEqual(device.Uuid, publishedDevice.Uuid); Assert.AreEqual(device.DeviceType, publishedDevice.DeviceType); }
public void Create_WhenProvidedWithRequest_CallsExpectedUrl() { var httpClient = new MockHttpClient<DonationStatus>(HttpStatusCode.OK); var api = ApiClient.Create<DonationApi, DonationStatus>(httpClient); api.RetrieveStatus(1); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/donation/{3}/status" , TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion, 1))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("GET")); }
public void Create_WhenProvidedWithRequest_CallsExpectedUrl() { var httpClient = new MockHttpClient<PageRegistrationConfirmation>(HttpStatusCode.OK); var api = ApiClient.Create<PageApi, PageRegistrationConfirmation>(httpClient); var response = api.Create(new RegisterPageRequest()); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/fundraising/pages" , TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("PUT")); }
public void Create_WhenProvidedWithNullRequest_ThrowsArgumentNullException() { var httpClient = new MockHttpClient<PageRegistrationConfirmation>(HttpStatusCode.OK); var api = ApiClient.Create<PageApi, PageRegistrationConfirmation>(httpClient); var exception = Assert.Throws<ArgumentNullException>(() => api.Create(null)); Assert.That(exception.ParamName, Is.StringContaining("request")); Assert.That(exception.Message, Is.StringContaining("Request cannot be null.")); }
public void IsPageShortNameRegistered_WhenProvidedWithNullOrEmptyPageShortName_ThrowsArgumentNullException(string pageShortName) { var httpClient = new MockHttpClient<PageRegistrationConfirmation>(HttpStatusCode.OK); var api = ApiClient.Create<PageApi, PageRegistrationConfirmation>(httpClient); var exception = Assert.Throws<ArgumentNullException>(() => api.IsPageShortNameRegistered(pageShortName, null)); Assert.That(exception.ParamName, Is.StringContaining("pageShortName")); Assert.That(exception.Message, Is.StringContaining("pageShortName cannot be null.")); }
public void ListAllPages_WhenProvidedWithEmail_CallsExpectedUrl() { var httpClient = new MockHttpClient<FundraisingPageSummaries>(HttpStatusCode.OK); var api = ApiClient.Create<AccountApi, FundraisingPageSummaries>(httpClient); const string email = "*****@*****.**"; api.ListAllPages(email); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/account/{3}/pages", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion, email))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("GET")); }
public void IsPageShortNameRegistered_WhenProvidedWithValidStringForPageShortName_CallsExpectedUrl(string domain) { var httpClient = new MockHttpClient<PageRegistrationConfirmation>(HttpStatusCode.OK); var api = ApiClient.Create<PageApi, PageRegistrationConfirmation>(httpClient); const string pageShortName = "someName"; api.IsPageShortNameRegistered(pageShortName, domain); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/fundraising/pages/{3}", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion, pageShortName))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("HEAD")); }
public void CreateAsync_WhenProvidedWithRequest_CallsExpectedUrl() { var httpClient = new MockHttpClient<AccountRegistrationConfirmation>(HttpStatusCode.OK); var api = ApiClient.Create<AccountApi, AccountRegistrationConfirmation>(httpClient); var request = new CreateAccountRequest(); api.CreateAsync(request, response => {}); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/account", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("PUT")); }
public void ListAllPages_ValidUserNameAndPassword_CallsExpectedUrl() { var client = new MockHttpClient<FundraisingPageSummaries>(HttpStatusCode.OK); var config = new ClientConfiguration("test") { Username = "******", Password = "******" }; var api = ApiClient.Create<PageApi, FundraisingPageSummaries>(config, client); api.ListAll(); var expected = string.Format( "{0}{1}/v{2}/fundraising/pages", config.RootDomain, config.ApiKey, config.ApiVersion); var url = client.LastRequestedUrl; Assert.AreEqual(expected, url); }
public void NetworkingModule_Request_Method() { var method = "GET"; var passed = false; var waitHandle = new AutoResetEvent(false); var httpClient = new MockHttpClient(request => { passed = request.Method.ToString() == method; waitHandle.Set(); return(new HttpResponseMessage(HttpStatusCode.NoContent)); }); var module = CreateNetworkingModule(httpClient, new MockInvocationHandler()); module.sendRequest(method, new Uri("http://example.com"), 1, null, null, "text", false, 1000); waitHandle.WaitOne(); Assert.IsTrue(passed); }
public async Task ReturnsMultipleHeaderInformation() { var mock = new MockHttpClient(); var headers = new HttpResponseHeaders(); headers["x-session-id"] = Guid.NewGuid().ToString(); headers.AcceptRanges.Add("none"); headers.AcceptRanges.Add("bytes"); headers.Location = new Uri("https://localhost/v1/customers/1"); mock.SetupGet("/").ReturnsAsync(headers); var result = await mock.Object.GetAsync("/"); Assert.Equal(headers.GetValues("x-session-id"), result.Headers.GetValues("x-session-id")); Assert.Equal(headers.AcceptRanges, result.Headers.AcceptRanges); Assert.Equal(headers.Location, result.Headers.Location); }
public TestHttpRepository() { var repo = new MockHttpClient(); repo.When(putRequest => putRequest.HasMethod(HttpMethod.Put)) .Then(async putRequest => { var requestString = await putRequest.Content.ReadAsStringAsync(); repo.When(HttpMethod.Get, putRequest.RequestUri) .Then(x => new HttpResponseMessage(HttpStatusCode.OK) .WithStringContent( requestString, mediaType: putRequest.Content.Headers.ContentType.MediaType)); return(new HttpResponseMessage(HttpStatusCode.OK)); }); repo.BaseAddress = new Uri("http://mockhttpclient.local"); Repo = repo; }
public async Task GetCurrentPlaybackInfo_AccessToken_GetJObjectInvokedWithAccessToken() { // arrange const string token = "abc123"; string json = JsonConvert.SerializeObject(new CurrentTrackPlaybackContext()); var http = new MockHttpClient(); http.SetupSendAsync(json); var service = new Mock <PlayerApi>(http.HttpClient, token) { CallBase = true }; // act await service.Object.GetCurrentPlaybackInfo(token); // assert service.Verify(s => s.GetJObject(It.IsAny <Uri>(), token)); }
public async Task Play_AccessToken_PutInvokedWithAccessToken() { // arrange const string token = "abc123"; var http = new MockHttpClient(); http.SetupSendAsync(); var service = new Mock <PlayerApi>(http.HttpClient, token) { CallBase = true }; // act await service.Object.Play(token); // assert service.Verify(s => s.Put(It.IsAny <Uri>(), It.IsAny <object>(), token)); }
public async Task GetTracks_UsernameAndPlaylistId_GetAccessTokenCalled() { // Arrange const string username = "******"; const string playlistId = "jkl012"; var mockHttp = new MockHttpClient(); mockHttp.SetupSendAsync("{\"Id\":\"def456\",\"Name\":\"ghi789\"}"); var mockAccounts = new MockAccountsService(); var api = new PlaylistsApi(mockHttp.HttpClient, mockAccounts.Object); // Act await api.GetTracks(username, playlistId); // Assert mockAccounts.Verify(a => a.GetAppAccessToken()); }
public async Task GetDevices_AccessToken_PutInvokedWithAccessToken() { // arrange const string token = "abc123"; string json = JsonConvert.SerializeObject(new { devices = new Device[] { new Device() } }); var http = new MockHttpClient(); http.SetupSendAsync(json); var service = new Mock <PlayerApi>(http.HttpClient, token) { CallBase = true }; // act await service.Object.GetDevices <dynamic>(token); // assert service.Verify(s => s.GetModelFromProperty <dynamic>(It.IsAny <Uri>(), It.IsAny <string>(), token)); }
public async Task GetRecommendations_2SeedTracks_UrlContainstracks() { // arrange string[] tracks = new[] { "trackabc123", "trackdef456" }; var http = new MockHttpClient(); var accounts = new MockAccountsService().Object; var api = new Mock <BrowseApi>(http.HttpClient, accounts) { CallBase = true }; api.Setup(a => a.GetModel <RecommendationsResult>(It.IsAny <string>(), null)).ReturnsAsync(new RecommendationsResult()); // act await api.Object.GetRecommendations(null, null, tracks); // assert api.Verify(a => a.GetModel <RecommendationsResult>("https://api.spotify.com/v1/recommendations?seed_tracks=trackabc123,trackdef456&", null)); }
public async Task When_json_predicate_pass_then_should_match() { // Arrange var client = new MockHttpClient(); client .When(x => x.Content.IsJson <TestDto>(i => i.Firstname == "Wayne" && i.IsMale == true)) .Then(HttpStatusCode.OK); // Act var result = await client.PostAsJsonAsync(new Uri("http://mockhttphandler.local"), new TestDto { Firstname = "Wayne", IsMale = true }); // Assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); }
public async Task PlayTracks_AccessToken_PutInvokedWithAccessToken() { // arrange const string token = "abc123"; const string trackUri = "spotify:track:7ouMYWpwJ422jRcDASZB7P"; var http = new MockHttpClient(); http.SetupSendAsync(); var service = new Mock <PlayerApi>(http.HttpClient, token) { CallBase = true }; // act await service.Object.PlayTracks(trackUri, token); // assert service.Verify(s => s.Put(It.IsAny <string>(), It.IsAny <object>(), token)); }
public async Task should_add_header_mix() { var client = new MockHttpClient(); client.When("*").Then(x => new HttpResponseMessage() .WithHeader("content-disposition", "inline") .WithHeader("warning", "110") .WithHeader("content-type", "application/json") .WithHeader("my-custom-header", "BOOM")); var request = new HttpRequestMessage(); request.RequestUri = new Uri("http://mockhttphandler.local"); var response = await client.SendAsync(request); Assert.Equal("inline", response.Content.Headers.GetValues("content-disposition").Single()); Assert.Equal("application/json", response.Content.Headers.GetValues("content-type").Single()); Assert.Equal("110", response.Headers.GetValues("warning").Single()); Assert.Equal("BOOM", response.Headers.GetValues("my-custom-header").Single()); }
public async Task MockHttpClientExceptionIsThrownIfUnmatchedResult() { var expected = "\n\nUnmatched setup result:\nStatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StringContent, Headers:\r\n{\r\n Content-Type: text/plain; charset=utf-8\r\n}\n"; var mock = new MockHttpClient(); var content = new StringContent("content"); mock.SetupPost("/api").ReturnsAsync(200).ReturnsAsync(404, content); var request = new SystemHttpRequestMessage(HttpMethod.Post, "/api"); request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); request.Content = new System.Net.Http.StringContent("actual body"); var result = await mock.Object.SendAsync(request); var exception = Assert.Throws <MockHttpClientException>(() => mock.VerifyAll()); Assert.Equal(ExceptionReasonTypes.UnmatchedResult, exception.Reason); Assert.Equal(expected, exception.Message); }
public async Task ShouldSendAsync() { //given await FHClient.Init(); var mock = new MockHttpClient(); FHHttpClientFactory.Get = () => mock; const string method = "POST"; //when await FHHttpClient.SendAsync(new Uri("http://localhost/test"), method, new Dictionary <string, string>() { { "key", "value" } }, "request-data", TimeSpan.FromSeconds(20)); //then Assert.IsNotNull(mock.Request); Assert.AreEqual(method, mock.Request.Method.Method); Assert.IsTrue(mock.Request.Headers.Contains("key")); Assert.AreEqual("\"request-data\"", await mock.Request.Content.ReadAsStringAsync()); Assert.AreEqual(20, mock.Timeout.Seconds); }
private static void ListenForTrainingStatus_Close(Assert assert) { var httpClient = new MockHttpClient(); var engineDto = new EngineDto { Id = "engine1" }; httpClient.Requests.Add(new MockRequest { Method = HttpRequestMethod.Get, Url = "translation/engines/project:project1", ResponseText = JsonConvert.SerializeObject(engineDto, RestClientBase.SerializerSettings) }); var buildDto = new BuildDto { Id = "build1", StepCount = 10 }; httpClient.Requests.Add(new MockRequest { Method = HttpRequestMethod.Get, Url = "translation/builds/engine:engine1?minRevision=0", Action = (body, ct) => Delay(1000, ct), ResponseText = JsonConvert.SerializeObject(buildDto, RestClientBase.SerializerSettings) }); var engine = new TranslationEngine("http://localhost/", "project1", httpClient); Action done = assert.Async(); engine.ListenForTrainingStatus( progress => { }, success => { assert.Equal(success, false); done(); }); engine.Close(); }
private static void Approve_Success(Assert assert) { string source = "En el principio la Palabra ya existía."; string prefix = "In the beginning the Word already existed."; MockHttpClient httpClient = CreateWebClient(); httpClient.Requests.Add(new MockRequest { Method = HttpRequestMethod.Post, Url = "translation/engines/project:project1/actions/trainSegment", Action = (body, ct) => { var segmentPair = JsonConvert.DeserializeObject <SegmentPairDto>(body, RestClientBase.SerializerSettings); var tokenizer = new LatinWordTokenizer(); assert.DeepEqual(segmentPair.SourceSegment, tokenizer.TokenizeToStrings(source).ToArray()); assert.DeepEqual(segmentPair.TargetSegment, tokenizer.TokenizeToStrings(prefix).ToArray()); return(Task.FromResult(true)); }, ResponseText = "" }); var engine = new TranslationEngine("http://localhost/", "project1", httpClient); Action done = assert.Async(); engine.TranslateInteractively(source, 0.2, session => { assert.NotEqual(session, null); session.Initialize(); session.UpdatePrefix(prefix); session.Approve(success => { assert.Ok(success); done(); }); }); }
public void BadStart() { var httpClient = MockHttpClient.Build("https://api.imgur.com/3") .ExpectHeaderPattern(".*", HttpRequestHeader.Authorization, $"Client-ID {ClientId}") .SetResponse("/credit", new MockHttpResponse { StatusCode = HttpStatusCode.GatewayTimeout }); var detectorTask = ImgurDetector.BuildAsync(ClientId, httpClient); detectorTask.Wait(); var detector = detectorTask.Result; Assert.Equal(expected: ImageDetectorState.BadNetwork, actual: detector.State); Thread.Sleep(4); httpClient.SetResponse("/credit", new MockHttpResponse { Content = DefaultCreditReponse }); mDetector.CheckStateAsync().Wait(); Assert.Equal(expected: ImageDetectorState.Good, actual: mDetector.State); }
public async Task HandleSecondHandshakeFailureCorrectly() { var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40"; var initialHandshakeClient = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK); var secondaryHandshakeClient = new MockHttpClient("", HttpStatusCode.RequestTimeout); var factoryMock = new Mock <IHttpClientFactory>(); factoryMock.SetupSequence(f => f.CreateHttpClient()) .Returns(initialHandshakeClient) .Returns(secondaryHandshakeClient); var socketFactoryMock = new Mock <IClientSocketFactory>(); var mediator = new SocketMediator("ws://localhost:7200/collections"); await AsyncAssert.Throws <HttpRequestException>( () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object)); Mock.VerifyAll(factoryMock); }
public async Task When_content_same_json_should_match() { // Arrange var testDto = new TestDto { Firstname = "Wayne", IsMale = true }; var client = new MockHttpClient(); client .When(x => x.Content.IsJson(testDto)) .Then(HttpStatusCode.OK); var content = JsonConvert.SerializeObject(testDto); // Act var result = await client.PostAsync(new Uri("http://mockhttphandler.local"), new StringContent(content)); // Assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); }
private static void Approve_SegmentInvalid(Assert assert) { string source = string.Join(" ", Enumerable.Repeat("palabra", TranslationEngine.MaxSegmentSize)) + "."; string prefix = string.Join(" ", Enumerable.Repeat("word", TranslationEngine.MaxSegmentSize)) + "."; MockHttpClient httpClient = CreateWebClient(); var engine = new TranslationEngine("http://localhost/", "project1", httpClient); Action done = assert.Async(); engine.TranslateInteractively(source, 0.2, session => { assert.NotEqual(session, null); session.Initialize(); assert.NotOk(session.IsSourceSegmentValid); session.UpdatePrefix(prefix); session.Approve(success => { assert.Ok(success); done(); }); }); }
public void DiscoveredDevice_GetDeviceInfo_MakesHttpRequest() { var publishedDevice = new SsdpRootDevice() { Location = new Uri("http://192.168.1.100:1702/description"), CacheLifetime = TimeSpan.FromMinutes(1), DeviceType = "TestDeviceType", Uuid = System.Guid.NewGuid().ToString() }; var discoveredDevice = new DiscoveredSsdpDevice(); discoveredDevice.Usn = "test usn"; discoveredDevice.AsAt = DateTimeOffset.Now; discoveredDevice.CacheLifetime = TimeSpan.FromSeconds(1); discoveredDevice.DescriptionLocation = publishedDevice.Location; var client = new MockHttpClient(publishedDevice.ToDescriptionDocument()); var device = discoveredDevice.GetDeviceInfo(client).GetAwaiter().GetResult(); Assert.IsNotNull(client.LastRequest); Assert.AreEqual(device.Uuid, publishedDevice.Uuid); Assert.AreEqual(device.DeviceType, publishedDevice.DeviceType); }
public async Task GetRecommendations_2SeedGenres_UrlContainsGenres() { // arrange string[] genres = new[] { "genreabc123", "genredef456" }; var http = new MockHttpClient(); var accounts = new MockAccountsService().Object; var api = new Mock <BrowseApi>(http.HttpClient, accounts) { CallBase = true }; api.Setup(a => a.GetModel <RecommendationsResult>(It.IsAny <Uri>(), null)) .ReturnsAsync(new RecommendationsResult()); // act await api.Object.GetRecommendations(null, genres, null); // assert api.Verify(a => a.GetModel <RecommendationsResult>( new Uri("https://api.spotify.com/v1/recommendations?seed_genres=genreabc123,genredef456"), null)); }
public async Task PushStream_HttpContentIntegrationTest() { // Arrange var expected = "Hello, world!"; using (var client = new MockHttpClient()) { // We mock the client, so this doesn't actually hit the web. This client will just echo back // the body content we give it. using ( var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:30000/") ) { request.Content = new PushStreamContent( (stream, content, context) => { using (var writer = new StreamWriter(stream)) { writer.Write(expected); } }, "text/plain" ); // Act using (var response = await client.SendAsync(request, CancellationToken.None)) { // Assert response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(expected, responseText); } } } }
public void CreateUserBinding_should_send_a_post_to_api_v2_user_bindings() { //given var userBinding = new UserBindingRequest() { TruCodeId = System.Guid.NewGuid().ToString(), UserIdentifier = "taco123" }; SetupMock(statusCode: HttpStatusCode.NoContent); //when sut.CreateUserBinding(userBinding); //then MockHttpClient.Verify(x => x.HandleRequest( It.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Post && req.RequestUri == new System.Uri("https://jones.net/api/v2/user_bindings") //&& req.Content.ToString().Contains(userBinding.TruCodeId.ToString()) ), It.IsAny <ApiCredentials>() ), Times.Exactly(1)); }
public async Task should_create_content_with_media_type() { var client = new MockHttpClient(); client.When("*").Then(x => new HttpResponseMessage() .WithJsonContent(new { FirstName = "John", LastName = "Doe", }, "application/vnd.mockhttphandler.local")); var request = new HttpRequestMessage(); request.RequestUri = new Uri("http://mockhttphandler.local"); var response = await client.SendAsync(request); var responseObj = JsonConvert.DeserializeObject <dynamic>(await response.Content.ReadAsStringAsync()); Assert.Equal(responseObj.FirstName.ToString(), "John"); Assert.Equal(responseObj.LastName.ToString(), "Doe"); Assert.Equal("application/vnd.mockhttphandler.local", response.Content.Headers.ContentType.MediaType); }
public async Task should_create_content_with_media_type() { var client = new MockHttpClient(); client.When("*").Then(x => new HttpResponseMessage() .WithXmlContent(new Name { FirstName = "John", LastName = "Doe", }, "application/vnd.mockhttphandler.local")); var request = new HttpRequestMessage(); request.RequestUri = new Uri("http://mockhttphandler.local"); var response = await client.SendAsync(request); var result = await response.Content.ReadAsStringAsync(); Assert.Contains("<FirstName>John</FirstName>", result); Assert.Contains("<LastName>Doe</LastName>", result); Assert.Equal("application/vnd.mockhttphandler.local", response.Content.Headers.ContentType.MediaType); }
public async Task MultipleReturnsSetupAsync() { var mock = new MockHttpClient(); var first = new StringContent("result"); var second = 201; mock.Setup <StringContent>(HttpMethod.Post, "/", content: x => x == "test") .ReturnsAsync(first) .ReturnsAsync(second); { var result = await mock.Object.PostAsync("/", new StringContent("test")); var actual = await result.Content.ReadAsStringAsync(); Assert.Equal(first, actual); } { var result = await mock.Object.PostAsync("/", new StringContent("test")); Assert.Equal(second, (int)result.StatusCode); } }
public void Ctor_UserNameAndPasswordSpecified_SetsBasicAuthenticationHeader() { var config = new ClientConfiguration("test") { Username = "******", Password = "******" }; var client = new MockHttpClient<object>(HttpStatusCode.OK); new HttpChannel(config, client); var header = client.Headers["Authorization"]; var credentials = new HttpBasicAuthCredentials("user", "pass").ToString(); Assert.That(header, Is.StringContaining("Basic " + credentials)); }
public static TApiClient Create <TApiClient, TResponse>(ClientConfiguration configuration, MockHttpClient <TResponse> httpClient) where TApiClient : ApiClientBase where TResponse : class, new() { var parent = new JustGivingClient(configuration, httpClient); var rtn = Activator.CreateInstance(typeof(TApiClient), parent.HttpChannel) as TApiClient; return(rtn); }
public void RequestPasswordReminder_WhenProvidedWithEmailAndDomain_CallsExpectedUrl() { const string email = "*****@*****.**"; const string domain = "www.tempori.org"; var httpClient = new MockHttpClient<object>(HttpStatusCode.OK); var api = ApiClient.Create<AccountApi, object>(new ClientConfiguration(TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion){WhiteLabelDomain = domain}, httpClient); api.RequestPasswordReminder(email); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/account/{3}/requestpasswordreminder?domain={4}", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion, email, domain))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("GET")); }
public async Task PushStream_HttpContentIntegrationTest() { // Arrange var expected = "Hello, world!"; using (var client = new MockHttpClient()) { // We mock the client, so this doesn't actually hit the web. This client will just echo back // the body content we give it. using (var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:30000/")) { request.Content = new PushStreamContent((stream, content, context) => { using (var writer = new StreamWriter(stream)) { writer.Write(expected); } }, "text/plain"); // Act using (var response = await client.SendAsync(request, CancellationToken.None)) { // Assert response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(expected, responseText); } } } }
public void AreCredentialsValid_WhenProvidedWithEmailAndPassword_CallsExpectedUrl() { var httpClient = new MockHttpClient<object>(HttpStatusCode.OK); var api = ApiClient.Create<AccountApi, object>(httpClient); const string email = "*****@*****.**"; const string password = "******"; api.AreCredentialsValid(email, password); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/account/validate", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("POST")); }
private static void TranslateInteractively_Success(Assert assert) { var httpClient = new MockHttpClient(); var resultDto = new InteractiveTranslationResultDto { WordGraph = new WordGraphDto { InitialStateScore = -111.111f, FinalStates = new[] { 4 }, Arcs = new[] { new WordGraphArcDto { PrevState = 0, NextState = 1, Score = -11.11f, Words = new[] { "This", "is" }, Confidences = new[] { 0.4f, 0.5f }, SourceSegmentRange = new RangeDto { Start = 0, End = 2 }, IsUnknown = false, Alignment = new[] { new AlignedWordPairDto { SourceIndex = 0, TargetIndex = 0 }, new AlignedWordPairDto { SourceIndex = 1, TargetIndex = 1 } } }, new WordGraphArcDto { PrevState = 1, NextState = 2, Score = -22.22f, Words = new[] { "a" }, Confidences = new[] { 0.6f }, SourceSegmentRange = new RangeDto { Start = 2, End = 3 }, IsUnknown = false, Alignment = new[] { new AlignedWordPairDto { SourceIndex = 0, TargetIndex = 0 } } }, new WordGraphArcDto { PrevState = 2, NextState = 3, Score = 33.33f, Words = new[] { "prueba" }, Confidences = new[] { 0.0f }, SourceSegmentRange = new RangeDto { Start = 3, End = 4 }, IsUnknown = true, Alignment = new[] { new AlignedWordPairDto { SourceIndex = 0, TargetIndex = 0 } } }, new WordGraphArcDto { PrevState = 3, NextState = 4, Score = -44.44f, Words = new[] { "." }, Confidences = new[] { 0.7f }, SourceSegmentRange = new RangeDto { Start = 4, End = 5 }, IsUnknown = false, Alignment = new[] { new AlignedWordPairDto { SourceIndex = 0, TargetIndex = 0 } } } } }, RuleResult = new TranslationResultDto { Target = new[] { "Esto", "es", "una", "test", "." }, Confidences = new[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }, Sources = new[] { TranslationSources.None, TranslationSources.None, TranslationSources.None, TranslationSources.Transfer, TranslationSources.None }, Alignment = new[] { new AlignedWordPairDto { SourceIndex = 0, TargetIndex = 0 }, new AlignedWordPairDto { SourceIndex = 1, TargetIndex = 1 }, new AlignedWordPairDto { SourceIndex = 2, TargetIndex = 2 }, new AlignedWordPairDto { SourceIndex = 3, TargetIndex = 3 }, new AlignedWordPairDto { SourceIndex = 4, TargetIndex = 4 } } } }; httpClient.Requests.Add(new MockRequest { Method = HttpRequestMethod.Post, ResponseText = JsonConvert.SerializeObject(resultDto, RestClientBase.SerializerSettings) }); var engine = new TranslationEngine("http://localhost/", "project1", httpClient); Action done = assert.Async(); engine.TranslateInteractively("Esto es una prueba.", 0.2, session => { assert.NotEqual(session, null); WordGraph wordGraph = session.SmtWordGraph; assert.Equal(wordGraph.InitialStateScore, -111.111); assert.DeepEqual(wordGraph.FinalStates.ToArray(), new[] { 4 }); assert.Equal(wordGraph.Arcs.Count, 4); WordGraphArc arc = wordGraph.Arcs[0]; assert.Equal(arc.PrevState, 0); assert.Equal(arc.NextState, 1); assert.Equal(arc.Score, -11.11); assert.DeepEqual(arc.Words.ToArray(), new[] { "This", "is" }); assert.DeepEqual(arc.WordConfidences.ToArray(), new[] { 0.4, 0.5 }); assert.Equal(arc.SourceSegmentRange.Start, 0); assert.Equal(arc.SourceSegmentRange.End, 2); assert.Equal(arc.IsUnknown, false); assert.Equal(arc.Alignment[0, 0], AlignmentType.Aligned); assert.Equal(arc.Alignment[1, 1], AlignmentType.Aligned); arc = wordGraph.Arcs[2]; assert.Equal(arc.IsUnknown, true); TranslationResult ruleResult = session.RuleResult; assert.DeepEqual(ruleResult.TargetSegment.ToArray(), new[] { "Esto", "es", "una", "test", "." }); assert.DeepEqual(ruleResult.WordConfidences.ToArray(), new[] { 0.0, 0.0, 0.0, 1.0, 0.0 }); assert.DeepEqual(ruleResult.WordSources.ToArray(), new[] { TranslationSources.None, TranslationSources.None, TranslationSources.None, TranslationSources.Transfer, TranslationSources.None }); assert.Equal(ruleResult.Alignment[0, 0], AlignmentType.Aligned); assert.Equal(ruleResult.Alignment[1, 1], AlignmentType.Aligned); assert.Equal(ruleResult.Alignment[2, 2], AlignmentType.Aligned); assert.Equal(ruleResult.Alignment[3, 3], AlignmentType.Aligned); assert.Equal(ruleResult.Alignment[4, 4], AlignmentType.Aligned); done(); }); }
public void RequestPasswordReminder_WhenProvidedWithEmail_CallsExpectedUrl() { var httpClient = new MockHttpClient<object>(HttpStatusCode.OK); var api = ApiClient.Create<AccountApi, object>(httpClient); const string email = "*****@*****.**"; api.RequestPasswordReminder(email); Assert.That(httpClient.LastRequestedUrl, Is.StringContaining(string.Format("{0}{1}/v{2}/account/{3}/requestpasswordreminder", TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion, email))); Assert.That(httpClient.LastRequest.Method, Is.StringContaining("GET")); }
public async Task LoadsAndStreamsDataCorrectly() { // 1. Initial handshake var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40"; var initialHandshakeClient = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK); var secondaryHandshakeResponse = "ok"; var secondaryHandshakeClient = new MockHttpClient(secondaryHandshakeResponse, HttpStatusCode.OK); var protocolUpgradeResponse = ""; var protocolUpgradeClient = new MockHttpClient(protocolUpgradeResponse, HttpStatusCode.SwitchingProtocols); protocolUpgradeClient.AddHeader("Sec-Websocket-Accept", "RWZIQcMHYHEyvemvvKIkivC1Tvo="); var finalHandshakeResponse = "15:40/collections,"; var finalHandshakeClient = new MockHttpClient(finalHandshakeResponse, HttpStatusCode.OK); var factoryMock = new Mock <IHttpClientFactory>(); factoryMock.SetupSequence(f => f.CreateHttpClient()) .Returns(initialHandshakeClient) .Returns(secondaryHandshakeClient) .Returns(protocolUpgradeClient) .Returns(finalHandshakeClient); var initialProbeResponse = Encoding.UTF8.GetBytes("3probe"); var secondaryProbeResponse = Encoding.UTF8.GetBytes("5"); // 2. Connection upgrade and handshake var socketMock = new Mock <IClientSocket>(); socketMock.Setup(s => s.ConnectAsync(It.IsAny <Uri>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); // The ws client handshake sends "2probe" and the server returns "3probe" socketMock.Setup(s => s.SendAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <WebSocketMessageType>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); // "3probe" response List <byte> initialProbeBytes = new List <byte>(initialProbeResponse); var originalBytes = initialProbeBytes.Count; var dataProvider = new MockSocketDataProvider(initialProbeBytes); socketMock.Setup(s => s.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <CancellationToken>())) .Returns((ArraySegment <byte> buffer, CancellationToken token) => { var writeResult = dataProvider.GetDataChunk(buffer.Array.Length); writeResult.buffer.CopyTo(buffer.Array, 0); return(MockSocketTaskFactory.CreateTask(initialProbeBytes.Count, writeResult.bytesWritten)); }); // This captures the mediator sending the value "5", can return the same thing socketMock.Setup(s => s.SendAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <WebSocketMessageType>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); var socketFactoryMock = new Mock <IClientSocketFactory>(); socketFactoryMock.Setup(f => f.CreateSocketClient()).Returns(socketMock.Object); var mediator = new SocketMediator("ws://localhost:7200/collections"); await mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object); Mock.VerifyAll(socketMock, socketFactoryMock, factoryMock); }
public void ListAll_WhenUsernameAuthenticationIsNull_ThrowsException() { var httpClient = new MockHttpClient<FundraisingPageSummaries>(HttpStatusCode.OK); var config = new ClientConfiguration(TestContext.ApiLocation, TestContext.ApiKey, TestContext.ApiVersion) { Password = "******" }; var api = ApiClient.Create<PageApi, FundraisingPageSummaries>(config, httpClient); var exception = Assert.Throws<Exception>(() => api.ListAll()); Assert.That(exception.Message, Is.StringContaining("Authentication required to list pages. Please set a valid configuration object.")); }
public void Setup() { _client = new MockHttpClient <CharitySearchResults>(HttpStatusCode.OK); _api = ApiClient.Create <SearchApi, CharitySearchResults>(_client); }
public void RetrieveAccount_ValidUserNameAndPassword_CallsExpectedUrl() { var client = new MockHttpClient<AccountDetails>(HttpStatusCode.OK); var config = new ClientConfiguration("test") { Username = "******", Password = "******" }; var api = ApiClient.Create<AccountApi, AccountDetails>(config, client); api.RetrieveAccount(); var expected = string.Format( "{0}{1}/v{2}/account/", config.RootDomain, config.ApiKey, config.ApiVersion); var url = client.LastRequestedUrl; Assert.AreEqual(expected, url); }