Skip to content
Open
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
21 changes: 19 additions & 2 deletions src/Nullean.Entities.CsCheck.FileSystem/FileWorld.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public FileWorld() : this(new MockFileSystem(), 0)
/// <summary>A world over a file system a baseline value already has; names start high so they cannot replace the baseline's own files.</summary>
public FileWorld(MockFileSystem fileSystem, int firstName = 10_000)
{
_counter = Counters.GetValue(fileSystem, _ => new StrongBox<int>(firstName));
_counter = Counters.GetValue(fileSystem, _ => new StrongBox<int>(firstName - 1));
FileSystem = fileSystem;
Root = OperatingSystem.IsWindows() ? @"C:\docs" : "/docs";
Outside = OperatingSystem.IsWindows() ? @"C:\elsewhere" : "/elsewhere";
Expand All @@ -92,15 +92,24 @@ public FileWorld(MockFileSystem fileSystem, int firstName = 10_000)

private string Combine(params string[] parts) => FileSystem.Path.Combine(parts);

private string NextName(PCG pcg) => $"{Words[(int)pcg.Next((uint)Words.Length)]}-{_counter.Value++}";
private string NextName(PCG pcg) => $"{Words[(int)pcg.Next((uint)Words.Length)]}-{Interlocked.Increment(ref _counter.Value)}";

private string Folder(PCG pcg)
{
var folder = Folders[(int)pcg.Next((uint)Folders.Length)];
return folder.Length == 0 ? Root : Combine(Root, folder.Replace('/', FileSystem.Path.DirectorySeparatorChar));
}

// Axes of one test run at the same time over a constant base, so its file system is shared: each draw changes it under a lock on it.
public IFileInfo File(PCG pcg, FileKind kind)
{
lock (FileSystem)
{
return FileCore(pcg, kind);
}
}

private IFileInfo FileCore(PCG pcg, FileKind kind)
{
var name = NextName(pcg);
switch (kind)
Expand Down Expand Up @@ -172,6 +181,14 @@ public IFileInfo File(PCG pcg, FileKind kind)
}

public IDirectoryInfo Directory(PCG pcg, DirectoryKind kind)
{
lock (FileSystem)
{
return DirectoryCore(pcg, kind);
}
}

private IDirectoryInfo DirectoryCore(PCG pcg, DirectoryKind kind)
{
switch (kind)
{
Expand Down
1 change: 1 addition & 0 deletions src/Nullean.Entities.CsCheck.FileSystem/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ where `valid` is one `Docset` whose files all satisfy the rules (for example, a
- The root is `/docs` (`C:\docs` on Windows) and the outside folder is `/elsewhere` (`C:\elsewhere`). A rule that depends on other paths needs a hand-built baseline.
- `MockFileSystem` is in-memory, so rules about permissions, locks or real disk behaviour are not exercised.
- Rules whose counter-examples need a structure the generator cannot draw (for example a specific folder name your rule looks for) still need one written by hand.
- A `Gen.Const` base is one `MockFileSystem` shared by every axis, and axes run at the same time. A counter-example given to `AutoTest` runs once per base, under a lock on it, and later axes reuse the result; the file system is not cloned, so a counter-example should add files rather than edit the base's own.
- It reaches the file-system members through AutoGen's reflection; do not reference it from an AOT-published app.

## Learn more
Expand Down
39 changes: 38 additions & 1 deletion src/Nullean.Entities.CsCheck/AutoTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// exposes each axis as a named method. Report() runs every axis and records what each did; Run() does the same and throws when any failed; Cases lists the
// axes the type actually declares, one per test, for a test framework's data source. An axis the type declares no rule for is reported, never passed in silence.

using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using CsCheck;

Expand Down Expand Up @@ -198,7 +199,43 @@ private AutoTest(
/// edge value where a single property breaks it alone; the others (sequential rules, <c>Idempotent</c>, cross-property rules) need one here, and axis 09 fails without it.
/// </summary>
public AutoTest<T> CounterExamples(IReadOnlyDictionary<string, Func<T, T>> counterExamples) =>
new(this, counterExamples: _counterExamples.Concat(counterExamples).GroupBy(kv => kv.Key).ToDictionary(g => g.Key, g => g.Last().Value));
new(
this,
counterExamples: _counterExamples
.Concat(counterExamples.Select(kv => new KeyValuePair<string, Func<T, T>>(kv.Key, AppliedOncePerBase(kv.Value))))
.GroupBy(kv => kv.Key)
.ToDictionary(g => g.Key, g => g.Last().Value)
);

/// <summary>
/// A constant generator (<c>Gen.Const</c>) hands every axis the same base object, and the axes run at the same time. A counter-example that changes the world its base holds
/// (adds a file to a <c>MockFileSystem</c>) would collide with itself, so it runs once per base, under a lock on that base; later applications get the value the first one made.
/// </summary>
private static Func<T, T> AppliedOncePerBase(Func<T, T> breakIt)
{
if (typeof(T).IsValueType)
{
return breakIt;
}
var made = new ConditionalWeakTable<object, StrongBox<T>>();
return value =>
{
if (value is null)
{
return breakIt(value);
}
lock (value)
{
if (made.TryGetValue(value, out var box))
{
return box.Value!;
}
var result = breakIt(value);
made.Add(value, new StrongBox<T>(result));
return result;
}
};
}

/// <summary>
/// The counter-example for one rule, named by the rule itself rather than by a string: a rename cannot orphan it and a typo does not compile.
Expand Down
26 changes: 26 additions & 0 deletions tests/Nullean.Entities.CsCheck.FileSystem.Tests/FileWorldTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,32 @@ public void The_laws_hold_for_the_file_rules_with_counter_examples_built_in_the_
Rules.Laws(valid, examples).Results.Should().HaveCount(6);
}

[Test]
public async Task A_counter_example_that_adds_a_file_survives_axes_running_at_once_on_one_constant_base()
{
// a Gen.Const base is one MockFileSystem; TUnit runs the Invariant and Vacancy cases at the same time, and both apply the counter-example to it
for (var attempt = 0; attempt < 30; attempt++)
{
var valid = Draw(AutoMode.Plausible, 40).First(d => d.Images.Count > 0);
var test = AutoTest
.For(Rules, Gen.Const(valid))
.Options(o => o.UseFileSystem())
.CounterExamples(new Dictionary<string, Func<Docset, Docset>>
{
["ImagesAreNotSymlinks"] = d =>
{
((MockFileSystem)d.FileSystem).AddFile("/docs/real.png", "x");
d.FileSystem.File.CreateSymbolicLink("/docs/link.png", "/docs/real.png");
return d with { Images = [d.FileSystem.FileInfo.New("/docs/link.png")] };
}
});

var results = await Task.WhenAll(Task.Run(test.InvariantAsync), Task.Run(test.VacancyAsync));

results.OfType<AxisResult.Failed>().Select(f => f.ToString()).Should().BeEmpty();
}
}

[Test]
public void Without_UseFileSystem_the_error_says_which_package_and_call_to_use()
{
Expand Down
Loading