using System.Collections.Concurrent; using System.Text; namespace Titano.Testing; /// /// Per-test services. A test class may take a in its constructor; /// one context is created for every test execution and disposed after it. /// public sealed class TestContext : IDisposable { private static readonly AsyncLocal CurrentTest = new(); private readonly ConcurrentQueue _log = new(); private readonly List _tempDirectories = []; private readonly Lock _gate = new(); internal TestContext(string testName, bool isSerial, CancellationToken cancellation) { TestName = testName; IsSerial = isSerial; Cancellation = cancellation; } /// /// The test running on this flow of execution (its constructor, body and the tasks it starts); null outside tests. /// Lets a test program guard process-wide state, which only a serial test may change. /// public static TestContext? Current { get => CurrentTest.Value; internal set => CurrentTest.Value = value; } public string TestName { get; } /// True when the test's class is : no other test runs beside it. public bool IsSerial { get; } /// Signalled when the test times out or the run is aborted. public CancellationToken Cancellation { get; } /// Repository root (the directory that holds Titano.slnx), or the working directory. public static string RepositoryRoot { get; } = FindRepositoryRoot(); /// tests/fixtures under the repository root. public static string FixturesDirectory => Path.Combine(RepositoryRoot, "tests", "fixtures"); /// Creates an empty directory that is deleted when the test ends. public string CreateTempDirectory(string? hint = null) { var path = Path.Combine(Path.GetTempPath(), "titano-tests", $"{Sanitize(hint ?? TestName)}-{Guid.NewGuid():N}"); Directory.CreateDirectory(path); lock (_gate) _tempDirectories.Add(path); return path; } /// Lines written here are printed only when the test fails or in verbose mode. public void Log(string message) => _log.Enqueue(message); public string LogText { get { var sb = new StringBuilder(); foreach (var line in _log) sb.AppendLine(line); return sb.ToString(); } } [System.Diagnostics.CodeAnalysis.DoesNotReturn] public static void Skip(string reason) => throw new SkipException(reason); public void Dispose() { lock (_gate) { foreach (var dir in _tempDirectories) { try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { // Best effort: a file still open by the OS indexer must not fail the test. } catch (UnauthorizedAccessException) { } } _tempDirectories.Clear(); } } private static string Sanitize(string s) { var chars = s.Select(c => char.IsLetterOrDigit(c) ? c : '-').Take(48).ToArray(); return new string(chars); } private static string FindRepositoryRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; dir = dir.Parent; } return Directory.GetCurrentDirectory(); } }