public async Task UpdateAsync(BasketData currentBasket, string accessToken) { var request = new HttpRequestMessage(HttpMethod.Post, "api/v1/basket") { Content = JsonContent.Create(currentBasket) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); }
public async void Finds_patient_accounts_by_ids() { var client = _factory.CreateClient(); List <int> accountIds = new List <int>(); accountIds.Add(1); var content = JsonContent.Create(accountIds); var response = await client.PostAsync("user/patient/accounts", content); var responseString = await response.Content.ReadAsStringAsync(); Assert.Contains("\"id\":1", responseString); }
public async void Finds_rooms_by_ids() { var client = _factory.CreateClient(); List <int> ids = new List <int>(); ids.Add(1); var content = JsonContent.Create(ids); var response = await client.PostAsync("hospital/room", content); var responseString = await response.Content.ReadAsStringAsync(); Assert.Contains("\"id\":1", responseString); }
public async void Gets_doctors_by_ids() { var client = _factory.CreateClient(); List <int> doctorIds = new List <int>(); doctorIds.Add(1); var content = JsonContent.Create(doctorIds); var response = await client.PostAsync("user/doctor", content); string responseString = await response.Content.ReadAsStringAsync(); Assert.Contains("\"id\":1", responseString); }
public async Task HandlePatch_ShouldReturnOkWithLinks() { var entity = new DummyEntityFaker().Generate(); var client = api.CreateClient(); var result = await client.PatchAsync($"/dummies/{entity.Id}", JsonContent.Create(entity)); result.StatusCode.Should().Be(StatusCodes.Status200OK); var content = await result.Content.ReadFromJsonAsync <Response <DummyEntity> >(); content.Should().BeEquivalentTo(DummyResponse.GetResponse()); }
private static async Task <HttpResponseMessage> PostJsonContentAsync <T>(string uri, HttpClient httpClient, T obj, CancellationToken cancellationToken) { var postRequest = new HttpRequestMessage(HttpMethod.Post, uri) { Content = JsonContent.Create(obj) }; var postResponse = await httpClient.SendAsync(postRequest, cancellationToken); // postResponse.EnsureSuccessStatusCode(); return(postResponse); }
public async Task <Order?> PlaceNewOrderAsync(NewOrderParameters newOrder, CancellationToken cancellationToken = default) { using var client = _factory.CreateClient(ClientNames.TradingClient); var content = JsonContent.Create(newOrder, options: _serializerOptions); var response = await client.PostAsync(new Uri("/orders", UriKind.Relative), content, cancellationToken); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(cancellationToken); return(JsonSerializer.Deserialize <Order>(json, _serializerOptions)); }
async Task<TestResponse> StartTest(string testName, int solutionId, int testId, bool recheck) { var serviceConfig = _config.Tests[testName]; var isAlive = await CheckIfAlive(serviceConfig); if (isAlive) { var req = new TestRequest { SolutionId = solutionId, TestId = testId, ReCheck = recheck, }; using var httpClient = new HttpClient(); using var form = JsonContent.Create(req); var url = serviceConfig.GetFullTestLinkFrom(_config.TestingSystemWorker); HttpResponseMessage response = await httpClient.PostAsync(url, form); string apiResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { TestResponse testResponse = JsonConvert.DeserializeObject<TestResponse>(apiResponse); if (!testResponse.OK || testResponse.Result == ResultCode.IE) { return WriteTestResponseToDb(testResponse, solutionId, testId); } return testResponse; } else { return WriteTestResponseToDb(new TestResponse { OK = false, Message = "Container of " + testName + " replied with " + response.StatusCode, Result = ResultCode.IE, TestId = testId, }, solutionId, testId); } } else { return WriteTestResponseToDb(new TestResponse { OK = false, Message = "Container of " + testName + " Is Dead!", Result = ResultCode.IE, TestId = testId, }, solutionId, testId); } }
private static Task WithRequestBodyFailTestAsync(Method method) => ExecuteAsync( () => new HttpRequestMessage(method, "b500") { Content = JsonContent.Create(Value) }, async(nginxResponse, response) => { nginxResponse.IsSuccessStatusCode.Should().BeFalse(); (await nginxResponse.Content.ReadAsStringAsync()).Should().Be(Value); response.IsSuccessStatusCode.Should().BeFalse(); (await response.Content.ReadAsStringAsync()).Should().Be(Value); });
public async void HttpPostSendJsonTest() { var message = new Content { message = "teste_body" }; var json = JsonContent.Create(message); var result = await _client.Post().Url("http://localhost:3000/content") .AddJson <Content>(message) .Send(); uint statusCode = result.StatusCode(); Assert.Equal(200u, statusCode); }
protected async Task Put <T>(Uri path, T data, IDictionary <string, string>?queryParams = null) { var queryString = DictionaryToQueryString(queryParams); using (var content = JsonContent.Create <T>(data)) { var response = await HttpClient.PutAsync(path + queryString, content); if (!response.IsSuccessStatusCode) { throw await GetExceptionFromResponse(response); } } }
public async void Gets_prescriptions_via_advanced_search() { var client = _factory.CreateClient(); var content = JsonContent.Create(new PrescriptionAdvancedFilterDto { Name = "Brufen", Status = TimeStatus.All }); var response = await client.PostAsync("hospital/docsearch/prescription/advanced", content); var responseString = await response.Content.ReadAsStringAsync(); Assert.Contains("Brufen", responseString); }
public async void Schedules_examination() { var client = _factory.CreateClient(); var content = JsonContent.Create(new ScheduledExaminationDTO { DoctorId = 1, StartTime = new DateTime(2022, 3, 3, 8, 0, 0) }); content.Headers.Add("UserId", "1"); var response = await client.PostAsync("schedule/examination", content); response.EnsureSuccessStatusCode(); }
public async Task <DaprStateSetResult> SetAsync(IEnumerable <KeyValuePair <string, object> > states) { var response = await _httpClient.PostAsync( _stateStoreUri, JsonContent.Create(states) ); return(new DaprStateSetResult { StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, ErrorMessage = await response.Content.ReadAsStringAsync() }); }
public static async ValueTask <OperationResult <TResult> > PostAsync <TRequest, TResult>(this HttpClient client, string url, TRequest request, Certificate certificate, CancellationToken cancellation = default) { //var json = System.Text.Json.JsonSerializer.Serialize(request, request.GetType(), Json.Options); var content = JsonContent.Create(request, request.GetType(), null, Json.Options); if (certificate != null) { content.Headers.Add("Wechatpay-Serial", certificate.Code); } var response = await client.PostAsync(url, content, cancellation); return(await GetResultAsync <TResult>(response, cancellation)); }
public void JsonContentMediaTypeDefaultIfNull() { Type fooType = typeof(Foo); Foo foo = null; JsonContent content = JsonContent.Create(foo, fooType, mediaType: null); Assert.Equal("application/json", content.Headers.ContentType.MediaType); Assert.Equal("utf-8", content.Headers.ContentType.CharSet); content = JsonContent.Create(foo, mediaType: null); Assert.Equal("application/json", content.Headers.ContentType.MediaType); Assert.Equal("utf-8", content.Headers.ContentType.CharSet); }
/// <summary> /// 指定したユーザーをルームに追加します。 /// </summary> /// <param name="roomId">ルームのID</param> /// <param name="userEmails">ルームに追加するユーザーのEmailのリスト</param> /// <param name="httpClient">razorで注入したHttpClientインスタンス</param> /// <returns><追加後のルームの詳細/returns> public static async Task <RoomDetail> AddUsersToRoom(Guid roomId, List <string> userEmails, HttpClient httpClient) { var urlBuilder = new System.Text.StringBuilder(); urlBuilder.Append("Room/"); urlBuilder.Append(roomId); urlBuilder.Append("/User/"); var urlParts = urlBuilder.ToString(); var url = new System.Text.StringBuilder(urlParts); var response = await httpClient.PostAsync(url.ToString(), JsonContent.Create(userEmails)); return(await response.Content.ReadFromJsonAsync <RoomDetail>()); }
public async Task Post_sends_failure_notification_if_download_task_fails() { /* Arrange */ var fixture = new Fixture().Customize(new AutoMoqCustomization()); var newDownloadId = fixture.Create <DownloadJob.JobId>(); var downloadJobsDictionary = new DownloadJobsDictionary(); var fileSystemStub = CreateAndSetupFileSystemMock(fixture, newDownloadId); var notificationsHubContextMock = fixture.Create <Mock <IHubContext <NotificationsHub, NotificationsHub.IClient> > >(); var downloadHttpClientStub = fixture.Create <Mock <DelegatingHandler> >(); downloadHttpClientStub .Protected() .As <IProtectedDelegatingHandler>() .Setup(h => h.SendAsync( It.Is <HttpRequestMessage>(r => r.Method == HttpMethod.Get && r.RequestUri !.OriginalString == "https://download.stuff/file.iso"), It.IsAny <CancellationToken>())) .ThrowsAsync(new Exception("Something went wrong!")); using var client = CreateClient( newDownloadId, downloadJobsDictionary, fileSystemStub.Object, downloadHttpClientStub.Object, notificationsHubContextMock.Object); /* Act */ var response = await client.PostAsync( ApiDownloadRoute, JsonContent.Create( new DownloadController.PostRequestDto( "https://download.stuff/file.iso", "saveAsFile.iso"))); /* Assert */ response.IsSuccessStatusCode.Should().BeTrue(); var newDownload = downloadJobsDictionary[newDownloadId]; /* To observe the results we need to simulate completion of the downloading task */ await newDownload.DownloadTask.AwaitIgnoringExceptions(); notificationsHubContextMock.Verify(h => h.Clients.All.SendFailed( It.Is <NotificationsHub.FailedMessage>(m => m.Id == newDownloadId && m.Reason == "Something went wrong!"))); }
public async Task AddCache(string description, string latitude, string longitude) { var ding = _http.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, $"{_config.ApiEndpoint}{ADMIN}{ADDCACHE}"); request.Content = JsonContent.Create(new AddCacheRequest { Description = description, Latitude = latitude, Longitude = longitude, Hints = new List <string>() }); var res = await ding.SendAsync(request); if (res.IsSuccessStatusCode) { } }
public void JsonContent_CopyTo_Succeeds() { Person person = Person.Create(); using JsonContent content = JsonContent.Create(person); using MemoryStream stream = new MemoryStream(); // HttpContent.CopyTo internally calls overriden JsonContent.SerializeToStream, which is the targeted method of this test. content.CopyTo(stream, context: null, cancellationToken: default); stream.Seek(0, SeekOrigin.Begin); using StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); Assert.Equal(person.Serialize(JsonOptions.DefaultSerializerOptions), json); }
public async Task AddAnswer(string answerText) { var ding = _http.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, $"{_config.ApiEndpoint}{ADMIN}{ADDANSWER}"); request.Content = JsonContent.Create(new AddAnswerRequest { Answer = answerText }); var res = await ding.SendAsync(request); if (res.IsSuccessStatusCode) { } }
public async Task AddQuestion(int order, string questionText) { var ding = _http.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, $"{_config.ApiEndpoint}{ADMIN}{ADDQUESTION}"); request.Content = JsonContent.Create(new AddQuestionRequest { Order = order, Question = questionText }); var res = await ding.SendAsync(request); if (res.IsSuccessStatusCode) { } }
public async Task ExecuteAsync <T>(T command) where T : class, ICommand { // TODO Add security var postRequest = new HttpRequestMessage(HttpMethod.Post, _config.Uri) { Content = JsonContent.Create(command) // TODO: use newton soft }; using var client = new HttpClient(); var postResponse = await client.SendAsync(postRequest); postResponse.EnsureSuccessStatusCode(); }
public async void TestClientDeletePlayer() { var client = Factory.CreateClient(); var registerRequest = new HttpRequestMessage(HttpMethod.Post, "/api/player/CreatePlayer"); registerRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); registerRequest.Content = JsonContent.Create(new PlayerViewModel() { userName = "******", password = "******" }); var registerResponse = await client.SendAsync(registerRequest); var loginRequest = new HttpRequestMessage(HttpMethod.Post, "/api/player/Login"); loginRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); loginRequest.Content = JsonContent.Create(new PlayerViewModel() { userName = "******", password = "******" }); var loginResponse = await client.SendAsync(loginRequest); Assert.True(loginResponse.IsSuccessStatusCode); var thePlayer = await loginResponse.Content.ReadFromJsonAsync <Player>(); var logoutRequest = new HttpRequestMessage(HttpMethod.Put, "/api/player/Logout"); logoutRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); logoutRequest.Content = JsonContent.Create(thePlayer); var logoutResponse = await client.SendAsync(logoutRequest); var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, "/api/player/DeletePlayer"); deleteRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); deleteRequest.Content = JsonContent.Create(thePlayer); var deleteResponse = await client.SendAsync(deleteRequest); Assert.True(deleteResponse.IsSuccessStatusCode); var allRequest = new HttpRequestMessage(HttpMethod.Get, "/api/player/GetPlayers"); allRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); var allResponse = await client.SendAsync(allRequest); Assert.True(allResponse.IsSuccessStatusCode); var listPlayers = await allResponse.Content.ReadFromJsonAsync <List <Player> >(); Assert.Null(listPlayers.Find(p => p.playerId == thePlayer.playerId)); }
private static async Task Login() { System.Console.WriteLine("Please enter your account details: "); System.Console.Write("Enter username: "******"Enter password: "******"{Url}/auth/login")) { Content = JsonContent.Create(model) }; var response = await httpClient.SendAsync(postRequest); if (!response.IsSuccessStatusCode) { System.Console.WriteLine(await response.Content.ReadAsStringAsync()); return; } var content = await response.Content.ReadAsStringAsync(); var tokenDetails = JsonConvert.DeserializeObject <AuthDetails>(content); var currentUserInfo = new CurrentUserInfo() { Token = tokenDetails.Token, TokenExpiresIn = tokenDetails.ExpireDate, UserId = tokenDetails.UserId, Username = username }; System.Console.WriteLine("Logged in! Load current users - use 'list'"); File.WriteAllText(Config, JsonConvert.SerializeObject(currentUserInfo)); await LoadContacts(); }
public async Task CallValidApiEndpoint_DoesNotThrowException() { //Arrange var data = new List <ContactViewModel>(); data.Add(new ContactViewModel() { Id = Guid.NewGuid(), Name = "Test", Address = "Test" }); data.Add(new ContactViewModel() { Id = Guid.NewGuid(), Name = "Test", Address = "Test" }); var httpMessageHandler = new Mock <HttpMessageHandler>(); httpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns(Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = JsonContent.Create(data) })); HttpClient httpClient = new HttpClient(httpMessageHandler.Object); httpClient.BaseAddress = new Uri(@"http://api/valid/"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); IPolicyRegistry <string> mockRegistry = new PolicyRegistry(); IAsyncPolicy <HttpResponseMessage> httpRetryPolicy = Policy.NoOpAsync <HttpResponseMessage>(); IAsyncPolicy httpClientTimeoutExceptionPolicy = Policy.NoOpAsync(); mockRegistry.Add("SimpleHttpWaitAndRetry", httpRetryPolicy); mockRegistry.Add("HttpClientTimeout", httpClientTimeoutExceptionPolicy); var service = new UsingPolicyRegistryService(mockRegistry, httpClient); var exception = await Record.ExceptionAsync(() => service.WaitAndRetry()); // ASSERT Assert.Null(exception); }
public static Task <HttpResponseMessage> GetSignalRInfo( [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequestMessage req, [SecurityTokenValidation] SecurityTokenResult tokenResult, [SignalRConnectionInfo(HubName = Constants.HubName)] SignalRConnectionInfo connectionInfo) { return(tokenResult.Status == SecurityTokenStatus.Valid ? Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(connectionInfo) }) : Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent($"Validation result: {tokenResult.Status.ToString()}; Message: {tokenResult.Exception?.Message}") })); }
public async Task <Photo> UpdateAsync(Photo photo, string tokenValue) { var requestMessage = new HttpRequestMessage() { Method = new HttpMethod("PUT"), RequestUri = new Uri($"{http.BaseAddress.AbsoluteUri}/{photo.Id}"), Content = JsonContent.Create(photo) }; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenValue); var response = await http.SendAsync(requestMessage); return(await response.Content.ReadFromJsonAsync <Photo>()); }
public async void TestClientCreatePlayer() { var client = Factory.CreateClient(); var registerRequest = new HttpRequestMessage(HttpMethod.Post, "/api/player/CreatePlayer"); registerRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); registerRequest.Content = JsonContent.Create(new PlayerViewModel() { userName = "******", password = "******" }); var registerResponse = await client.SendAsync(registerRequest); Assert.True(registerResponse.IsSuccessStatusCode); }
public async void Create_ReturnsOK() { string org = "testOrg"; string app = "testApp"; string requestUri = $"{BasePath}/{org}/{app}/texts"; HttpResponseMessage response = await _httpClient.PostAsync( requestUri, JsonContent.Create(GetValidTextResource(), new MediaTypeHeaderValue("application/json"))); Assert.Equal(HttpStatusCode.OK, response.StatusCode); string content = response.Content.ReadAsStringAsync().Result; Assert.False(string.IsNullOrEmpty(content)); }