Files
KJD/test/HttpHelperAsyncSmoke.cs
2026-11-05 18:50:13 +08:00

69 lines
3.2 KiB
C#

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using CsharpHttpHelper;
internal static class HttpHelperAsyncSmoke
{
public static async Task Main()
{
await CheckRequests(false);
await CheckRequests(true);
}
private static async Task CheckRequests(bool asynchronous)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
string url = "http://" + listener.LocalEndpoint + "/";
var pending = asynchronous ? HttpHelper.PostAsync(url, "hello") : Task.Run(() => HttpHelper.Post(url, "hello"));
using (var client = await listener.AcceptTcpClientAsync())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true))
{
if (!reader.ReadLine().StartsWith("POST ", StringComparison.OrdinalIgnoreCase))
throw new Exception("Expected POST");
while (!string.IsNullOrEmpty(reader.ReadLine())) { }
var reply = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
stream.Write(reply, 0, reply.Length);
var body = new char[5];
if (reader.ReadBlock(body, 0, body.Length) != 5 || new string(body) != "hello")
throw new Exception("POST body mismatch");
reply = Encoding.ASCII.GetBytes("HTTP/1.1 400 Bad Request\r\nContent-Length: 7\r\nConnection: close\r\n\r\ninvalid");
stream.Write(reply, 0, reply.Length);
}
var result = await pending;
if (result.StatusCode != HttpStatusCode.BadRequest || result.Html != "invalid")
throw new Exception("Missing error response");
var get = asynchronous ? HttpHelper.GetAsync(url) : Task.Run(() => HttpHelper.Get(url));
using (var client = await listener.AcceptTcpClientAsync())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true))
{
if (!reader.ReadLine().StartsWith("GET ", StringComparison.OrdinalIgnoreCase))
throw new Exception("Expected GET");
while (!string.IsNullOrEmpty(reader.ReadLine())) { }
var reply = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 5\r\nConnection: close\r\n\r\n\uFEFFok");
stream.Write(reply, 0, reply.Length);
}
if ((await get).Html != "\uFEFFok") throw new Exception("Expected GET response to retain its BOM");
var item = new HttpItem { URL = url, Timeout = 250 };
var stalled = asynchronous ? HttpHelper.RequestAsync(item) : Task.Run(() => HttpHelper.Request(item));
if (await Task.WhenAny(stalled, Task.Delay(5000)) != stalled || string.IsNullOrEmpty((await stalled).Html))
throw new Exception("Expected a timeout result");
}
finally
{
listener.Stop();
}
}
}