89 lines
2.4 KiB
C#
89 lines
2.4 KiB
C#
using NUnit.Framework;
|
|
using Sarand.Net.Standard.Base.Net;
|
|
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using ZstdNet;
|
|
|
|
namespace Sacs.UnitTests.Net.Standard.Base.Net
|
|
{
|
|
[TestFixture]
|
|
public class SacsHttpClient_Tester
|
|
{
|
|
// --- Zstandard Responses ---
|
|
|
|
[Test]
|
|
public async Task DoRequest_DecompressesZstandardResponse()
|
|
{
|
|
const string responseText = "Zstandard response content: £12.34";
|
|
byte[] compressedData;
|
|
using (Compressor compressor = new Compressor())
|
|
compressedData = compressor.Wrap(Encoding.UTF8.GetBytes(responseText));
|
|
|
|
TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
try
|
|
{
|
|
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
Task serverTask = SendResponse(listener, compressedData);
|
|
SacsHttpRequestData requestData = new SacsHttpRequestData(null)
|
|
{
|
|
Url = $"http://127.0.0.1:{port}/zstd"
|
|
};
|
|
|
|
SacsHttpResponseData response = await SacsHttpClient.DoRequest(requestData);
|
|
await serverTask;
|
|
|
|
Assert.That(response.Success, Is.True);
|
|
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
|
Assert.That(response.Exception, Is.Null);
|
|
Assert.That(response.Data, Is.EqualTo(responseText));
|
|
Assert.That(response.ContentHeaders["Content-Encoding"], Does.Contain("zstd"));
|
|
}
|
|
finally
|
|
{
|
|
listener.Stop();
|
|
}
|
|
}
|
|
|
|
// --- Test Support ---
|
|
|
|
private static async Task SendResponse(TcpListener listener, byte[] compressedData)
|
|
{
|
|
using (TcpClient client = await listener.AcceptTcpClientAsync())
|
|
using (NetworkStream stream = client.GetStream())
|
|
{
|
|
await ReadRequestHeaders(stream);
|
|
byte[] headers = Encoding.ASCII.GetBytes(
|
|
"HTTP/1.1 200 OK\r\n" +
|
|
"Content-Encoding: zstd\r\n" +
|
|
"Content-Type: text/plain; charset=utf-8\r\n" +
|
|
$"Content-Length: {compressedData.Length}\r\n" +
|
|
"Connection: close\r\n\r\n");
|
|
|
|
await stream.WriteAsync(headers);
|
|
await stream.WriteAsync(compressedData);
|
|
}
|
|
}
|
|
|
|
private static async Task ReadRequestHeaders(Stream stream)
|
|
{
|
|
byte[] buffer = new byte[1];
|
|
int matchedBytes = 0;
|
|
byte[] terminator = "\r\n\r\n"u8.ToArray();
|
|
|
|
while (matchedBytes < terminator.Length && await stream.ReadAsync(buffer) > 0)
|
|
{
|
|
matchedBytes = buffer[0] == terminator[matchedBytes]
|
|
? matchedBytes + 1
|
|
: buffer[0] == terminator[0] ? 1 : 0;
|
|
}
|
|
}
|
|
|
|
// --- The End ---
|
|
}
|
|
}
|