private async Task <TokenResponse> GetTokenAsync() { var now = DateTime.Now.Second; var response = await _httpClient.GetAsync($"{Endpoints.GetToken}{now}").As <dynamic>(); var csrfToken = (string)response.token; response = await _httpClient.GetAsync(Endpoints.ValidateToken) .WithHeader("Cookie", $"csrf_token={csrfToken}") .As <dynamic>(); var multiPart = new MultipartFormDataContent(); multiPart.Add(new StringContent(csrfToken), ":cq_csrf_token"); multiPart.Add(new StringContent(_username), "username"); multiPart.Add(new StringContent(_password), "password"); multiPart.Add(new StringContent("https://owners.hyundaiusa.com/us/en/index.html"), "url"); var strResponse = await _httpClient.PostAsync(Endpoints.Auth) //.WithHeader("Cookie", $"csrf_token={csrfToken}") .WithBody(multiPart).AsString(); //.As<string>(); var responseJson = JsonConvert.DeserializeObject <dynamic>(strResponse); var tokenJObj = (JObject)responseJson.Token; return(tokenJObj.ToObject <TokenResponse>()); }
public void Retry_success() { // Arrange the Http client var mockHttp = new MockHttpMessageHandler(); // First attempt, we return HTTP 429 which means TOO MANY REQUESTS mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); // Second attempt, we return the expected result mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}"); var httpClient = new HttpClient(mockHttp); // Arrange the Request coordinator var coordinator = new RetryCoordinator( 2, (response) => response.StatusCode == (HttpStatusCode)429, (attempts, response) => TimeSpan.Zero); // Arrange the fluent htpp client var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient) .SetRequestCoordinator(coordinator); // Act var result = fluentClient .GetAsync("endpoint") .As <JObject>() .Result; // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); Assert.That(result.Value <string>("name"), Is.EqualTo("This is a test")); }
public static async Task <JObject> GetRequest(FluentClient client, string uri, CancellationToken cancellationToken) { return(await client .GetAsync(uri) .WithCancellationToken(cancellationToken) .AsRawJsonObject()); }
public void Retry_failure() { // Arrange the Http client var mockHttp = new MockHttpMessageHandler(); // Three successive HTTP 429 (which mean TOO MANY REQUESTS) mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); var httpClient = new HttpClient(mockHttp); // Arrange the Request coordinator var coordinator = new RetryCoordinator( 3, (response) => response.StatusCode == (HttpStatusCode)429, (attempts, response) => TimeSpan.Zero); // Arrange the fluent http client var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient) .SetRequestCoordinator(coordinator); // Act Assert.ThrowsAsync <ApiException>(async() => await fluentClient.GetAsync("endpoint").As <JObject>()); // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); }
protected async Task <T> GetAsync <T>(string url) { using (var client = new FluentClient(baseUri)) { return(await client.GetAsync(url).As <T>()); } }
public void WhenIRequestPostWithId(int id) { //act response = client.GetAsync(b => b .AppendPath("posts") .AppendPath(id.ToString())).Result; }
public async Task PostApiTestMethod() { var userModelObj = new UserModel() { FirstName = "Kishor", LastName = "Naik" }; IClient client = new FluentClient("http://localhost:49506/api/users"); // Post Work //var data = // await // client // .PostAsync<UserModel>("postdemo", userModelObj) // .As<UserModel>(); //// Post Array Work //var data = // await // client // .PostAsync("postdemoarray") // .As<List<UserModel>>(); var data = await client .GetAsync("getdemo/11") .As <int>(); Assert.IsNotNull(data); }
public async Task <string> GetToken() { using (var fluentClient = new FluentClient($"{Addresses.ServerUrl}api/")) { //TODO: Use hash return(await(await fluentClient.GetAsync($"Authentication/terminal/hash/testing")).As <string>()); } }
public async Task RetriesOnTimeout([Values(true, false)] bool retryOnTimeout) { // configure const int maxAttempts = 3; // two test requests in non-retry mode // set up int attempts = 0; var mockHandler = new MockHttpMessageHandler(); mockHandler.When(HttpMethod.Get, "*").With(req => ++ attempts == maxAttempts).Respond(HttpStatusCode.OK); // succeed on last attempt mockHandler.When(HttpMethod.Get, "*").Respond(async request => { await Task.Delay(TimeSpan.FromSeconds(10)); Assert.Fail("The request unexpectedly didn't time out."); return(null); }); IClient client = new FluentClient("https://example.org", new HttpClient(mockHandler)) .SetRequestCoordinator(this.GetRetryConfig(maxAttempts - 1, retryOnTimeout)); client.BaseClient.Timeout = TimeSpan.FromMilliseconds(500); // execute & verify if (retryOnTimeout) { IResponse response = await client.GetAsync(""); Assert.AreEqual(maxAttempts, attempts, "The client did not retry the expected number of times."); Assert.AreEqual(HttpStatusCode.OK, response.Status, "The response is unexpectedly not successful."); } else { // make sure timeout is treated as a normal error Assert.ThrowsAsync <ApiException>(async() => await client.GetAsync(""), "The request unexpectedly didn't fail."); Assert.AreEqual(1, attempts, "The client unexpectedly retried."); // validate response when errors-as-exceptions is disabled IResponse response = await client.GetAsync("").WithOptions(ignoreHttpErrors: true); Assert.AreEqual(this.TimeoutStatusCode, response.Status, "The response has an unexpected status code."); } }
//Devuelve los tipos de origen public async Task <Types> getSourceTypes() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.SourceTypes) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Types>(); return(rest); } }
//Devuelve el estado de los procesos. public async Task <Status> getStatusProcesses() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.ProcessesStatus) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Status>(); return(rest); } }
public void Request_Url_WhenInvalid(string baseUrl, string url) { // arrange var mockHttp = new MockHttpMessageHandler(); mockHttp.When(HttpMethod.Get, "*").Respond(HttpStatusCode.OK, req => new StringContent(req.RequestUri.ToString())); var fluentClient = new FluentClient(baseUrl, new HttpClient(mockHttp)); // assert Assert.ThrowsAsync <FormatException>(async() => await fluentClient.GetAsync(url).AsString()); }
//Devuelve un esquema con un id específico. public async Task <Schema> getSchemaId(string id) { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.SchemasId + id) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Schema>(); return(rest); } }
//Verifica si la tarea de promover un schema se está ejecutando public async Task <PromoteSchema> getPromoteSchema() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.PromoteSchema) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <PromoteSchema>(); return(rest); } }
public async Task <string> Request_Url(string baseUrl, string url) { // arrange var mockHttp = new MockHttpMessageHandler(); mockHttp.When(HttpMethod.Get, "*").Respond(HttpStatusCode.OK, req => new StringContent(req.RequestUri.ToString())); var fluentClient = new FluentClient(baseUrl, new HttpClient(mockHttp)); // act return(await fluentClient.GetAsync(url).AsString()); }
//Retorna una lista de fondos filtrado por id public async Task <Funds> searchFunds(string id) { string url = String.Format(Config.Funds + Config.FilterId, null, id); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Funds>(); return(rest); } }
//Devuelve la lista completa de fields. public async Task <FieldsList> getFields(string schema) { string url = String.Format(Config.Fields, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <FieldsList>(); return(rest); } }
// Retorna la lista de Símbolos (UnderlyingSymbol) de Instrumentos financieros public async Task <ReferenceDataSymbolsList> getReferenceDataSymbols(string schema) { string url = String.Format(Config.OData + Config.RDSymbols, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <ReferenceDataSymbolsList>(); return(rest); } }
// Retorna la lista de Sociedades Depositarias o Custodia de Fondos public async Task <CustodiansList> getCustodians(string schema) { string url = String.Format(Config.OData + Config.Depositary, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <CustodiansList>(); return(rest); } }
//Retorna la lista de instrumentos filtrados por Id public async Task <ODataList> getODataReferenceDatasById(string id, string schema) { string url = String.Format(Config.OData + Config.FilterId, schema, id); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <ODataList>(); return(rest); } }
//Retorna los instrumentos que contengan una cadena de búsqueda como parte del id. public async Task <Instruments> searchInstruments(string cfg, string id, string schema) { string url = String.Format(cfg + Config.FilterId, schema, id); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Instruments>(); return(rest); } }
//Retorna un titulo valor por id public async Task <Securitie> getSecuritie(string id) { string url = String.Format(Config.Securitie, id); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Securitie>(); return(rest); } }
//Retorna una lista de instruments. public async Task <Instruments> getInstruments(string cfg, string type, string source, string schema) { string url = API.getUrl(cfg, type, source, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Instruments>(); return(rest); } }
//Retorna una lista de derivados public async Task <Derivatives> getDerivatives(string market, string symbol) { string url = API.getUrlDerivatives(market, symbol); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Derivatives>(); return(rest); } }
//Retorna una especificación del estado actual. public async Task <Specification> getSpecification(string schema) { string url = String.Format(Config.Specification, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Specification>(); return(rest); } }
//Devuelve un source field con un id específico. public async Task <SourceField> getSourceField(string id, string schema) { string url = String.Format(Config.SourceField, schema, id); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <SourceField>(); return(rest); } }
//Retorna una lista de fondos public async Task <Funds> getFunds(string managment, string depositary, string currency, string rent) { string url = API.getUrlFunds(managment, depositary, currency, rent); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Funds>(); return(rest); } }
public void AbandonsOnTooManyFailures() { // arrange const int maxAttempts = 2; var mockHttp = new MockHttpMessageHandler(); var mockRequest = mockHttp.When(HttpMethod.Get, "*").Respond(HttpStatusCode.NotFound); var client = new FluentClient(new Uri("http://example.org"), new HttpClient(mockHttp)) .SetRequestCoordinator(this.GetRetryConfig(maxAttempts - 1)); // act & assert Assert.ThrowsAsync <ApiException>(async() => await client.GetAsync("")); Assert.AreEqual(maxAttempts, mockHttp.GetMatchCount(mockRequest), "The client did not retry the expected number of times."); }
//Retorna la lista de instrumentos financieros. public async Task <ReferenceDatas> getReferenceDatas(string cfg, string type, string schema) { string url = (type != null) ? String.Format(cfg + Config.FilterTypeStr, schema, type) : String.Format(cfg, schema); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <ReferenceDatas>(); return(rest); } }
//Retorna una lista de títulos valores public async Task <Securities> getSecurities(string id) { string url = (id != null) ? String.Format(Config.Securities + Config.FilterId, null, id) : String.Format(Config.Securities); using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + url) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Securities>(); return(rest); } }