using System.Text; using Flypaper.Core.Models; using Flypaper.Core.Strategies; using Flypaper.Tests.Fakes; using Shouldly; namespace Flypaper.Tests.Core; public sealed class HtmlDripStrategyTests { [Fact] public async Task Drips_html_in_small_chunks_until_cancelled() { var strategy = CreateStrategy(); var channel = new FakeTrapChannel(); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); channel.Writes.Count.ShouldBeGreaterThan(5); channel.Writes.ShouldAllBe(write => write.Length >= 1 && write.Length <= 64); Encoding.UTF8.GetString(channel.Writes.SelectMany(write => write).ToArray()).ShouldStartWith(""); } [Fact] public async Task Sends_head_start_without_delay_before_dripping() { var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30), HeadStartSize = 1024 }; var strategy = new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(21), TimeProvider.System); var channel = new FakeTrapChannel(); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); channel.Writes.Count.ShouldBe(2); var head = channel.Writes.First(); head.Length.ShouldBeGreaterThanOrEqualTo(1024); Encoding.UTF8.GetString(head).ShouldStartWith(""); } [Fact] public async Task Skips_head_start_when_disabled() { var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30), HeadStartSize = 0 }; var strategy = new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(21), TimeProvider.System); var channel = new FakeTrapChannel(); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); channel.Writes.Count.ShouldBe(1); channel.Writes.First().Length.ShouldBeLessThanOrEqualTo(64); } [Theory] [InlineData(1024, "html-drip 5-10ms 1-64B head 1024B")] [InlineData(0, "html-drip 5-10ms 1-64B")] public void Describe_marks_the_head_start_variant(int headStart, string expected) { var options = new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(10), HeadStartSize = headStart }; new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(1), TimeProvider.System).Describe().ShouldBe(expected); } [Theory] [InlineData(TrapProtocol.Http, true)] [InlineData(TrapProtocol.Ssh, false)] public void Supports_only_http(TrapProtocol protocol, bool expected) => CreateStrategy().Supports(protocol).ShouldBe(expected); private static HtmlDripStrategy CreateStrategy() => new( TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5), HeadStartSize = 0 }), new SeededRandomSource(21), TimeProvider.System); }