Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 39 additions & 7 deletions src/Tests/Sa.Media.FFmpegTests/CodecProbe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,52 @@ private static async Task CheckEncoder(string encoderName, CancellationToken tok
{
var codecs = await IFFMpegExecutor.Default.GetCodecs(token);

var found = codecs.Split('\n').Any(
line => line
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Any(token => token.Trim('(', ')', ':', ',') == encoderName));

if (!found)
if (!Tokens(codecs).Contains(encoderName, StringComparer.Ordinal))
{
var message = $"Encoder '{encoderName}' is not in the detected FFmpeg build — " +
"rebuild the payload (build/common.sh carries the codec flags).";
"rebuild the payload (build/common.sh carries the codec flags)." +
$"{Environment.NewLine}{await DescribeDetectedBuildAsync(token)}";

if (skipWhenMissing)
Assert.Skip(message);
else
Assert.Fail(message);
}
}

/// <summary>
/// Слова из вывода <c>ffmpeg -codecs</c>. <see cref="string.Trim()"/> обязателен перед
/// снятием скобок: на Windows строки приходят с <c>\r</c>, и токен в конце строки
/// (<c>libvorbis\r</c>) не совпадал ни с одним именем энкодера.
/// </summary>
private static IEnumerable<string> Tokens(string codecs) =>
codecs
.Split('\n')
.SelectMany(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.Select(part => part.Trim().Trim('(', ')', ':', ','));

/// <summary>
/// Что именно тест увидел: путь к бинарю, его версия и список внешних библиотек
/// (<c>lib*</c>), найденных в сборке. Без этого «энкодера нет» не отличить от «взят
/// не тот ffmpeg» — а Windows-лег уже один раз упал именно так, и по сообщению
/// невозможно было понять, какой бинарь опрошен.
/// </summary>
private static async Task<string> DescribeDetectedBuildAsync(CancellationToken token)
{
var executor = IFFMpegExecutor.Default;

var version = (await executor.GetVersion(token))
.Split('\n')
.FirstOrDefault(line => line.Contains("version", StringComparison.OrdinalIgnoreCase))
?.Trim() ?? "(version unknown)";

var external = string.Join(", ", Tokens(await executor.GetCodecs(token))
.Where(part => part.StartsWith("lib", StringComparison.Ordinal))
.Distinct(StringComparer.Ordinal)
.OrderBy(part => part, StringComparer.Ordinal));

return $"Detected: {version}{Environment.NewLine}" +
$"Executable: {executor.Executor.ExecutablePath}{Environment.NewLine}" +
$"External encoders: {external}";
}
}
10 changes: 7 additions & 3 deletions src/Tests/Sa.Media.FFmpegTests/FFMpegProcessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,13 @@ await Processor.ConvertToMp3(
[InlineData("./data/input.wav")]
public async Task ConvertToOgg_ShouldBeWork(string testFilePath)
{
// isLibopus: false → команда явно называет энкодер libvorbis; если его нет
// в сборке (win-x64 payload старше фикса кодеков) — тест пропускается, а не падает.
await CodecProbe.RequireEncoderAvailable("libvorbis", CancellationToken);
// isLibopus: false → команда явно называет энкодер libvorbis. Payload win-x64 старше
// linux-ового и собран отдельной кросс-компиляцией, поэтому отсутствие libvorbis в нём —
// известное состояние, а не регрессия: тест обязан пропуститься, а не падать
// (RequireEncoderAvailable здесь валил windows-лег на ровном месте).
// Причина пропуска несёт путь к бинарю, версию и список внешних энкодеров —
// по ней видно, опрошен ли бандл или подобран чужой ffmpeg из PATH.
await CodecProbe.EnsureEncoderAvailable("libvorbis", CancellationToken);

var fn = "./data/output.ogg_";
// Act
Expand Down
5 changes: 4 additions & 1 deletion src/Tests/Sa.Media.FFmpegTests/ProcessExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ public async Task OwnTimeout_FiresAtTheDeadlineNotAtProcessDeath()
Assert.InRange(sw.Elapsed, TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(10));

// Команда попала в сообщение — диагностика таймаута не «голый» текст.
Assert.Contains("sleep", ex.Message, StringComparison.OrdinalIgnoreCase);
// Имя процесса платформенное: LongRunningProcess запускает ping на Windows и /bin/sleep
// на Unix, поэтому захардкоженное "sleep" валило windows-лег на ровном месте.
var expectedCommand = OperatingSystem.IsWindows() ? "ping" : "sleep";
Assert.Contains(expectedCommand, ex.Message, StringComparison.OrdinalIgnoreCase);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,22 +140,22 @@ public async Task SelectTenant_ReturnsEveryTenantExactlyOnce()
// A projection mistake here would return fewer tenants than exist and only show up
// as a quietly under-consumed outbox.
//
// Counted rather than compared against a literal: both tests in this class share the
// fixture and therefore the message table, and the plan test seeds every configured
// tenant, so the number of distinct tenants is TenantCount by the time this runs. The
// point being asserted is "one row per tenant, never fewer and never more", which is
// what a broken projection or a missing DISTINCT would break.
// Every configured tenant is seeded *by this test*: both tests in this class share the
// fixture and therefore the message table, but xUnit gives no order guarantee, and
// relying on the sibling's seeding made the expected count depend on it. On a CI runner
// this test ran first, so the table held only the two tenants it had published itself
// and the assertion went 4 != 2. Two messages per tenant keep the dedup exercised.
var ct = TestContext.Current.CancellationToken;

var published = await fixture.Sub.Publish(
[
new TestMessage { PayloadId = "distinct-a", Content = "a", TenantId = 1 },
new TestMessage { PayloadId = "distinct-b", Content = "b", TenantId = 1 },
new TestMessage { PayloadId = "distinct-c", Content = "c", TenantId = 3 },
],
m => m.TenantId,
ct);
Assert.Equal(3u, published);
List<TestMessage> messages = [];
for (var tenant = 1; tenant <= TenantCount; tenant++)
{
messages.Add(new TestMessage { PayloadId = $"distinct-{tenant}-a", Content = "a", TenantId = tenant });
messages.Add(new TestMessage { PayloadId = $"distinct-{tenant}-b", Content = "b", TenantId = tenant });
}

var published = await fixture.Sub.Publish(messages, m => m.TenantId, ct);
Assert.Equal((ulong)messages.Count, published);

var field = TableSettings.Message.Fields.TenantId;
var tenants = await DataSource.ExecuteReaderList(
Expand All @@ -165,7 +165,7 @@ public async Task SelectTenant_ReturnsEveryTenantExactlyOnce()

Assert.Equal(TenantCount, tenants.Count);
Assert.Equal(tenants.Count, tenants.Distinct().Count());
Assert.Equal(tenants.Order(), tenants.OrderBy(t => t));
Assert.Equal(Enumerable.Range(1, TenantCount), tenants.Order());
}

private async Task<List<string>> ExplainAsync(string sql, CancellationToken cancellationToken)
Expand Down
39 changes: 36 additions & 3 deletions src/Tests/Sa.Utils.WorkQueue.Tests/WorkQueueSyncReaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,43 @@ public Task Execute(int input, CancellationToken ct)
// below reach it by reflection. They check the two properties the registry has
// to have: every entry is a usable reader, and none of them is a leftover.

private static readonly FieldInfo ReadersField = typeof(SaWorkQueue<int>)
.GetField("_readers", BindingFlags.Instance | BindingFlags.NonPublic)!;

private static readonly FieldInfo ReadersSyncField = typeof(SaWorkQueue<int>)
.GetField("_readersSync", BindingFlags.Instance | BindingFlags.NonPublic)!;

private static readonly MethodInfo LockEnter = typeof(Lock).GetMethod(nameof(Lock.Enter))!;

private static readonly MethodInfo LockExit = typeof(Lock).GetMethod(nameof(Lock.Exit))!;

/// <summary>
/// Snapshot of the registry, taken under the queue's own <c>_readersSync</c>.
/// </summary>
/// <remarks>
/// Readers are added and removed from their own threads, so a plain copy of the list
/// raced with that and threw "Collection was modified; enumeration operation may not
/// execute" on a 4-core CI runner, pointing the finger at the queue while the fault was
/// purely in the snapshot. <see cref="Lock.EnterScope"/> cannot be reached through
/// reflection (it returns a <c>ref struct</c>), so the same lock is taken through
/// <see cref="Lock.Enter"/>/<see cref="Lock.Exit"/>. <c>Monitor.Enter</c> would not do:
/// a <see cref="Lock"/> synchronizes through its own state, not through the object's
/// monitor, so anything but the very same <see cref="Lock"/> provides no exclusion at all.
/// </remarks>
private static List<object> Readers(SaWorkQueue<int> queue)
=> [.. (IEnumerable)typeof(SaWorkQueue<int>)
.GetField("_readers", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(queue)!];
{
var sync = ReadersSyncField.GetValue(queue)!;

LockEnter.Invoke(sync, null);
try
{
return [.. (IEnumerable)ReadersField.GetValue(queue)!];
}
finally
{
LockExit.Invoke(sync, null);
}
}

private static object? Prop(object instance, string name)
=> instance.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public)!.GetValue(instance);
Expand Down
24 changes: 20 additions & 4 deletions src/Tests/Sa.Utils.WorkQueue.Tests/WorkQueueTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,24 @@ public async Task ShutdownAsync_StopsProcessing()
ConcurrentBag<SaWorkStatus> errors = [];

// Arrange
var processor = new TestWorkWithDelay(TimeSpan.FromMilliseconds(300));
// All five items have to be *in flight* when the shutdown starts. An item still sitting
// in the buffer is drained as Faulted ("dropped"), not Cancelled ("interrupted"), so with
// the default pool — ProcessorCount readers and a buffer of the same size — the expected
// count silently depended on the core count: a 4-core CI runner started 4 readers, left
// the fifth item buffered, and the assertion went 5 != 4. Hence the explicit pool size
// and the "started" signal below instead of a sleep.
using var started = new SemaphoreSlim(0);
using var gate = new SemaphoreSlim(0);

using var queue = new SaWorkQueue<TestModel>(SaWorkQueueOptions<TestModel>
.Create(processor)
.Create(async (_, ct) =>
{
started.Release();
await gate.WaitAsync(ct);
})
.WithMaxConcurrency(5)
.WithConcurrencyLimit(5)
.WithQueueCapacity(5)
.WithStatusCallback((m, s, e) =>
{
if (s == SaWorkStatus.Cancelled)
Expand All @@ -212,8 +226,10 @@ public async Task ShutdownAsync_StopsProcessing()
for (int i = 0; i < 5; i++)
await queue.Enqueue(new TestModel(), cancellationToken: CancellationToken.None);


await Task.Delay(50, TestToken);
for (int i = 0; i < 5; i++)
Assert.True(
await started.WaitAsync(TimeSpan.FromSeconds(5), TestToken),
"An enqueued item never started, so the shutdown would interrupt fewer than five.");

// Act
await queue.ShutdownAsync();
Expand Down
31 changes: 23 additions & 8 deletions src/Tests/SaTests/Classes/StackallocTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,30 @@ namespace SaTests.Classes;
/// <summary>
/// Регрессия на неограниченный <c>stackalloc</c>. Стек потока ограничен, а
/// <see cref="StackOverflowException"/> перехватить нельзя — процесс падает целиком.
/// Тесты гоняются на отдельном потоке с 256 КБ стека, как у потоков ASP.NET.
/// Тесты гоняются на отдельном потоке с 256 КБ стека, как у потоков ASP.NET; квадратичные
/// алгоритмы — на 64 КБ, чтобы проверка не стоила десятков секунд (см.
/// <see cref="SmallStackBytesForQuadraticWork"/>).
/// </summary>
public class StackallocTests
{
private const int ThreadStackBytes = 256 * 1024;

/// <summary>
/// Стек для квадратичных алгоритмов. Наивный <c>stackalloc</c> трёх полос по 6 001 int —
/// это 3 * 6 001 * 4 = 72 КБ, то есть 64 КБ стека по-прежнему переполняются, и тест
/// ловит ту же регрессию, что и на 256 КБ. Зато 6 000 × 6 000 ячеек считаются за доли
/// секунды, тогда как 60 000 × 60 000 — это 3.6 млрд итераций: ~21 с в Release и заметно
/// дольше в Debug, где 60-секундный <see cref="Thread.Join(TimeSpan)"/> превращал
/// медленный прогон в «test thread did not finish».
/// </summary>
private const int SmallStackBytesForQuadraticWork = 64 * 1024;

/// <summary>
/// Выполняет <paramref name="action"/> на потоке с маленьким стеком и возвращает результат.
/// Поток намеренно переживает падение: без этого упавший StackOverflowException убил бы
/// весь тестовый процесс, и падение выглядело бы как «тесты зависли».
/// </summary>
private static Exception? RunOnSmallStackThread(Action action)
private static Exception? RunOnSmallStackThread(Action action, int stackBytes = ThreadStackBytes)
{
Exception? captured = null;

Expand All @@ -31,7 +43,7 @@ public class StackallocTests
{
captured = e;
}
}, ThreadStackBytes);
}, stackBytes);

thread.Start();
Assert.True(thread.Join(TimeSpan.FromSeconds(60)), "Test thread did not finish");
Expand Down Expand Up @@ -77,15 +89,18 @@ public void NormalizeWhiteSpace_ShortString_StillNormalizes()
[Fact]
public void Levenshtein_Distance_StringsLongerThanStack_DoNotOverflow()
{
// Три полосы по 60 001 int = 720 КБ при стеке 256 КБ.
var a = new string('a', 60_000);
var b = new string('b', 60_000);
// 6 000 символов уводят расчёт на кучу (граница MaxStackallocInts = 1024), а наивный
// stackalloc трёх полос занял бы 3 * 6 001 * 4 = 72 КБ — больше 64 КБ стека потока.
// Прежние 60 000 символов давали 3.6 млрд итераций DP: 21 с в Release и больше
// 60 с в Debug, где собственный Join-таймаут теста валил его как «завис».
var a = new string('a', 6_000);
var b = new string('b', 6_000);

var error = RunOnSmallStackThread(() =>
{
Assert.Equal(60_000, Levenshtein.Distance(a, b));
Assert.Equal(6_000, Levenshtein.Distance(a, b));
Assert.Equal(0, Levenshtein.Distance(a, a));
});
}, SmallStackBytesForQuadraticWork);

Assert.Null(error);
}
Expand Down
Loading