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

96 lines
2.6 KiB
C#
Raw Normal View History

2023-03-21 07:23:15 +00:00
using Newtonsoft.Json;
using NUnit.Framework;
using System.Net.Http.Headers;
2023-03-21 12:20:21 +00:00
namespace CodexDistTestCore
2023-03-21 07:23:15 +00:00
{
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 T HttpGetJson<T>(string route)
{
return Retry(() =>
{
using var client = GetClient();
var url = GetUrl() + route;
var result = Utils.Wait(client.GetAsync(url));
var json = Utils.Wait(result.Content.ReadAsStringAsync());
return JsonConvert.DeserializeObject<T>(json)!;
});
}
public string HttpPostStream(string route, Stream stream)
{
2023-03-21 12:20:21 +00:00
return Retry(() =>
2023-03-21 07:23:15 +00:00
{
using var client = GetClient();
var url = GetUrl() + route;
var content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = Utils.Wait(client.PostAsync(url, content));
return Utils.Wait(response.Content.ReadAsStringAsync());
});
}
public Stream HttpGetStream(string route)
{
return Retry(() =>
{
var client = GetClient();
var url = GetUrl() + route;
return Utils.Wait(client.GetStreamAsync(url));
});
}
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)
{
retryCounter++;
if (retryCounter > Timing.HttpCallRetryCount())
{
Assert.Fail(exception.Message);
throw;
}
}
}
}
private static HttpClient GetClient()
{
var client = new HttpClient();
client.Timeout = Timing.HttpCallTimeout();
return client;
}
}
}