Both clients are written in house on HttpClient and ClientWebSocket, behind IMarketDataSource, with a rate limiter on the injected clock and retries that wait on it too. OKX: EUR pairs only (trap 14), rules from public/instruments, daily candles with bar=1Dutc and a refusal of any candle not opening at 00:00 UTC (trap 23), backwards paging of history-candles, errors read from the code field because OKX answers them with HTTP 200, tickers on the public stream and candles on the business stream with ping after silence. The HMAC signer and the demo header are ready for Phase 3. Alpaca: consolidated daily bars, real and adjusted, dated in New York and never newer than 15 minutes (trap 8), an explicit feed on every request, IEX for recent minutes, quotes and the stream (at most 30 symbols), calendar and clock converted to UTC, corporate actions. Without keys nothing is sent and the reason is stated. Tests use the documentation's examples and synthetic answers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
147 lines
4.6 KiB
C#
147 lines
4.6 KiB
C#
using System.Net;
|
|
using System.Text;
|
|
using System.Threading.Channels;
|
|
using Anubis.Brokers;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>Recorded responses saved under Fixtures/ (trap 12: no network in tests).</summary>
|
|
internal static class Fixture
|
|
{
|
|
public static string Path(string relative) => System.IO.Path.Combine(AppContext.BaseDirectory, "Fixtures", relative);
|
|
|
|
public static string Text(string relative) => File.ReadAllText(Path(relative));
|
|
|
|
public static byte[] Bytes(string relative) => File.ReadAllBytes(Path(relative));
|
|
}
|
|
|
|
/// <summary>
|
|
/// An HTTP handler that answers from a list of rules (first match wins) and records every request.
|
|
/// A request no rule matches fails the test with its address.
|
|
/// </summary>
|
|
internal sealed class FakeHttp : HttpMessageHandler
|
|
{
|
|
private readonly List<(Func<Uri, bool> Match, Func<HttpRequestMessage, HttpResponseMessage> Answer)> _rules = [];
|
|
|
|
public List<HttpRequestMessage> Requests { get; } = [];
|
|
|
|
public HttpClient Client() => new(this, disposeHandler: false);
|
|
|
|
public FakeHttp On(Func<Uri, bool> match, Func<HttpRequestMessage, HttpResponseMessage> answer)
|
|
{
|
|
_rules.Add((match, answer));
|
|
return this;
|
|
}
|
|
|
|
public FakeHttp On(string contains, string body, HttpStatusCode status = HttpStatusCode.OK) =>
|
|
On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => Respond(body, status));
|
|
|
|
public FakeHttp OnBytes(string contains, byte[] body) =>
|
|
On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) });
|
|
|
|
public static HttpResponseMessage Respond(string body, HttpStatusCode status = HttpStatusCode.OK) =>
|
|
new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
|
|
|
|
public IEnumerable<Uri> Urls => Requests.Select(r => r.RequestUri!);
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
lock (Requests)
|
|
{
|
|
Requests.Add(request);
|
|
}
|
|
|
|
foreach (var (match, answer) in _rules)
|
|
{
|
|
if (match(request.RequestUri!))
|
|
{
|
|
return Task.FromResult(answer(request));
|
|
}
|
|
}
|
|
|
|
throw new AssertFailedException("Unexpected request: " + request.RequestUri);
|
|
}
|
|
}
|
|
|
|
/// <summary>A WebSocket that plays messages pushed by the test and records what the client sends.</summary>
|
|
internal sealed class FakeSocket : IWebSocketTransport
|
|
{
|
|
private readonly Channel<string?> _incoming = Channel.CreateUnbounded<string?>();
|
|
|
|
public Uri? Url { get; private set; }
|
|
|
|
public IReadOnlyDictionary<string, string>? Headers { get; private set; }
|
|
|
|
public List<string> Sent { get; } = [];
|
|
|
|
public TaskCompletionSource Connected { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
public bool Disposed { get; private set; }
|
|
|
|
public void Push(string message) => _incoming.Writer.TryWrite(message);
|
|
|
|
/// <summary>The server closes the connection.</summary>
|
|
public void Close() => _incoming.Writer.TryWrite(null);
|
|
|
|
public Task ConnectAsync(Uri url, IReadOnlyDictionary<string, string>? headers, CancellationToken cancellationToken)
|
|
{
|
|
Url = url;
|
|
Headers = headers;
|
|
Connected.TrySetResult();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task SendAsync(string text, CancellationToken cancellationToken)
|
|
{
|
|
lock (Sent)
|
|
{
|
|
Sent.Add(text);
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken) =>
|
|
await _incoming.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
Disposed = true;
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
}
|
|
|
|
/// <summary>A clock whose waits finish at once by moving time forward: back-offs and rate limits cost nothing in tests.</summary>
|
|
internal sealed class FastClock(DateTimeOffset start) : Anubis.Core.IClock
|
|
{
|
|
private readonly Lock _gate = new();
|
|
private DateTimeOffset _now = start;
|
|
|
|
public DateTimeOffset UtcNow
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _now;
|
|
}
|
|
}
|
|
}
|
|
|
|
public TimeSpan Waited { get; private set; }
|
|
|
|
public Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (dueUtc > _now)
|
|
{
|
|
Waited += dueUtc - _now;
|
|
_now = dueUtc;
|
|
}
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|