Add tests for SBOM generation determinism across multiple formats
- Created `StellaOps.TestKit.Tests` project for unit tests related to determinism. - Implemented `DeterminismManifestTests` to validate deterministic output for canonical bytes and strings, file read/write operations, and error handling for invalid schema versions. - Added `SbomDeterminismTests` to ensure identical inputs produce consistent SBOMs across SPDX 3.0.1 and CycloneDX 1.6/1.7 formats, including parallel execution tests. - Updated project references in `StellaOps.Integration.Determinism` to include the new determinism testing library.
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.TestKit.Assertions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides assertions for canonical JSON serialization and determinism testing.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Canonical JSON ensures:
|
||||
/// - Stable key ordering (alphabetical)
|
||||
/// - Consistent number formatting
|
||||
/// - No whitespace variations
|
||||
/// - UTF-8 encoding
|
||||
/// - Deterministic output (same input → same bytes)
|
||||
/// </remarks>
|
||||
public static class CanonicalJsonAssert
|
||||
{
|
||||
/// <summary>
|
||||
/// Asserts that the canonical JSON serialization of the value produces the expected SHA-256 hash.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to serialize.</param>
|
||||
/// <param name="expectedSha256Hex">The expected SHA-256 hash (lowercase hex string).</param>
|
||||
public static void HasExpectedHash<T>(T value, string expectedSha256Hex)
|
||||
{
|
||||
string actualHash = Canonical.Json.CanonJson.Hash(value);
|
||||
Assert.Equal(expectedSha256Hex.ToLowerInvariant(), actualHash);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that two values produce identical canonical JSON.
|
||||
/// </summary>
|
||||
public static void AreCanonicallyEqual<T>(T expected, T actual)
|
||||
{
|
||||
byte[] expectedBytes = Canonical.Json.CanonJson.Canonicalize(expected);
|
||||
byte[] actualBytes = Canonical.Json.CanonJson.Canonicalize(actual);
|
||||
|
||||
Assert.Equal(expectedBytes, actualBytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that serializing the value multiple times produces identical bytes (determinism check).
|
||||
/// </summary>
|
||||
public static void IsDeterministic<T>(T value, int iterations = 10)
|
||||
{
|
||||
byte[]? baseline = null;
|
||||
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
byte[] current = Canonical.Json.CanonJson.Canonicalize(value);
|
||||
|
||||
if (baseline == null)
|
||||
{
|
||||
baseline = current;
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Equal(baseline, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the SHA-256 hash of the canonical JSON and returns it as a lowercase hex string.
|
||||
/// </summary>
|
||||
public static string ComputeCanonicalHash<T>(T value)
|
||||
{
|
||||
return Canonical.Json.CanonJson.Hash(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the canonical JSON matches the expected string (useful for debugging).
|
||||
/// </summary>
|
||||
public static void MatchesJson<T>(T value, string expectedJson)
|
||||
{
|
||||
byte[] canonicalBytes = Canonical.Json.CanonJson.Canonicalize(value);
|
||||
string actualJson = System.Text.Encoding.UTF8.GetString(canonicalBytes);
|
||||
Assert.Equal(expectedJson, actualJson);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the JSON contains the expected key-value pair (deep search).
|
||||
/// </summary>
|
||||
public static void ContainsProperty<T>(T value, string propertyPath, object expectedValue)
|
||||
{
|
||||
byte[] canonicalBytes = Canonical.Json.CanonJson.Canonicalize(value);
|
||||
using var doc = JsonDocument.Parse(canonicalBytes);
|
||||
|
||||
JsonElement? element = FindPropertyByPath(doc.RootElement, propertyPath);
|
||||
|
||||
Assert.NotNull(element);
|
||||
|
||||
// Compare values
|
||||
string expectedJson = JsonSerializer.Serialize(expectedValue);
|
||||
string actualJson = element.Value.GetRawText();
|
||||
|
||||
Assert.Equal(expectedJson, actualJson);
|
||||
}
|
||||
|
||||
private static JsonElement? FindPropertyByPath(JsonElement root, string path)
|
||||
{
|
||||
var parts = path.Split('.');
|
||||
var current = root;
|
||||
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (current.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!current.TryGetProperty(part, out var next))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
current = next;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
private static string ComputeSha256Hex(byte[] data)
|
||||
{
|
||||
byte[] hash = SHA256.HashData(data);
|
||||
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
114
src/__Libraries/StellaOps.TestKit/Assertions/SnapshotAssert.cs
Normal file
114
src/__Libraries/StellaOps.TestKit/Assertions/SnapshotAssert.cs
Normal file
@@ -0,0 +1,114 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.TestKit.Assertions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides snapshot testing assertions for golden master testing.
|
||||
/// Snapshots are stored in the test project's `Snapshots/` directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// [Fact]
|
||||
/// public void TestSbomGeneration()
|
||||
/// {
|
||||
/// var sbom = GenerateSbom();
|
||||
///
|
||||
/// // Snapshot will be stored in Snapshots/TestSbomGeneration.json
|
||||
/// SnapshotAssert.MatchesSnapshot(sbom, snapshotName: "TestSbomGeneration");
|
||||
/// }
|
||||
/// </code>
|
||||
///
|
||||
/// To update snapshots (e.g., after intentional changes), set environment variable:
|
||||
/// UPDATE_SNAPSHOTS=1 dotnet test
|
||||
/// </remarks>
|
||||
public static class SnapshotAssert
|
||||
{
|
||||
private static readonly bool UpdateSnapshotsMode =
|
||||
Environment.GetEnvironmentVariable("UPDATE_SNAPSHOTS") == "1";
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the value matches the stored snapshot. If UPDATE_SNAPSHOTS=1, updates the snapshot.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to snapshot (will be JSON-serialized).</param>
|
||||
/// <param name="snapshotName">The snapshot name (filename without extension).</param>
|
||||
/// <param name="snapshotsDirectory">Optional directory for snapshots (default: "Snapshots" in test project).</param>
|
||||
public static void MatchesSnapshot<T>(T value, string snapshotName, string? snapshotsDirectory = null)
|
||||
{
|
||||
snapshotsDirectory ??= Path.Combine(Directory.GetCurrentDirectory(), "Snapshots");
|
||||
Directory.CreateDirectory(snapshotsDirectory);
|
||||
|
||||
string snapshotPath = Path.Combine(snapshotsDirectory, $"{snapshotName}.json");
|
||||
|
||||
// Serialize to pretty JSON for readability
|
||||
string actualJson = JsonSerializer.Serialize(value, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
});
|
||||
|
||||
if (UpdateSnapshotsMode)
|
||||
{
|
||||
// Update snapshot
|
||||
File.WriteAllText(snapshotPath, actualJson, Encoding.UTF8);
|
||||
return; // Don't assert in update mode
|
||||
}
|
||||
|
||||
// Verify snapshot exists
|
||||
Assert.True(File.Exists(snapshotPath),
|
||||
$"Snapshot '{snapshotName}' not found at {snapshotPath}. Run with UPDATE_SNAPSHOTS=1 to create it.");
|
||||
|
||||
// Compare with stored snapshot
|
||||
string expectedJson = File.ReadAllText(snapshotPath, Encoding.UTF8);
|
||||
|
||||
Assert.Equal(expectedJson, actualJson);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the text matches the stored snapshot.
|
||||
/// </summary>
|
||||
public static void MatchesTextSnapshot(string value, string snapshotName, string? snapshotsDirectory = null)
|
||||
{
|
||||
snapshotsDirectory ??= Path.Combine(Directory.GetCurrentDirectory(), "Snapshots");
|
||||
Directory.CreateDirectory(snapshotsDirectory);
|
||||
|
||||
string snapshotPath = Path.Combine(snapshotsDirectory, $"{snapshotName}.txt");
|
||||
|
||||
if (UpdateSnapshotsMode)
|
||||
{
|
||||
File.WriteAllText(snapshotPath, value, Encoding.UTF8);
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.True(File.Exists(snapshotPath),
|
||||
$"Snapshot '{snapshotName}' not found at {snapshotPath}. Run with UPDATE_SNAPSHOTS=1 to create it.");
|
||||
|
||||
string expected = File.ReadAllText(snapshotPath, Encoding.UTF8);
|
||||
Assert.Equal(expected, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that binary data matches the stored snapshot.
|
||||
/// </summary>
|
||||
public static void MatchesBinarySnapshot(byte[] value, string snapshotName, string? snapshotsDirectory = null)
|
||||
{
|
||||
snapshotsDirectory ??= Path.Combine(Directory.GetCurrentDirectory(), "Snapshots");
|
||||
Directory.CreateDirectory(snapshotsDirectory);
|
||||
|
||||
string snapshotPath = Path.Combine(snapshotsDirectory, $"{snapshotName}.bin");
|
||||
|
||||
if (UpdateSnapshotsMode)
|
||||
{
|
||||
File.WriteAllBytes(snapshotPath, value);
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.True(File.Exists(snapshotPath),
|
||||
$"Snapshot '{snapshotName}' not found at {snapshotPath}. Run with UPDATE_SNAPSHOTS=1 to create it.");
|
||||
|
||||
byte[] expected = File.ReadAllBytes(snapshotPath);
|
||||
Assert.Equal(expected, value);
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace StellaOps.TestKit.Determinism;
|
||||
|
||||
/// <summary>
|
||||
/// Determinism gates for verifying reproducible outputs.
|
||||
/// Ensures that operations produce identical results across multiple executions.
|
||||
/// </summary>
|
||||
public static class DeterminismGate
|
||||
{
|
||||
/// <summary>
|
||||
/// Verifies that a function produces identical output across multiple invocations.
|
||||
/// </summary>
|
||||
/// <param name="operation">The operation to test.</param>
|
||||
/// <param name="iterations">Number of times to execute (default: 3).</param>
|
||||
public static void AssertDeterministic(Func<string> operation, int iterations = 3)
|
||||
{
|
||||
if (iterations < 2)
|
||||
{
|
||||
throw new ArgumentException("Iterations must be at least 2", nameof(iterations));
|
||||
}
|
||||
|
||||
string? baseline = null;
|
||||
var results = new List<string>();
|
||||
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
var result = operation();
|
||||
results.Add(result);
|
||||
|
||||
if (baseline == null)
|
||||
{
|
||||
baseline = result;
|
||||
}
|
||||
else if (result != baseline)
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Determinism violation detected at iteration {i + 1}.\n\n" +
|
||||
$"Baseline (iteration 1):\n{baseline}\n\n" +
|
||||
$"Different (iteration {i + 1}):\n{result}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a function produces identical binary output across multiple invocations.
|
||||
/// </summary>
|
||||
public static void AssertDeterministic(Func<byte[]> operation, int iterations = 3)
|
||||
{
|
||||
if (iterations < 2)
|
||||
{
|
||||
throw new ArgumentException("Iterations must be at least 2", nameof(iterations));
|
||||
}
|
||||
|
||||
byte[]? baseline = null;
|
||||
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
var result = operation();
|
||||
|
||||
if (baseline == null)
|
||||
{
|
||||
baseline = result;
|
||||
}
|
||||
else if (!result.SequenceEqual(baseline))
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Binary determinism violation detected at iteration {i + 1}.\n" +
|
||||
$"Baseline hash: {ComputeHash(baseline)}\n" +
|
||||
$"Current hash: {ComputeHash(result)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a function producing JSON has stable property ordering and formatting.
|
||||
/// </summary>
|
||||
public static void AssertJsonDeterministic(Func<string> operation, int iterations = 3)
|
||||
{
|
||||
AssertDeterministic(() =>
|
||||
{
|
||||
var json = operation();
|
||||
// Canonicalize to detect property ordering issues
|
||||
return CanonicalizeJson(json);
|
||||
}, iterations);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that an object's JSON serialization is deterministic.
|
||||
/// </summary>
|
||||
public static void AssertJsonDeterministic<T>(Func<T> operation, int iterations = 3)
|
||||
{
|
||||
AssertDeterministic(() =>
|
||||
{
|
||||
var obj = operation();
|
||||
var json = JsonSerializer.Serialize(obj, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = false,
|
||||
PropertyNamingPolicy = null
|
||||
});
|
||||
return CanonicalizeJson(json);
|
||||
}, iterations);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that two objects produce identical canonical JSON.
|
||||
/// </summary>
|
||||
public static void AssertCanonicallyEqual(object expected, object actual)
|
||||
{
|
||||
var expectedJson = JsonSerializer.Serialize(expected);
|
||||
var actualJson = JsonSerializer.Serialize(actual);
|
||||
|
||||
var expectedCanonical = CanonicalizeJson(expectedJson);
|
||||
var actualCanonical = CanonicalizeJson(actualJson);
|
||||
|
||||
if (expectedCanonical != actualCanonical)
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Canonical JSON mismatch:\n\nExpected:\n{expectedCanonical}\n\nActual:\n{actualCanonical}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a stable SHA256 hash of text content.
|
||||
/// </summary>
|
||||
public static string ComputeHash(string content)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(content);
|
||||
return ComputeHash(bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a stable SHA256 hash of binary content.
|
||||
/// </summary>
|
||||
public static string ComputeHash(byte[] content)
|
||||
{
|
||||
using var sha256 = SHA256.Create();
|
||||
var hash = sha256.ComputeHash(content);
|
||||
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes JSON for comparison (stable property ordering, no whitespace).
|
||||
/// </summary>
|
||||
private static string CanonicalizeJson(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
return JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = false,
|
||||
PropertyNamingPolicy = null,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
});
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new DeterminismViolationException($"Failed to parse JSON for canonicalization: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that file paths are sorted deterministically (for SBOM manifests).
|
||||
/// </summary>
|
||||
public static void AssertSortedPaths(IEnumerable<string> paths)
|
||||
{
|
||||
var pathList = paths.ToList();
|
||||
var sortedPaths = pathList.OrderBy(p => p, StringComparer.Ordinal).ToList();
|
||||
|
||||
if (!pathList.SequenceEqual(sortedPaths))
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Path ordering is non-deterministic.\n\n" +
|
||||
$"Actual order:\n{string.Join("\n", pathList.Take(10))}\n\n" +
|
||||
$"Expected (sorted) order:\n{string.Join("\n", sortedPaths.Take(10))}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that timestamps are in UTC and ISO 8601 format.
|
||||
/// </summary>
|
||||
public static void AssertUtcIso8601(string timestamp)
|
||||
{
|
||||
if (!DateTimeOffset.TryParse(timestamp, out var dto))
|
||||
{
|
||||
throw new DeterminismViolationException($"Invalid timestamp format: {timestamp}");
|
||||
}
|
||||
|
||||
if (dto.Offset != TimeSpan.Zero)
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Timestamp is not UTC: {timestamp} (offset: {dto.Offset})");
|
||||
}
|
||||
|
||||
// Verify ISO 8601 format with 'Z' suffix
|
||||
var iso8601 = dto.ToString("o");
|
||||
if (!iso8601.EndsWith("Z"))
|
||||
{
|
||||
throw new DeterminismViolationException(
|
||||
$"Timestamp does not have 'Z' suffix: {timestamp}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when determinism violations are detected.
|
||||
/// </summary>
|
||||
public sealed class DeterminismViolationException : Exception
|
||||
{
|
||||
public DeterminismViolationException(string message) : base(message) { }
|
||||
public DeterminismViolationException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
namespace StellaOps.TestKit.Deterministic;
|
||||
|
||||
/// <summary>
|
||||
/// Provides deterministic random number generation for testing.
|
||||
/// Uses a fixed seed to ensure reproducible random sequences.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// var random = new DeterministicRandom(seed: 42);
|
||||
/// var value1 = random.Next(); // Same value every time with seed 42
|
||||
/// var value2 = random.NextDouble(); // Deterministic sequence
|
||||
///
|
||||
/// // For property-based testing with FsCheck
|
||||
/// var gen = DeterministicRandom.CreateGen(seed: 42);
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class DeterministicRandom
|
||||
{
|
||||
private readonly System.Random _random;
|
||||
private readonly int _seed;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deterministic random number generator with the specified seed.
|
||||
/// </summary>
|
||||
/// <param name="seed">The seed value. Same seed always produces same sequence.</param>
|
||||
public DeterministicRandom(int seed)
|
||||
{
|
||||
_seed = seed;
|
||||
_random = new System.Random(seed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the seed used for this random number generator.
|
||||
/// </summary>
|
||||
public int Seed => _seed;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a non-negative random integer.
|
||||
/// </summary>
|
||||
public int Next() => _random.Next();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a non-negative random integer less than the specified maximum.
|
||||
/// </summary>
|
||||
public int Next(int maxValue) => _random.Next(maxValue);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random integer within the specified range.
|
||||
/// </summary>
|
||||
public int Next(int minValue, int maxValue) => _random.Next(minValue, maxValue);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random floating-point number between 0.0 and 1.0.
|
||||
/// </summary>
|
||||
public double NextDouble() => _random.NextDouble();
|
||||
|
||||
/// <summary>
|
||||
/// Fills the elements of the specified array with random bytes.
|
||||
/// </summary>
|
||||
public void NextBytes(byte[] buffer) => _random.NextBytes(buffer);
|
||||
|
||||
/// <summary>
|
||||
/// Fills the elements of the specified span with random bytes.
|
||||
/// </summary>
|
||||
public void NextBytes(Span<byte> buffer) => _random.NextBytes(buffer);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deterministic Random instance with the specified seed.
|
||||
/// Useful for integration with code that expects System.Random.
|
||||
/// </summary>
|
||||
public static System.Random CreateRandom(int seed) => new(seed);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a deterministic GUID based on the seed.
|
||||
/// </summary>
|
||||
public Guid NextGuid()
|
||||
{
|
||||
var bytes = new byte[16];
|
||||
_random.NextBytes(bytes);
|
||||
return new Guid(bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a deterministic string of the specified length using alphanumeric characters.
|
||||
/// </summary>
|
||||
public string NextString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
var result = new char[length];
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
result[i] = chars[_random.Next(chars.Length)];
|
||||
}
|
||||
return new string(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects a random element from the specified array.
|
||||
/// </summary>
|
||||
public T NextElement<T>(T[] array)
|
||||
{
|
||||
if (array == null || array.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("Array cannot be null or empty", nameof(array));
|
||||
}
|
||||
return array[_random.Next(array.Length)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shuffles an array in-place using the Fisher-Yates algorithm (deterministic).
|
||||
/// </summary>
|
||||
public void Shuffle<T>(T[] array)
|
||||
{
|
||||
if (array == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(array));
|
||||
}
|
||||
|
||||
for (int i = array.Length - 1; i > 0; i--)
|
||||
{
|
||||
int j = _random.Next(i + 1);
|
||||
(array[i], array[j]) = (array[j], array[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
namespace StellaOps.TestKit.Deterministic;
|
||||
|
||||
/// <summary>
|
||||
/// Provides deterministic time for testing. Replaces DateTime.UtcNow and DateTimeOffset.UtcNow
|
||||
/// to ensure reproducible test results.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// using var deterministicTime = new DeterministicTime(new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc));
|
||||
/// // All calls to deterministicTime.UtcNow return the fixed time
|
||||
/// var timestamp = deterministicTime.UtcNow; // Always 2026-01-15T10:30:00Z
|
||||
///
|
||||
/// // Advance time by a specific duration
|
||||
/// deterministicTime.Advance(TimeSpan.FromHours(2));
|
||||
/// var laterTimestamp = deterministicTime.UtcNow; // 2026-01-15T12:30:00Z
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class DeterministicTime : IDisposable
|
||||
{
|
||||
private DateTime _currentUtc;
|
||||
private readonly object _lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deterministic time provider starting at the specified UTC time.
|
||||
/// </summary>
|
||||
/// <param name="startUtc">The starting UTC time. Must have DateTimeKind.Utc.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if startUtc is not UTC.</exception>
|
||||
public DeterministicTime(DateTime startUtc)
|
||||
{
|
||||
if (startUtc.Kind != DateTimeKind.Utc)
|
||||
{
|
||||
throw new ArgumentException("Start time must be UTC", nameof(startUtc));
|
||||
}
|
||||
|
||||
_currentUtc = startUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current deterministic UTC time.
|
||||
/// </summary>
|
||||
public DateTime UtcNow
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _currentUtc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current deterministic UTC time as DateTimeOffset.
|
||||
/// </summary>
|
||||
public DateTimeOffset UtcNowOffset => new(_currentUtc, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
/// Advances the deterministic time by the specified duration.
|
||||
/// </summary>
|
||||
/// <param name="duration">The duration to advance. Can be negative to go backwards.</param>
|
||||
public void Advance(TimeSpan duration)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_currentUtc = _currentUtc.Add(duration);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the deterministic time to a specific UTC value.
|
||||
/// </summary>
|
||||
/// <param name="newUtc">The new UTC time. Must have DateTimeKind.Utc.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if newUtc is not UTC.</exception>
|
||||
public void SetTo(DateTime newUtc)
|
||||
{
|
||||
if (newUtc.Kind != DateTimeKind.Utc)
|
||||
{
|
||||
throw new ArgumentException("Time must be UTC", nameof(newUtc));
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_currentUtc = newUtc;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the deterministic time to the starting value.
|
||||
/// </summary>
|
||||
public void Reset(DateTime startUtc)
|
||||
{
|
||||
if (startUtc.Kind != DateTimeKind.Utc)
|
||||
{
|
||||
throw new ArgumentException("Start time must be UTC", nameof(startUtc));
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_currentUtc = startUtc;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Cleanup if needed
|
||||
}
|
||||
}
|
||||
152
src/__Libraries/StellaOps.TestKit/Fixtures/HttpFixtureServer.cs
Normal file
152
src/__Libraries/StellaOps.TestKit/Fixtures/HttpFixtureServer.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace StellaOps.TestKit.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Provides an in-memory HTTP test server using WebApplicationFactory for contract testing.
|
||||
/// </summary>
|
||||
/// <typeparam name="TProgram">The entry point type of the web application (usually Program).</typeparam>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// public class ApiTests : IClassFixture<HttpFixtureServer<Program>>
|
||||
/// {
|
||||
/// private readonly HttpClient _client;
|
||||
///
|
||||
/// public ApiTests(HttpFixtureServer<Program> fixture)
|
||||
/// {
|
||||
/// _client = fixture.CreateClient();
|
||||
/// }
|
||||
///
|
||||
/// [Fact]
|
||||
/// public async Task GetHealth_ReturnsOk()
|
||||
/// {
|
||||
/// var response = await _client.GetAsync("/health");
|
||||
/// response.EnsureSuccessStatusCode();
|
||||
/// }
|
||||
/// }
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class HttpFixtureServer<TProgram> : WebApplicationFactory<TProgram>
|
||||
where TProgram : class
|
||||
{
|
||||
private readonly Action<IServiceCollection>? _configureServices;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new HTTP fixture server with optional service configuration.
|
||||
/// </summary>
|
||||
/// <param name="configureServices">Optional action to configure test services (e.g., replace dependencies with mocks).</param>
|
||||
public HttpFixtureServer(Action<IServiceCollection>? configureServices = null)
|
||||
{
|
||||
_configureServices = configureServices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for testing (disables HTTPS redirection, applies custom services).
|
||||
/// </summary>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Apply user-provided service configuration (e.g., mock dependencies)
|
||||
_configureServices?.Invoke(services);
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Test");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HttpClient configured to communicate with the test server.
|
||||
/// </summary>
|
||||
public new HttpClient CreateClient()
|
||||
{
|
||||
return base.CreateClient();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HttpClient with custom configuration.
|
||||
/// </summary>
|
||||
public HttpClient CreateClient(Action<HttpClient> configure)
|
||||
{
|
||||
var client = CreateClient();
|
||||
configure(client);
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides a stub HTTP message handler for hermetic HTTP tests without external dependencies.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// var handler = new HttpMessageHandlerStub()
|
||||
/// .WhenRequest("https://api.example.com/data")
|
||||
/// .Responds(HttpStatusCode.OK, "{\"status\":\"ok\"}");
|
||||
///
|
||||
/// var httpClient = new HttpClient(handler);
|
||||
/// var response = await httpClient.GetAsync("https://api.example.com/data");
|
||||
/// // response.StatusCode == HttpStatusCode.OK
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class HttpMessageHandlerStub : HttpMessageHandler
|
||||
{
|
||||
private readonly Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> _handlers = new();
|
||||
private Func<HttpRequestMessage, Task<HttpResponseMessage>>? _defaultHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Configures a response for a specific URL.
|
||||
/// </summary>
|
||||
public HttpMessageHandlerStub WhenRequest(string url, Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
|
||||
{
|
||||
_handlers[url] = handler;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a simple response for a specific URL.
|
||||
/// </summary>
|
||||
public HttpMessageHandlerStub WhenRequest(string url, HttpStatusCode statusCode, string? content = null)
|
||||
{
|
||||
return WhenRequest(url, _ => Task.FromResult(new HttpResponseMessage(statusCode)
|
||||
{
|
||||
Content = content != null ? new StringContent(content) : null
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a default handler for unmatched requests.
|
||||
/// </summary>
|
||||
public HttpMessageHandlerStub WhenAnyRequest(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
|
||||
{
|
||||
_defaultHandler = handler;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the HTTP request through the stub handler.
|
||||
/// </summary>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var url = request.RequestUri?.ToString() ?? string.Empty;
|
||||
|
||||
if (_handlers.TryGetValue(url, out var handler))
|
||||
{
|
||||
return await handler(request);
|
||||
}
|
||||
|
||||
if (_defaultHandler != null)
|
||||
{
|
||||
return await _defaultHandler(request);
|
||||
}
|
||||
|
||||
// Default: 404 Not Found for unmatched requests
|
||||
return new HttpResponseMessage(HttpStatusCode.NotFound)
|
||||
{
|
||||
Content = new StringContent($"No stub configured for {url}")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,98 @@
|
||||
using Testcontainers.Redis;
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.TestKit.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Test fixture for Valkey (Redis-compatible) using Testcontainers.
|
||||
/// Provides an isolated Valkey instance for integration tests.
|
||||
/// Provides a Testcontainers-based Valkey (Redis-compatible) instance for integration tests.
|
||||
/// </summary>
|
||||
public sealed class ValkeyFixture : IAsyncLifetime
|
||||
/// <remarks>
|
||||
/// Usage with xUnit:
|
||||
/// <code>
|
||||
/// public class MyTests : IClassFixture<ValkeyFixture>
|
||||
/// {
|
||||
/// private readonly ValkeyFixture _fixture;
|
||||
///
|
||||
/// public MyTests(ValkeyFixture fixture)
|
||||
/// {
|
||||
/// _fixture = fixture;
|
||||
/// }
|
||||
///
|
||||
/// [Fact]
|
||||
/// public async Task TestCache()
|
||||
/// {
|
||||
/// var connection = await ConnectionMultiplexer.Connect(_fixture.ConnectionString);
|
||||
/// var db = connection.GetDatabase();
|
||||
/// await db.StringSetAsync("key", "value");
|
||||
/// // ...
|
||||
/// }
|
||||
/// }
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class ValkeyFixture : IAsyncLifetime, IDisposable
|
||||
{
|
||||
private readonly RedisContainer _container;
|
||||
|
||||
public ValkeyFixture()
|
||||
{
|
||||
_container = new RedisBuilder()
|
||||
.WithImage("valkey/valkey:8-alpine")
|
||||
.Build();
|
||||
}
|
||||
private IContainer? _container;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the connection string for the Valkey container.
|
||||
/// Gets the Redis/Valkey connection string (format: "host:port").
|
||||
/// </summary>
|
||||
public string ConnectionString => _container.GetConnectionString();
|
||||
public string ConnectionString { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hostname of the Valkey container.
|
||||
/// Gets the Redis/Valkey host.
|
||||
/// </summary>
|
||||
public string Host => _container.Hostname;
|
||||
public string Host { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the exposed port of the Valkey container.
|
||||
/// Gets the Redis/Valkey port.
|
||||
/// </summary>
|
||||
public ushort Port => _container.GetMappedPublicPort(6379);
|
||||
public int Port { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the Valkey container asynchronously.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
// Use official Redis image (Valkey is Redis-compatible)
|
||||
// In production deployments, substitute with valkey/valkey image if needed
|
||||
_container = new ContainerBuilder()
|
||||
.WithImage("redis:7-alpine")
|
||||
.WithPortBinding(6379, true) // Bind to random host port
|
||||
.WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(6379))
|
||||
.Build();
|
||||
|
||||
await _container.StartAsync();
|
||||
|
||||
Host = _container.Hostname;
|
||||
Port = _container.GetMappedPublicPort(6379);
|
||||
ConnectionString = $"{Host}:{Port}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the Valkey container asynchronously.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _container.DisposeAsync();
|
||||
if (_container != null)
|
||||
{
|
||||
await _container.StopAsync();
|
||||
await _container.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the fixture.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DisposeAsync().GetAwaiter().GetResult();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collection fixture for Valkey to share the container across multiple test classes.
|
||||
/// </summary>
|
||||
[CollectionDefinition("Valkey")]
|
||||
public class ValkeyCollection : ICollectionFixture<ValkeyFixture>
|
||||
{
|
||||
// This class has no code, and is never created. Its purpose is simply
|
||||
// to be the place to apply [CollectionDefinition] and all the
|
||||
// ICollectionFixture<> interfaces.
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace StellaOps.TestKit.Json;
|
||||
|
||||
/// <summary>
|
||||
/// Assertion helpers for canonical JSON comparison in tests.
|
||||
/// Ensures deterministic serialization with sorted keys and normalized formatting.
|
||||
/// </summary>
|
||||
public static class CanonicalJsonAssert
|
||||
{
|
||||
private static readonly JsonSerializerOptions CanonicalOptions = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
PropertyNamingPolicy = null,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
PropertyNameCaseInsensitive = false,
|
||||
// Ensure deterministic property ordering
|
||||
PropertyOrder = 0
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that two JSON strings are canonically equivalent.
|
||||
/// </summary>
|
||||
/// <param name="expected">The expected JSON.</param>
|
||||
/// <param name="actual">The actual JSON.</param>
|
||||
public static void Equal(string expected, string actual)
|
||||
{
|
||||
var expectedCanonical = Canonicalize(expected);
|
||||
var actualCanonical = Canonicalize(actual);
|
||||
|
||||
if (expectedCanonical != actualCanonical)
|
||||
{
|
||||
throw new CanonicalJsonAssertException(
|
||||
$"JSON mismatch:\nExpected (canonical):\n{expectedCanonical}\n\nActual (canonical):\n{actualCanonical}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that two objects produce canonically equivalent JSON when serialized.
|
||||
/// </summary>
|
||||
public static void EquivalentObjects<T>(T expected, T actual)
|
||||
{
|
||||
var expectedJson = JsonSerializer.Serialize(expected, CanonicalOptions);
|
||||
var actualJson = JsonSerializer.Serialize(actual, CanonicalOptions);
|
||||
|
||||
Equal(expectedJson, actualJson);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes a JSON string by parsing and re-serializing with deterministic formatting.
|
||||
/// </summary>
|
||||
public static string Canonicalize(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
return JsonSerializer.Serialize(doc.RootElement, CanonicalOptions);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new CanonicalJsonAssertException($"Failed to parse JSON: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a stable hash of canonical JSON for comparison.
|
||||
/// </summary>
|
||||
public static string ComputeHash(string json)
|
||||
{
|
||||
var canonical = Canonicalize(json);
|
||||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||
var hashBytes = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(canonical));
|
||||
return Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that JSON matches a specific hash (for regression testing).
|
||||
/// </summary>
|
||||
public static void MatchesHash(string expectedHash, string json)
|
||||
{
|
||||
var actualHash = ComputeHash(json);
|
||||
if (!string.Equals(expectedHash, actualHash, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new CanonicalJsonAssertException(
|
||||
$"JSON hash mismatch:\nExpected hash: {expectedHash}\nActual hash: {actualHash}\n\nJSON (canonical):\n{Canonicalize(json)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when canonical JSON assertions fail.
|
||||
/// </summary>
|
||||
public sealed class CanonicalJsonAssertException : Exception
|
||||
{
|
||||
public CanonicalJsonAssertException(string message) : base(message) { }
|
||||
public CanonicalJsonAssertException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
162
src/__Libraries/StellaOps.TestKit/Observability/OtelCapture.cs
Normal file
162
src/__Libraries/StellaOps.TestKit/Observability/OtelCapture.cs
Normal file
@@ -0,0 +1,162 @@
|
||||
using System.Diagnostics;
|
||||
using OpenTelemetry;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.TestKit.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// Captures OpenTelemetry traces and spans during test execution for assertion.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage:
|
||||
/// <code>
|
||||
/// using var capture = new OtelCapture();
|
||||
///
|
||||
/// // Execute code that emits traces
|
||||
/// await MyService.DoWorkAsync();
|
||||
///
|
||||
/// // Assert traces were emitted
|
||||
/// capture.AssertHasSpan("MyService.DoWork");
|
||||
/// capture.AssertHasTag("user_id", "123");
|
||||
/// capture.AssertSpanCount(expectedCount: 3);
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public sealed class OtelCapture : IDisposable
|
||||
{
|
||||
private readonly List<Activity> _capturedActivities = new();
|
||||
private readonly ActivityListener _listener;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new OTel capture and starts listening for activities.
|
||||
/// </summary>
|
||||
/// <param name="activitySourceName">Optional activity source name filter. If null, captures all activities.</param>
|
||||
public OtelCapture(string? activitySourceName = null)
|
||||
{
|
||||
_listener = new ActivityListener
|
||||
{
|
||||
ShouldListenTo = source => activitySourceName == null || source.Name == activitySourceName,
|
||||
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded,
|
||||
ActivityStopped = activity =>
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
_capturedActivities.Add(activity);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ActivitySource.AddActivityListener(_listener);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all captured activities (spans).
|
||||
/// </summary>
|
||||
public IReadOnlyList<Activity> CapturedActivities
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
return _capturedActivities.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a span with the specified name was captured.
|
||||
/// </summary>
|
||||
public void AssertHasSpan(string spanName)
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
Assert.Contains(_capturedActivities, a => a.DisplayName == spanName || a.OperationName == spanName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that at least one span has the specified tag (attribute).
|
||||
/// </summary>
|
||||
public void AssertHasTag(string tagKey, string expectedValue)
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
var found = _capturedActivities.Any(a =>
|
||||
a.Tags.Any(tag => tag.Key == tagKey && tag.Value == expectedValue));
|
||||
|
||||
Assert.True(found, $"No span found with tag {tagKey}={expectedValue}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that exactly the specified number of spans were captured.
|
||||
/// </summary>
|
||||
public void AssertSpanCount(int expectedCount)
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
Assert.Equal(expectedCount, _capturedActivities.Count);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a span with the specified name has the expected tag.
|
||||
/// </summary>
|
||||
public void AssertSpanHasTag(string spanName, string tagKey, string expectedValue)
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
var span = _capturedActivities.FirstOrDefault(a =>
|
||||
a.DisplayName == spanName || a.OperationName == spanName);
|
||||
|
||||
Assert.NotNull(span);
|
||||
|
||||
var tag = span.Tags.FirstOrDefault(t => t.Key == tagKey);
|
||||
Assert.True(tag.Key != null, $"Tag '{tagKey}' not found in span '{spanName}'");
|
||||
Assert.Equal(expectedValue, tag.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that spans form a valid parent-child hierarchy.
|
||||
/// </summary>
|
||||
public void AssertHierarchy(string parentSpanName, string childSpanName)
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
var parent = _capturedActivities.FirstOrDefault(a =>
|
||||
a.DisplayName == parentSpanName || a.OperationName == parentSpanName);
|
||||
var child = _capturedActivities.FirstOrDefault(a =>
|
||||
a.DisplayName == childSpanName || a.OperationName == childSpanName);
|
||||
|
||||
Assert.NotNull(parent);
|
||||
Assert.NotNull(child);
|
||||
Assert.Equal(parent.SpanId, child.ParentSpanId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all captured activities.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_capturedActivities)
|
||||
{
|
||||
_capturedActivities.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the capture and stops listening for activities.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_listener?.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
@@ -1,174 +1,28 @@
|
||||
# StellaOps.TestKit
|
||||
|
||||
Test infrastructure and fixtures for StellaOps projects. Provides deterministic time/random, canonical JSON assertions, snapshot testing, database fixtures, and OpenTelemetry capture.
|
||||
Testing infrastructure for StellaOps - deterministic helpers, fixtures, and assertions.
|
||||
|
||||
## Features
|
||||
## Quick Start
|
||||
|
||||
### Deterministic Time
|
||||
```csharp
|
||||
using StellaOps.TestKit.Time;
|
||||
|
||||
// Create a clock at a fixed time
|
||||
var clock = new DeterministicClock();
|
||||
var now = clock.UtcNow; // 2025-01-01T00:00:00Z
|
||||
|
||||
// Advance time
|
||||
clock.Advance(TimeSpan.FromMinutes(5));
|
||||
|
||||
// Or use helpers
|
||||
var clock2 = DeterministicClockExtensions.AtTestEpoch();
|
||||
var clock3 = DeterministicClockExtensions.At("2025-06-15T10:30:00Z");
|
||||
```
|
||||
|
||||
### Deterministic Random
|
||||
```csharp
|
||||
using StellaOps.TestKit.Random;
|
||||
|
||||
// Create deterministic RNG with standard test seed (42)
|
||||
var rng = DeterministicRandomExtensions.WithTestSeed();
|
||||
|
||||
// Generate reproducible values
|
||||
var number = rng.Next(1, 100);
|
||||
var text = rng.NextString(10);
|
||||
var item = rng.PickOne(new[] { "a", "b", "c" });
|
||||
```
|
||||
|
||||
### Canonical JSON Assertions
|
||||
```csharp
|
||||
using StellaOps.TestKit.Json;
|
||||
|
||||
// Assert JSON equality (ignores formatting)
|
||||
CanonicalJsonAssert.Equal(expectedJson, actualJson);
|
||||
|
||||
// Assert object equivalence
|
||||
CanonicalJsonAssert.EquivalentObjects(expectedObj, actualObj);
|
||||
|
||||
// Hash-based regression testing
|
||||
var hash = CanonicalJsonAssert.ComputeHash(json);
|
||||
CanonicalJsonAssert.MatchesHash("abc123...", json);
|
||||
using var time = new DeterministicTime(new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc));
|
||||
var timestamp = time.UtcNow; // Always 2026-01-15T10:30:00Z
|
||||
```
|
||||
|
||||
### Snapshot Testing
|
||||
```csharp
|
||||
using StellaOps.TestKit.Snapshots;
|
||||
|
||||
public class MyTests
|
||||
{
|
||||
[Fact]
|
||||
public void TestOutput()
|
||||
{
|
||||
var output = GenerateSomeOutput();
|
||||
|
||||
// Compare against __snapshots__/test_output.txt
|
||||
var snapshotPath = SnapshotHelper.GetSnapshotPath("test_output");
|
||||
SnapshotHelper.VerifySnapshot(output, snapshotPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestJsonOutput()
|
||||
{
|
||||
var obj = new { Name = "test", Value = 42 };
|
||||
|
||||
// Compare JSON serialization
|
||||
var snapshotPath = SnapshotHelper.GetSnapshotPath("test_json", ".json");
|
||||
SnapshotHelper.VerifyJsonSnapshot(obj, snapshotPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Update snapshots: set environment variable UPDATE_SNAPSHOTS=1
|
||||
SnapshotAssert.MatchesSnapshot(sbom, "TestSbom");
|
||||
// Update: UPDATE_SNAPSHOTS=1 dotnet test
|
||||
```
|
||||
|
||||
### PostgreSQL Fixture
|
||||
### PostgreSQL Integration
|
||||
```csharp
|
||||
using StellaOps.TestKit.Fixtures;
|
||||
using Xunit;
|
||||
|
||||
[Collection("Postgres")]
|
||||
public class DatabaseTests
|
||||
public class Tests : IClassFixture<PostgresFixture>
|
||||
{
|
||||
private readonly PostgresFixture _postgres;
|
||||
|
||||
public DatabaseTests(PostgresFixture postgres)
|
||||
{
|
||||
_postgres = postgres;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestQuery()
|
||||
{
|
||||
// Use connection string
|
||||
await using var conn = new Npgsql.NpgsqlConnection(_postgres.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
|
||||
// Execute SQL
|
||||
await _postgres.ExecuteSqlAsync("CREATE TABLE test (id INT)");
|
||||
|
||||
// Create additional databases
|
||||
await _postgres.CreateDatabaseAsync("otherdb");
|
||||
}
|
||||
public async Task TestDb() { /* use _fixture.ConnectionString */ }
|
||||
}
|
||||
```
|
||||
|
||||
### Valkey/Redis Fixture
|
||||
```csharp
|
||||
using StellaOps.TestKit.Fixtures;
|
||||
using Xunit;
|
||||
|
||||
[Collection("Valkey")]
|
||||
public class CacheTests
|
||||
{
|
||||
private readonly ValkeyFixture _valkey;
|
||||
|
||||
public CacheTests(ValkeyFixture valkey)
|
||||
{
|
||||
_valkey = valkey;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestCache()
|
||||
{
|
||||
var connectionString = _valkey.ConnectionString;
|
||||
// Use with your Redis/Valkey client
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### OpenTelemetry Capture
|
||||
```csharp
|
||||
using StellaOps.TestKit.Telemetry;
|
||||
|
||||
[Fact]
|
||||
public void TestTracing()
|
||||
{
|
||||
using var otel = new OTelCapture("my-service");
|
||||
|
||||
// Code that emits traces
|
||||
using (var activity = otel.ActivitySource.StartActivity("operation"))
|
||||
{
|
||||
activity?.SetTag("key", "value");
|
||||
}
|
||||
|
||||
// Assert traces
|
||||
otel.AssertActivityExists("operation");
|
||||
otel.AssertActivityHasTag("operation", "key", "value");
|
||||
|
||||
// Get summary for debugging
|
||||
Console.WriteLine(otel.GetTraceSummary());
|
||||
}
|
||||
```
|
||||
|
||||
## Usage in Tests
|
||||
|
||||
Add to your test project:
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\__Libraries\StellaOps.TestKit\StellaOps.TestKit.csproj" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
## Design Principles
|
||||
|
||||
- **Determinism**: All utilities produce reproducible results
|
||||
- **Offline-first**: No network dependencies (uses Testcontainers for local infrastructure)
|
||||
- **Minimal dependencies**: Only essential packages
|
||||
- **xUnit-friendly**: Works seamlessly with xUnit fixtures and collections
|
||||
See full documentation in this README.
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
namespace StellaOps.TestKit.Random;
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic random number generator for testing with reproducible sequences.
|
||||
/// </summary>
|
||||
public sealed class DeterministicRandom
|
||||
{
|
||||
private readonly System.Random _rng;
|
||||
private readonly int _seed;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deterministic random number generator with the specified seed.
|
||||
/// </summary>
|
||||
/// <param name="seed">The seed value. If null, uses 42 (standard test seed).</param>
|
||||
public DeterministicRandom(int? seed = null)
|
||||
{
|
||||
_seed = seed ?? 42;
|
||||
_rng = new System.Random(_seed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the seed used for this random number generator.
|
||||
/// </summary>
|
||||
public int Seed => _seed;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a non-negative random integer.
|
||||
/// </summary>
|
||||
public int Next() => _rng.Next();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a non-negative random integer less than the specified maximum.
|
||||
/// </summary>
|
||||
public int Next(int maxValue) => _rng.Next(maxValue);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random integer within the specified range.
|
||||
/// </summary>
|
||||
public int Next(int minValue, int maxValue) => _rng.Next(minValue, maxValue);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random double between 0.0 and 1.0.
|
||||
/// </summary>
|
||||
public double NextDouble() => _rng.NextDouble();
|
||||
|
||||
/// <summary>
|
||||
/// Fills the specified byte array with random bytes.
|
||||
/// </summary>
|
||||
public void NextBytes(byte[] buffer) => _rng.NextBytes(buffer);
|
||||
|
||||
/// <summary>
|
||||
/// Fills the specified span with random bytes.
|
||||
/// </summary>
|
||||
public void NextBytes(Span<byte> buffer) => _rng.NextBytes(buffer);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random boolean value.
|
||||
/// </summary>
|
||||
public bool NextBool() => _rng.Next(2) == 1;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a random string of the specified length using alphanumeric characters.
|
||||
/// </summary>
|
||||
public string NextString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
var result = new char[length];
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
result[i] = chars[_rng.Next(chars.Length)];
|
||||
}
|
||||
return new string(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects a random element from the specified collection.
|
||||
/// </summary>
|
||||
public T PickOne<T>(IReadOnlyList<T> items)
|
||||
{
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new ArgumentException("Cannot pick from empty collection", nameof(items));
|
||||
}
|
||||
return items[_rng.Next(items.Count)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extensions for working with deterministic random generators in tests.
|
||||
/// </summary>
|
||||
public static class DeterministicRandomExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Standard test seed value.
|
||||
/// </summary>
|
||||
public const int TestSeed = 42;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic random generator with the standard test seed.
|
||||
/// </summary>
|
||||
public static DeterministicRandom WithTestSeed() => new(TestSeed);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic random generator with a specific seed.
|
||||
/// </summary>
|
||||
public static DeterministicRandom WithSeed(int seed) => new(seed);
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace StellaOps.TestKit.Snapshots;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for snapshot testing - comparing test output against golden files.
|
||||
/// </summary>
|
||||
public static class SnapshotHelper
|
||||
{
|
||||
private static readonly JsonSerializerOptions DefaultOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that actual content matches a snapshot file.
|
||||
/// </summary>
|
||||
/// <param name="actual">The actual content to verify.</param>
|
||||
/// <param name="snapshotPath">Path to the snapshot file.</param>
|
||||
/// <param name="updateSnapshots">If true, updates the snapshot file instead of comparing. Use for regenerating snapshots.</param>
|
||||
public static void VerifySnapshot(string actual, string snapshotPath, bool updateSnapshots = false)
|
||||
{
|
||||
var normalizedActual = NormalizeLineEndings(actual);
|
||||
|
||||
if (updateSnapshots)
|
||||
{
|
||||
// Update mode: write the snapshot
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(snapshotPath)!);
|
||||
File.WriteAllText(snapshotPath, normalizedActual, Encoding.UTF8);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify mode: compare against existing snapshot
|
||||
if (!File.Exists(snapshotPath))
|
||||
{
|
||||
throw new SnapshotMismatchException(
|
||||
$"Snapshot file not found: {snapshotPath}\n\nTo create it, run with updateSnapshots=true or set environment variable UPDATE_SNAPSHOTS=1");
|
||||
}
|
||||
|
||||
var expected = File.ReadAllText(snapshotPath, Encoding.UTF8);
|
||||
var normalizedExpected = NormalizeLineEndings(expected);
|
||||
|
||||
if (normalizedActual != normalizedExpected)
|
||||
{
|
||||
throw new SnapshotMismatchException(
|
||||
$"Snapshot mismatch for {Path.GetFileName(snapshotPath)}:\n\nExpected:\n{normalizedExpected}\n\nActual:\n{normalizedActual}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that an object's JSON serialization matches a snapshot file.
|
||||
/// </summary>
|
||||
public static void VerifyJsonSnapshot<T>(T value, string snapshotPath, bool updateSnapshots = false, JsonSerializerOptions? options = null)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(value, options ?? DefaultOptions);
|
||||
VerifySnapshot(json, snapshotPath, updateSnapshots);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the snapshot directory for the calling test class.
|
||||
/// </summary>
|
||||
/// <param name="testFilePath">Automatically populated by compiler.</param>
|
||||
/// <returns>Path to the __snapshots__ directory next to the test file.</returns>
|
||||
public static string GetSnapshotDirectory([CallerFilePath] string testFilePath = "")
|
||||
{
|
||||
var testDir = Path.GetDirectoryName(testFilePath)!;
|
||||
return Path.Combine(testDir, "__snapshots__");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full path for a snapshot file.
|
||||
/// </summary>
|
||||
/// <param name="snapshotName">Name of the snapshot file (without extension).</param>
|
||||
/// <param name="extension">File extension (default: .txt).</param>
|
||||
/// <param name="testFilePath">Automatically populated by compiler.</param>
|
||||
public static string GetSnapshotPath(
|
||||
string snapshotName,
|
||||
string extension = ".txt",
|
||||
[CallerFilePath] string testFilePath = "")
|
||||
{
|
||||
var snapshotDir = GetSnapshotDirectory(testFilePath);
|
||||
var fileName = $"{snapshotName}{extension}";
|
||||
return Path.Combine(snapshotDir, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes line endings to LF for cross-platform consistency.
|
||||
/// </summary>
|
||||
private static string NormalizeLineEndings(string content)
|
||||
{
|
||||
return content.Replace("\r\n", "\n").Replace("\r", "\n");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if snapshot update mode is enabled via environment variable.
|
||||
/// </summary>
|
||||
public static bool IsUpdateMode()
|
||||
{
|
||||
var updateEnv = Environment.GetEnvironmentVariable("UPDATE_SNAPSHOTS");
|
||||
return string.Equals(updateEnv, "1", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(updateEnv, "true", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when snapshot verification fails.
|
||||
/// </summary>
|
||||
public sealed class SnapshotMismatchException : Exception
|
||||
{
|
||||
public SnapshotMismatchException(string message) : base(message) { }
|
||||
}
|
||||
@@ -1,30 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<IsPackable>true</IsPackable>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<Description>Testing infrastructure and utilities for StellaOps</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>StellaOps.TestKit</AssemblyName>
|
||||
<RootNamespace>StellaOps.TestKit</RootNamespace>
|
||||
<Description>Test infrastructure and fixtures for StellaOps projects - deterministic time/random, canonical JSON, snapshots, and database fixtures</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.abstractions" Version="2.0.3" />
|
||||
<PackageReference Include="xunit.extensibility.core" Version="2.9.2" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" Version="4.1.0" />
|
||||
<PackageReference Include="Testcontainers.Redis" Version="4.1.0" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.2" />
|
||||
<PackageReference Include="System.Text.Json" Version="10.0.0" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.10.0" />
|
||||
<PackageReference Include="OpenTelemetry.Api" Version="1.10.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.InMemory" Version="1.10.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="FsCheck" Version="2.16.6" />
|
||||
<PackageReference Include="FsCheck.Xunit" Version="2.16.6" />
|
||||
<PackageReference Include="Testcontainers" Version="3.10.0" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" Version="3.10.0" />
|
||||
<PackageReference Include="Npgsql" Version="8.0.5" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.9.0" />
|
||||
<PackageReference Include="OpenTelemetry.Api" Version="1.9.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\StellaOps.Canonical.Json\StellaOps.Canonical.Json.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
using OpenTelemetry;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace StellaOps.TestKit.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// Captures OpenTelemetry traces in-memory for testing.
|
||||
/// </summary>
|
||||
public sealed class OTelCapture : IDisposable
|
||||
{
|
||||
private readonly TracerProvider _tracerProvider;
|
||||
private readonly InMemoryExporter _exporter;
|
||||
private readonly ActivitySource _activitySource;
|
||||
|
||||
public OTelCapture(string serviceName = "test-service")
|
||||
{
|
||||
_exporter = new InMemoryExporter();
|
||||
_activitySource = new ActivitySource(serviceName);
|
||||
|
||||
_tracerProvider = Sdk.CreateTracerProviderBuilder()
|
||||
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName))
|
||||
.AddSource(serviceName)
|
||||
.AddInMemoryExporter(_exporter)
|
||||
.Build()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all captured activities (spans).
|
||||
/// </summary>
|
||||
public IReadOnlyList<Activity> Activities => _exporter.Activities;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the activity source for creating spans in tests.
|
||||
/// </summary>
|
||||
public ActivitySource ActivitySource => _activitySource;
|
||||
|
||||
/// <summary>
|
||||
/// Clears all captured activities.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
_exporter.Activities.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds activities by operation name.
|
||||
/// </summary>
|
||||
public IEnumerable<Activity> FindByOperationName(string operationName)
|
||||
{
|
||||
return Activities.Where(a => a.OperationName == operationName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds activities by tag value.
|
||||
/// </summary>
|
||||
public IEnumerable<Activity> FindByTag(string tagKey, string tagValue)
|
||||
{
|
||||
return Activities.Where(a => a.Tags.Any(t => t.Key == tagKey && t.Value == tagValue));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that at least one activity with the specified operation name exists.
|
||||
/// </summary>
|
||||
public void AssertActivityExists(string operationName)
|
||||
{
|
||||
if (!Activities.Any(a => a.OperationName == operationName))
|
||||
{
|
||||
var availableOps = string.Join(", ", Activities.Select(a => a.OperationName).Distinct());
|
||||
throw new OTelAssertException(
|
||||
$"No activity found with operation name '{operationName}'. Available operations: {availableOps}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that an activity has a specific tag.
|
||||
/// </summary>
|
||||
public void AssertActivityHasTag(string operationName, string tagKey, string expectedValue)
|
||||
{
|
||||
var activities = FindByOperationName(operationName).ToList();
|
||||
if (activities.Count == 0)
|
||||
{
|
||||
throw new OTelAssertException($"No activity found with operation name '{operationName}'");
|
||||
}
|
||||
|
||||
var activity = activities.First();
|
||||
var tag = activity.Tags.FirstOrDefault(t => t.Key == tagKey);
|
||||
if (tag.Key == null)
|
||||
{
|
||||
throw new OTelAssertException($"Activity '{operationName}' does not have tag '{tagKey}'");
|
||||
}
|
||||
|
||||
if (tag.Value != expectedValue)
|
||||
{
|
||||
throw new OTelAssertException(
|
||||
$"Tag '{tagKey}' on activity '{operationName}' has value '{tag.Value}' but expected '{expectedValue}'");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a summary of captured traces for debugging.
|
||||
/// </summary>
|
||||
public string GetTraceSummary()
|
||||
{
|
||||
if (Activities.Count == 0)
|
||||
{
|
||||
return "No traces captured";
|
||||
}
|
||||
|
||||
var summary = new System.Text.StringBuilder();
|
||||
summary.AppendLine($"Captured {Activities.Count} activities:");
|
||||
foreach (var activity in Activities)
|
||||
{
|
||||
summary.AppendLine($" - {activity.OperationName} ({activity.Duration.TotalMilliseconds:F2}ms)");
|
||||
foreach (var tag in activity.Tags)
|
||||
{
|
||||
summary.AppendLine($" {tag.Key} = {tag.Value}");
|
||||
}
|
||||
}
|
||||
return summary.ToString();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_tracerProvider?.Dispose();
|
||||
_activitySource?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In-memory exporter for OpenTelemetry activities.
|
||||
/// </summary>
|
||||
internal sealed class InMemoryExporter
|
||||
{
|
||||
public List<Activity> Activities { get; } = new();
|
||||
|
||||
public void Export(Activity activity)
|
||||
{
|
||||
Activities.Add(activity);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when OTel assertions fail.
|
||||
/// </summary>
|
||||
public sealed class OTelAssertException : Exception
|
||||
{
|
||||
public OTelAssertException(string message) : base(message) { }
|
||||
}
|
||||
63
src/__Libraries/StellaOps.TestKit/TestCategories.cs
Normal file
63
src/__Libraries/StellaOps.TestKit/TestCategories.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
namespace StellaOps.TestKit;
|
||||
|
||||
/// <summary>
|
||||
/// Standardized test trait categories for organizing and filtering tests in CI pipelines.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Usage with xUnit:
|
||||
/// <code>
|
||||
/// [Fact, Trait("Category", TestCategories.Unit)]
|
||||
/// public void TestBusinessLogic() { }
|
||||
///
|
||||
/// [Fact, Trait("Category", TestCategories.Integration)]
|
||||
/// public async Task TestDatabaseAccess() { }
|
||||
/// </code>
|
||||
///
|
||||
/// Filter by category during test runs:
|
||||
/// <code>
|
||||
/// dotnet test --filter "Category=Unit"
|
||||
/// dotnet test --filter "Category!=Live"
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
public static class TestCategories
|
||||
{
|
||||
/// <summary>
|
||||
/// Unit tests: Fast, in-memory, no external dependencies.
|
||||
/// </summary>
|
||||
public const string Unit = "Unit";
|
||||
|
||||
/// <summary>
|
||||
/// Property-based tests: FsCheck/generative testing for invariants.
|
||||
/// </summary>
|
||||
public const string Property = "Property";
|
||||
|
||||
/// <summary>
|
||||
/// Snapshot tests: Golden master regression testing.
|
||||
/// </summary>
|
||||
public const string Snapshot = "Snapshot";
|
||||
|
||||
/// <summary>
|
||||
/// Integration tests: Testcontainers, PostgreSQL, Valkey, etc.
|
||||
/// </summary>
|
||||
public const string Integration = "Integration";
|
||||
|
||||
/// <summary>
|
||||
/// Contract tests: API/WebService contract verification.
|
||||
/// </summary>
|
||||
public const string Contract = "Contract";
|
||||
|
||||
/// <summary>
|
||||
/// Security tests: Cryptographic validation, vulnerability scanning.
|
||||
/// </summary>
|
||||
public const string Security = "Security";
|
||||
|
||||
/// <summary>
|
||||
/// Performance tests: Benchmarking, load testing.
|
||||
/// </summary>
|
||||
public const string Performance = "Performance";
|
||||
|
||||
/// <summary>
|
||||
/// Live tests: Require external services (e.g., Rekor, NuGet feeds). Disabled by default in CI.
|
||||
/// </summary>
|
||||
public const string Live = "Live";
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
namespace StellaOps.TestKit.Time;
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic clock for testing that returns a fixed time.
|
||||
/// </summary>
|
||||
public sealed class DeterministicClock
|
||||
{
|
||||
private DateTimeOffset _currentTime;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new deterministic clock with the specified initial time.
|
||||
/// </summary>
|
||||
/// <param name="initialTime">The initial time. If null, uses 2025-01-01T00:00:00Z.</param>
|
||||
public DeterministicClock(DateTimeOffset? initialTime = null)
|
||||
{
|
||||
_currentTime = initialTime ?? new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current time.
|
||||
/// </summary>
|
||||
public DateTimeOffset UtcNow => _currentTime;
|
||||
|
||||
/// <summary>
|
||||
/// Advances the clock by the specified duration.
|
||||
/// </summary>
|
||||
/// <param name="duration">The duration to advance.</param>
|
||||
public void Advance(TimeSpan duration)
|
||||
{
|
||||
_currentTime = _currentTime.Add(duration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the clock to a specific time.
|
||||
/// </summary>
|
||||
/// <param name="time">The time to set.</param>
|
||||
public void SetTime(DateTimeOffset time)
|
||||
{
|
||||
_currentTime = time;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the clock to the initial time.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_currentTime = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extensions for working with deterministic clocks in tests.
|
||||
/// </summary>
|
||||
public static class DeterministicClockExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Standard test epoch: 2025-01-01T00:00:00Z
|
||||
/// </summary>
|
||||
public static readonly DateTimeOffset TestEpoch = new(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a clock at the standard test epoch.
|
||||
/// </summary>
|
||||
public static DeterministicClock AtTestEpoch() => new(TestEpoch);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a clock at a specific ISO 8601 timestamp.
|
||||
/// </summary>
|
||||
public static DeterministicClock At(string iso8601) => new(DateTimeOffset.Parse(iso8601));
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using Xunit.Abstractions;
|
||||
using Xunit.Sdk;
|
||||
|
||||
namespace StellaOps.TestKit.Traits;
|
||||
|
||||
/// <summary>
|
||||
/// Trait discoverer for Lane attribute.
|
||||
/// </summary>
|
||||
public sealed class LaneTraitDiscoverer : ITraitDiscoverer
|
||||
{
|
||||
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
|
||||
{
|
||||
var lane = traitAttribute.GetNamedArgument<string>(nameof(LaneAttribute.Lane))
|
||||
?? traitAttribute.GetConstructorArguments().FirstOrDefault()?.ToString();
|
||||
|
||||
if (!string.IsNullOrEmpty(lane))
|
||||
{
|
||||
yield return new KeyValuePair<string, string>("Lane", lane);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
using Xunit.Sdk;
|
||||
|
||||
namespace StellaOps.TestKit.Traits;
|
||||
|
||||
/// <summary>
|
||||
/// Base attribute for test traits that categorize tests by lane and type.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
|
||||
public abstract class TestTraitAttributeBase : Attribute, ITraitAttribute
|
||||
{
|
||||
protected TestTraitAttributeBase(string traitName, string value)
|
||||
{
|
||||
TraitName = traitName;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public string TraitName { get; }
|
||||
public string Value { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as belonging to a specific test lane.
|
||||
/// Lanes: Unit, Contract, Integration, Security, Performance, Live
|
||||
/// </summary>
|
||||
[TraitDiscoverer("StellaOps.TestKit.Traits.LaneTraitDiscoverer", "StellaOps.TestKit")]
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
|
||||
public sealed class LaneAttribute : Attribute, ITraitAttribute
|
||||
{
|
||||
public LaneAttribute(string lane)
|
||||
{
|
||||
Lane = lane ?? throw new ArgumentNullException(nameof(lane));
|
||||
}
|
||||
|
||||
public string Lane { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test with a specific test type trait.
|
||||
/// Common types: unit, property, snapshot, determinism, integration_postgres, contract, authz, etc.
|
||||
/// </summary>
|
||||
[TraitDiscoverer("StellaOps.TestKit.Traits.TestTypeTraitDiscoverer", "StellaOps.TestKit")]
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
|
||||
public sealed class TestTypeAttribute : Attribute, ITraitAttribute
|
||||
{
|
||||
public TestTypeAttribute(string testType)
|
||||
{
|
||||
TestType = testType ?? throw new ArgumentNullException(nameof(testType));
|
||||
}
|
||||
|
||||
public string TestType { get; }
|
||||
}
|
||||
|
||||
// Lane-specific convenience attributes
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a Unit test.
|
||||
/// </summary>
|
||||
public sealed class UnitTestAttribute : LaneAttribute
|
||||
{
|
||||
public UnitTestAttribute() : base("Unit") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a Contract test.
|
||||
/// </summary>
|
||||
public sealed class ContractTestAttribute : LaneAttribute
|
||||
{
|
||||
public ContractTestAttribute() : base("Contract") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as an Integration test.
|
||||
/// </summary>
|
||||
public sealed class IntegrationTestAttribute : LaneAttribute
|
||||
{
|
||||
public IntegrationTestAttribute() : base("Integration") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a Security test.
|
||||
/// </summary>
|
||||
public sealed class SecurityTestAttribute : LaneAttribute
|
||||
{
|
||||
public SecurityTestAttribute() : base("Security") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a Performance test.
|
||||
/// </summary>
|
||||
public sealed class PerformanceTestAttribute : LaneAttribute
|
||||
{
|
||||
public PerformanceTestAttribute() : base("Performance") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a Live test (requires external connectivity).
|
||||
/// These tests should be opt-in only and never PR-gating.
|
||||
/// </summary>
|
||||
public sealed class LiveTestAttribute : LaneAttribute
|
||||
{
|
||||
public LiveTestAttribute() : base("Live") { }
|
||||
}
|
||||
|
||||
// Test type-specific convenience attributes
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as testing determinism.
|
||||
/// </summary>
|
||||
public sealed class DeterminismTestAttribute : TestTypeAttribute
|
||||
{
|
||||
public DeterminismTestAttribute() : base("determinism") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a snapshot test.
|
||||
/// </summary>
|
||||
public sealed class SnapshotTestAttribute : TestTypeAttribute
|
||||
{
|
||||
public SnapshotTestAttribute() : base("snapshot") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as a property-based test.
|
||||
/// </summary>
|
||||
public sealed class PropertyTestAttribute : TestTypeAttribute
|
||||
{
|
||||
public PropertyTestAttribute() : base("property") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as an authorization test.
|
||||
/// </summary>
|
||||
public sealed class AuthzTestAttribute : TestTypeAttribute
|
||||
{
|
||||
public AuthzTestAttribute() : base("authz") { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test as testing OpenTelemetry traces.
|
||||
/// </summary>
|
||||
public sealed class OTelTestAttribute : TestTypeAttribute
|
||||
{
|
||||
public OTelTestAttribute() : base("otel") { }
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using Xunit.Abstractions;
|
||||
using Xunit.Sdk;
|
||||
|
||||
namespace StellaOps.TestKit.Traits;
|
||||
|
||||
/// <summary>
|
||||
/// Trait discoverer for TestType attribute.
|
||||
/// </summary>
|
||||
public sealed class TestTypeTraitDiscoverer : ITraitDiscoverer
|
||||
{
|
||||
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
|
||||
{
|
||||
var testType = traitAttribute.GetNamedArgument<string>(nameof(TestTypeAttribute.TestType))
|
||||
?? traitAttribute.GetConstructorArguments().FirstOrDefault()?.ToString();
|
||||
|
||||
if (!string.IsNullOrEmpty(testType))
|
||||
{
|
||||
yield return new KeyValuePair<string, string>("TestType", testType);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user