public async Task CustomerTriesRegisterWithGoogle_InvalidOrExpiredAuthToken_ErrorReturned() { var customerManagementClient = new Mock <ICustomerManagementServiceClient>(); var googleApiClient = new Mock <IGoogleApi>(); googleApiClient.Setup(x => x.GetGoogleUser(It.IsAny <string>())) .ThrowsAsync( ApiException.Create(new HttpRequestMessage(HttpMethod.Get, "a"), HttpMethod.Get, new HttpResponseMessage(HttpStatusCode.Unauthorized)).Result); var customerProfileClient = new Mock <ICustomerProfileClient>(); var customerService = new CustomerService( customerManagementClient.Object, customerProfileClient.Object, googleApiClient.Object, _dictionariesClientMock.Object, _mapper); var actual = await customerService.GoogleRegisterAsync( new GoogleRegistrationRequestDto { AccessToken = MockAccessToken }); Assert.Equal(CustomerError.InvalidOrExpiredGoogleAccessToken, actual.Error); }
protected async Task <T> PostStreamData <T>(string urlString, string Name, Stream Data) { var uri = new Uri(urlString); MultipartFormDataContent form = new MultipartFormDataContent(); HttpContent content = new StringContent(Name); content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); form.Add(content, Name); content = new StreamContent(Data); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = Name, FileName = Name }; form.Add(content); using (var resp = await _client.PostAsync(uri, form).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(uri, HttpMethod.Post, resp).ConfigureAwait(false); } var responseContent = await resp.Content.ReadAsStringAsync(); return(DeserializeObject <T>(responseContent)); } }
public async Task <T> Add(T item) { HttpResponseMessage response = await httpClient.PostAsJsonAsync(name + "?" + UrlArgsUtil.makeArgs(args), item); return((response.IsSuccessStatusCode) ? await response.Content.ReadAsAsync <T>() : throw ApiException.Create(await response.Content.ReadAsAsync <ErrorType>())); }
public async Task <T> Get(int id) { HttpResponseMessage response = await httpClient.GetAsync(name + "/" + id + "?" + UrlArgsUtil.makeArgs(args)); return((response.IsSuccessStatusCode) ? await response.Content.ReadAsAsync <T>() : throw ApiException.Create(await response.Content.ReadAsAsync <ErrorType>())); }
public async Task Update(int id, T item) { HttpResponseMessage response = await httpClient.PutAsJsonAsync(name + "/" + id + "?" + UrlArgsUtil.makeArgs(args), item); if (!response.IsSuccessStatusCode) { throw ApiException.Create(await response.Content.ReadAsAsync <ErrorType>()); } }
public static async Task <CreateDocumentsResponse> Execute(HttpClient http, CreateDocumentsRequest request) { var responseMessage = await http.PostAsJsonAsync("Documents/CreateWithTemplate", request); if (!responseMessage.IsSuccessStatusCode) { throw await ApiException.Create(responseMessage); } return(await responseMessage.Content.ReadAsAsync <CreateDocumentsResponse>()); }
public static async Task <DocumentSignersResponse> Execute(HttpClient http) { var responseMessage = await http.GetAsync("documentsigners/list"); if (!responseMessage.IsSuccessStatusCode) { throw await ApiException.Create(responseMessage); } return(await responseMessage.Content.ReadAsAsync <DocumentSignersResponse>()); }
public static async Task <DocumentStatusResponse> Execute(HttpClient http, int documentId) { var responseMessage = await http.GetAsync("Documents/Status?id=" + documentId); if (!responseMessage.IsSuccessStatusCode) { throw await ApiException.Create(responseMessage); } return(await responseMessage.Content.ReadAsAsync <DocumentStatusResponse>()); }
public static Mock <IIoasysApiAdapterClient> CreateScenarioThrowEnterpriseCoreExceptionForId() { var mockIoasysAdapter = new Mock <IIoasysApiAdapterClient>(); mockIoasysAdapter.Setup(x => x.ShowEnterpriseById(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Throws(ApiException.Create(new System.Net.Http.HttpRequestMessage(), new System.Net.Http.HttpMethod("GET"), new System.Net.Http.HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.NotFound }, null).Result); return(mockIoasysAdapter); }
public async Task <List <T> > GetAll(bool deleted) { Dictionary <string, string> args = new Dictionary <string, string>(this.args); args.Add("deleted", deleted.ToString()); HttpResponseMessage response = await httpClient.GetAsync(name + "?" + UrlArgsUtil.makeArgs(args)); return((response.IsSuccessStatusCode) ? await response.Content.ReadAsAsync <List <T> >() : throw ApiException.Create(await response.Content.ReadAsAsync <ErrorType>())); }
public static async Task <ApiException> CreateException(string url, HttpMethod method, HttpStatusCode statusCode, string jsonContent = null) { var response = new HttpResponseMessage { StatusCode = statusCode, Content = string.IsNullOrWhiteSpace(jsonContent) ? null : new StringContent(jsonContent, Encoding.UTF8, "application/json"), RequestMessage = new HttpRequestMessage(method, url) }; return(await ApiException.Create(response.RequestMessage, method, response)); }
public async Task GoogleAuthAsync_InvalidOrExpiredAccessToken_ErrorReturned() { _googleApiMock.Setup(x => x.GetGoogleUser(It.IsAny <string>())) .ThrowsAsync( ApiException.Create(new HttpRequestMessage(HttpMethod.Get, "a"), HttpMethod.Get, new HttpResponseMessage(HttpStatusCode.Unauthorized)).Result); var sut = CreateSutInstance(); var result = await sut.GoogleAuthenticateAsync(FakeAccessToken); Assert.Equal(CustomerError.InvalidOrExpiredGoogleAccessToken, result.Error); }
protected async Task <T> GetData <T>(Uri uri) { using (var resp = await _client.GetAsync(uri).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(uri, HttpMethod.Get, resp).ConfigureAwait(false); } var content = await resp.Content.ReadAsStringAsync(); return(DeserializeObject <T>(content)); } }
public async Task Test3() { var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound); var exception = await ApiException.Create(new HttpRequestMessage(), HttpMethod.Get, responseMessage, new RefitSettings()); var apiResponse = new ApiResponse <PlacesApiResponse>(responseMessage, null, new RefitSettings(), exception); var provider = new PlaceInfoProvider(this.placesApiClientMock.Object, this.repositoryMock.Object); this.SetupApiClientGetPlaceInfoAsyncMethod(apiResponse); var result = await provider.GetPlaceInfoAsync(this.placeInfo.Iata !, CancellationToken.None); result.Should().BeOfType <Result <IataPoint> >(); result.IsFailure.Should().Be(true); }
public async Task <AuthSession> Login(Account account) { HttpResponseMessage response = await httpClient.PostAsJsonAsync <Account>(NAME + "\\login", account); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsAsync <AuthSession>()); } else { ErrorType errorType = await response.Content.ReadAsAsync <ErrorType>(); throw ApiException.Create(errorType); } }
public async Task ReturnsErrorIfTranslationFailsAsync() { using var request = new HttpRequestMessage(); using var response = new HttpResponseMessage(HttpStatusCode.InternalServerError); var exception = ApiException.Create(request, HttpMethod.Get, response, new RefitSettings()).Result; Api .Setup(x => x.GetShakespeareanTranslation(It.IsAny <string>())) .ThrowsAsync(exception); var result = await Service.GetShakespeareanTranslation("dummy"); Assert.Null(result.Result); Assert.NotNull(result.Exception); Assert.Same(exception, result.Exception); }
public async Task When_MakePayment_Then_ResponseIsUnsuccessful() { var(request, _) = PaymentInitialiser.InitialiseRequest("4485920504392908", 5, 2024, 199.99m); IBank bank = Substitute.For <IBank>(); bank .When(b => b.CreatePayment(Arg.Is <Payment>(p => p.Amount > 100m))) .Do(b => { throw ApiException.Create(Substitute.For <HttpRequestMessage>(), HttpMethod.Post, Substitute.For <HttpResponseMessage>(), Substitute.For <RefitSettings>()).Result; }); var service = new PaymentService(bank); var response = await service.MakePayment(new Payment { Amount = 199.99m }, request.Card); response.Rejected.ShouldBeTrue(); }
protected async Task <T> DeleteData <T>(string urlString) { var uri = new Uri(urlString); using (var resp = await _client.DeleteAsync(uri).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(uri, HttpMethod.Delete, resp).ConfigureAwait(false); } var responseContent = await resp.Content.ReadAsStringAsync(); return(DeserializeObject <T>(responseContent)); } }
public static async Task <DocumentTemplatesResponse> Execute(HttpClient http, int pageSize, int pageIndex, bool filterAccess) { var uri = QueryHelpers.AddQueryString("documenttemplates/list", new Dictionary <string, string> { { "pageSize", pageSize.ToString() }, { "pageIndex", pageIndex.ToString() }, { "filterAccess", filterAccess.ToString() } }); var responseMessage = await http.GetAsync(uri); if (!responseMessage.IsSuccessStatusCode) { throw await ApiException.Create(responseMessage); } return(await responseMessage.Content.ReadAsAsync <DocumentTemplatesResponse>()); }
public async Task Get_UserNotFound_ReturnsNull() { var exception = await ApiException.Create( null, null, new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound } ); A.CallTo(() => Client.Get(UserId, AccessToken.Value)) .ThrowsAsync(exception); var user = await ClientWrapper.Get(UserId); Assert.Null(user); }
protected async Task <T> PostData <T, E>(string urlString, E Data) { var uri = new Uri(urlString); var json = JsonConvert.SerializeObject(Data); var requestContent = new StringContent(json, Encoding.UTF8, "application/json"); using (var resp = await _client.PostAsync(uri, requestContent).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(uri, HttpMethod.Post, resp).ConfigureAwait(false); } var responseContent = await resp.Content.ReadAsStringAsync(); return(DeserializeObject <T>(responseContent)); } }
public async Task CalculoService_BuscarTaxaJuro_DeveBuscarComErroNaoTrato() { // Arrange var exception = await ApiException.Create(new HttpRequestMessage(), HttpMethod.Get, new HttpResponseMessage(HttpStatusCode.InternalServerError), new RefitSettings()); var taxaJuroAPI = Substitute.For<ITaxaJuroAPI>(); taxaJuroAPI.GetAsync().Throws(exception); // Act Func<Task> resultado = async () => await taxaJuroAPI.GetAsync(); // Assert (await resultado.Should().ThrowAsync<ApiException>()) .Where(x => x.Content == null && x.StatusCode == HttpStatusCode.InternalServerError); }
public async Task <ApiResult <T> > PostAsync <T>(Uri uri, HttpContent content) { ApiResult <T> result; try { result = await _decorated.PostAsync <T>(uri, content).ConfigureAwait(false); } catch (Exception ex) { InternalLogger.LogException(ex); result = new ApiResult <T> { Exception = ApiException.Create(ex) }; } return(result); }
public async Task <GetSummonerByNameResponse> GetSummonerByName(string summonerName) { if (ShouldThrow) { var apiException = await ApiException.Create(new HttpRequestMessage(), HttpMethod.Get, new HttpResponseMessage(), null);; throw apiException; } var summoner = new GetSummonerByNameResponse() { AccountId = "9OnF1YN-vTD7-vzFmVafiDk31yudiaRF1V9RaQR-ygE", ProfileIconId = 4568, RevisionDate = 1620858743000, Name = "Kaelsin", Id = "M_uI3RI7JlQlY2kZXz4LuvmR7ilm6OlvPKcJHfycM7ih", Puuid = "6WWJyoBhf9xdkCAWnypkUcy08U7lQORIPWqymtUf-7v_NWqqCfry7P5Eotgh-gJBDkejlX4eP_MLLg", SummonerLevel = 107 }; return(summoner); }
public ApiResult <T> Post <T>(Uri uri, HttpContent content) { ApiResult <T> result; try { result = _decorated.Post <T>(uri, content); } catch (Exception ex) { InternalLogger.LogException(ex); result = new ApiResult <T> { Exception = ApiException.Create(ex) }; } return(result); }
public async void NonVoidMethod_ExecutedWithFailure_ItShouldBeExecutedFourTimes() { var apiException = await ApiException.Create(new Uri("http://www.google.pl"), HttpMethod.Get, new HttpResponseMessage(System.Net.HttpStatusCode.NotFound)); _mockedDecoratedRestService.Setup(x => x.Execute <IRestMockedApi>(api => api.AnotherSampleRestMethod())) .Callback(() => executedRestNonVoidMethodCount++) .ThrowsAsync(apiException); try { await _systemUnderTest.Execute <IRestMockedApi>(api => api.AnotherSampleRestMethod()); } catch (Exception) { } Assert.AreEqual(4, executedRestNonVoidMethodCount, "Method has not been called four times (1 normal execution + 3 retry)"); }
public static async Task <Guid> Execute(HttpClient http, Stream pdf, string fileName) { using (var content = new MultipartFormDataContent()) using (var fileContent = new StreamContent(pdf)) { fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; content.Add(fileContent); var responseMessage = await http.PostAsync("Documents/Post", content); if (!responseMessage.IsSuccessStatusCode) { throw await ApiException.Create(responseMessage); } var response = await responseMessage.Content.ReadAsStringAsync(); return(Guid.Parse(response.Trim('"'))); } }
private ApiResult <T> ReadResult <T>(HttpResponseMessage response) { string stringResponse = response.Content.ReadAsStringAsync().Result; ApiResult <T> result = new ApiResult <T> { ResponseContent = stringResponse, StatusCode = (int)response.StatusCode }; if (response.IsSuccessStatusCode == false) { result.Exception = ApiException.Create(stringResponse); } else { if (!string.IsNullOrEmpty(stringResponse)) { result.Result = KissLogConfiguration.JsonSerializer.Deserialize <T>(stringResponse); } } return(result); }
private static async Task <SetResult <T> > generateSetResult <T>(int start, int limit, bool count, HttpResponseMessage httpResponseMessage) { var setResult = new SetResult <T>(); setResult.Start = start; setResult.Limit = limit; try { var content = httpResponseMessage.Content ?? new StringContent(string.Empty); if (!httpResponseMessage.IsSuccessStatusCode) { var apiException = await ApiException.Create(httpResponseMessage.RequestMessage, httpResponseMessage.RequestMessage.Method, httpResponseMessage).ConfigureAwait(false); //if (apiException.HasContent) //{ // //var serverExceptionModel = JsonConvert.DeserializeObject<ErrorModel>(apiException.Content); // //var requestId = httpResponseMessage.GetHeaderValue(HttpHeader.XMnsRequestId); // //var serverException = new DDYServerException(serverExceptionModel.Code, serverExceptionModel.Message, requestId, apiException.StatusCode); // //throw serverException; // var errorModel = JsonConvert.DeserializeObject<ErrorModel>(apiException.Content); // var requestId = httpResponseMessage.GetHeaderValue(HttpHeader.XMnsRequestId); // var intStatusCode = (int)apiException.StatusCode; // if (intStatusCode >= 400 && intStatusCode < 500) // { // throw new DDYClientException(errorModel.Code, errorModel.Message, requestId, apiException.StatusCode); // } // else if (intStatusCode >= 500) // { // throw new DDYServerException(errorModel.Code, errorModel.Message, requestId, apiException.StatusCode); // } //} throw apiException; } using (var stream = await content.ReadAsStreamAsync().ConfigureAwait(false)) using (var reader = new StreamReader(stream)) { using (var jsonReader = new JsonTextReader(reader)) { var serializer = JsonSerializer.Create(); var datas = serializer.Deserialize <IEnumerable <T> >(jsonReader); setResult.Datas = datas; setResult.Count = datas.Count(); if (count) { var totalCountStr = httpResponseMessage.GetHeaderValue(HttpHeader.XMnsTotalCount); if (int.TryParse(totalCountStr, out var totalCount)) { setResult.TotalCount = totalCount; } } } } } finally { } return(setResult); }
private static async Task <ApiException> GetRefitException(HttpStatusCode statusCode) => await ApiException.Create(null, null, new HttpResponseMessage(statusCode));