cs-codex-dist-tests/DistTestCore/Http.cs

102 lines
2.8 KiB
C#
Raw Normal View History

2023-04-12 11:53:55 +00:00
using Newtonsoft.Json;
using NUnit.Framework;
using System.Net.Http.Headers;
2023-04-13 07:33:10 +00:00
using Utils;
2023-04-12 11:53:55 +00:00
namespace DistTestCore
{
public class Http
{
private readonly string ip;
private readonly int port;
private readonly string baseUrl;
public Http(string ip, int port, string baseUrl)
{
this.ip = ip;
this.port = port;
this.baseUrl = baseUrl;
if (!this.baseUrl.StartsWith("/")) this.baseUrl = "/" + this.baseUrl;
if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/";
}
public string HttpGetString(string route)
{
return Retry(() =>
{
using var client = GetClient();
var url = GetUrl() + route;
2023-04-13 07:33:10 +00:00
var result = Time.Wait(client.GetAsync(url));
return Time.Wait(result.Content.ReadAsStringAsync());
2023-04-12 11:53:55 +00:00
});
}
public T HttpGetJson<T>(string route)
{
return JsonConvert.DeserializeObject<T>(HttpGetString(route))!;
}
public string HttpPostStream(string route, Stream stream)
{
return Retry(() =>
{
using var client = GetClient();
var url = GetUrl() + route;
var content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
2023-04-13 07:33:10 +00:00
var response = Time.Wait(client.PostAsync(url, content));
2023-04-12 11:53:55 +00:00
2023-04-13 07:33:10 +00:00
return Time.Wait(response.Content.ReadAsStringAsync());
2023-04-12 11:53:55 +00:00
});
}
public Stream HttpGetStream(string route)
{
return Retry(() =>
{
var client = GetClient();
var url = GetUrl() + route;
2023-04-13 07:33:10 +00:00
return Time.Wait(client.GetStreamAsync(url));
2023-04-12 11:53:55 +00:00
});
}
private string GetUrl()
{
return $"http://{ip}:{port}{baseUrl}";
}
private static T Retry<T>(Func<T> operation)
{
var retryCounter = 0;
while (true)
{
try
{
return operation();
}
catch (Exception exception)
{
Timing.HttpCallRetryDelay();
retryCounter++;
if (retryCounter > Timing.HttpCallRetryCount())
{
Assert.Fail(exception.Message);
throw;
}
}
}
}
private static HttpClient GetClient()
{
var client = new HttpClient();
client.Timeout = Timing.HttpCallTimeout();
return client;
}
}
}