From 14b26c1764a7259d67615b9da8917be423b553ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Fri, 30 Oct 2026 02:09:19 +0100 Subject: [PATCH] docs: set the examples in an abstract art gallery aweXpect, Mockolate and Awaiten each tell their examples in one theme, while the Abstractions examples used placeholders like foo.txt and ReportService. A shared gallery domain makes the examples easier to follow and remember, and enables a complete example that combines the file system, time and random system. --- .../companion-libraries/access-control.mdx | 8 +- .../docs/companion-libraries/compression.mdx | 14 +-- .../memory-mapped-files.mdx | 6 +- Docs/pages/docs/complete-example.mdx | 116 ++++++++++++++++++ .../pages/docs/file-system/access-control.mdx | 14 +-- Docs/pages/docs/file-system/drives.mdx | 20 +-- .../docs/file-system/file-system-watcher.mdx | 34 ++--- .../docs/file-system/file-version-info.mdx | 10 +- Docs/pages/docs/file-system/index.mdx | 16 +-- .../pages/docs/file-system/initialization.mdx | 58 ++++----- .../docs/file-system/intercept-and-notify.mdx | 20 +-- Docs/pages/docs/file-system/random-access.mdx | 12 +- .../docs/file-system/safe-file-handles.mdx | 10 +- Docs/pages/docs/file-system/statistics.mdx | 10 +- .../pages/docs/file-system/unix-file-mode.mdx | 20 +-- Docs/pages/docs/getting-started.mdx | 27 ++-- Docs/pages/docs/index.mdx | 61 +++++---- .../docs/migration-from-testableio/index.mdx | 14 +-- .../deterministic-randomness.mdx | 2 +- .../docs/time-system/configuring-time.mdx | 6 +- Docs/pages/docs/time-system/notifications.mdx | 2 +- .../pages/docs/time-system/periodic-timer.mdx | 38 +++--- 22 files changed, 318 insertions(+), 200 deletions(-) create mode 100644 Docs/pages/docs/complete-example.mdx diff --git a/Docs/pages/docs/companion-libraries/access-control.mdx b/Docs/pages/docs/companion-libraries/access-control.mdx index 3324a7837..3614bf927 100644 --- a/Docs/pages/docs/companion-libraries/access-control.mdx +++ b/Docs/pages/docs/companion-libraries/access-control.mdx @@ -29,11 +29,11 @@ Each `GetAccessControl` overload accepts an optional `AccessControlSections` mas ```csharp IFileSystem fileSystem; // injected -DirectorySecurity acl = fileSystem.Directory.GetAccessControl("data"); -fileSystem.Directory.SetAccessControl("backup", acl); +DirectorySecurity acl = fileSystem.Directory.GetAccessControl("archive"); +fileSystem.Directory.SetAccessControl("vault", acl); -fileSystem.File.WriteAllText("secret.txt", "x"); -FileSecurity fileAcl = fileSystem.File.GetAccessControl("secret.txt"); +fileSystem.File.WriteAllText("provenance.txt", ""); +FileSecurity fileAcl = fileSystem.File.GetAccessControl("provenance.txt"); ``` ## Behaviour on the mock diff --git a/Docs/pages/docs/companion-libraries/compression.mdx b/Docs/pages/docs/companion-libraries/compression.mdx index ea0e50e65..97c6d7589 100644 --- a/Docs/pages/docs/companion-libraries/compression.mdx +++ b/Docs/pages/docs/companion-libraries/compression.mdx @@ -20,7 +20,7 @@ dotnet add package Testably.Abstractions.Compression ```csharp // With Testably.Abstractions.Compression - one line: -fileSystem.ZipFile.CreateFromDirectory("source", "out.zip"); +fileSystem.ZipFile.CreateFromDirectory("artworks", "artworks.zip"); ```
@@ -30,7 +30,7 @@ fileSystem.ZipFile.CreateFromDirectory("source", "out.zip"); using MemoryStream buffer = new(); using (ZipArchive archive = new(buffer, ZipArchiveMode.Create, leaveOpen: true)) { - AddDirectory("", "source"); + AddDirectory("", "artworks"); void AddDirectory(string prefix, string directory) { @@ -49,7 +49,7 @@ using (ZipArchive archive = new(buffer, ZipArchiveMode.Create, leaveOpen: true)) } } buffer.Position = 0; -using FileSystemStream output = fileSystem.File.Create("out.zip"); +using FileSystemStream output = fileSystem.File.Create("artworks.zip"); buffer.CopyTo(output); ``` @@ -69,13 +69,13 @@ On `RealFileSystem`, every call forwards to the matching `System.IO.Compression` ```csharp fileSystem.ZipFile - .CreateFromDirectory("your-directory", "your-file.zip"); + .CreateFromDirectory("artworks", "artworks.zip"); fileSystem.ZipFile - .ExtractToDirectory("your-file.zip", "your-destination"); + .ExtractToDirectory("artworks.zip", "vault"); using IZipArchive archive = fileSystem.ZipFile - .Open("your-file.zip", ZipArchiveMode.Update); + .Open("artworks.zip", ZipArchiveMode.Update); ``` All overloads from the BCL are present, including the async variants on .NET 10+ (`CreateFromDirectoryAsync`, `ExtractToDirectoryAsync`, `OpenAsync`, `OpenReadAsync`). @@ -85,7 +85,7 @@ All overloads from the BCL are present, including the async variants on .NET 10+ `fileSystem.ZipArchive` is a factory for `IZipArchive` from a `Stream` (matches the `new ZipArchive(...)` constructors): ```csharp -using FileSystemStream stream = fileSystem.File.OpenRead("your-file.zip"); +using FileSystemStream stream = fileSystem.File.OpenRead("artworks.zip"); using IZipArchive archive = fileSystem.ZipArchive .New(stream, ZipArchiveMode.Read); diff --git a/Docs/pages/docs/companion-libraries/memory-mapped-files.mdx b/Docs/pages/docs/companion-libraries/memory-mapped-files.mdx index 94b18901d..b66a1f197 100644 --- a/Docs/pages/docs/companion-libraries/memory-mapped-files.mdx +++ b/Docs/pages/docs/companion-libraries/memory-mapped-files.mdx @@ -22,7 +22,7 @@ dotnet add package Testably.Abstractions.MemoryMappedFiles IFileSystem fileSystem = //... using IMemoryMappedFile mappedFile = fileSystem.MemoryMappedFile - .CreateFromFile("data.bin"); + .CreateFromFile("red-square.png"); using IMemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor(); accessor.Write(0, 42); @@ -41,7 +41,7 @@ On `RealFileSystem`, every call forwards to the base class library (BCL) `Memory ```csharp using IMemoryMappedFile fromPath = fileSystem.MemoryMappedFile - .CreateFromFile("data.bin", FileMode.Open, mapName: null, capacity: 0, + .CreateFromFile("red-square.png", FileMode.Open, mapName: null, capacity: 0, MemoryMappedFileAccess.ReadWrite); ``` @@ -49,7 +49,7 @@ The `FileStream`-based overload is exposed with a `FileSystemStream` instead of ```csharp using FileSystemStream stream = - fileSystem.FileStream.New("data.bin", FileMode.Open, FileAccess.ReadWrite); + fileSystem.FileStream.New("red-square.png", FileMode.Open, FileAccess.ReadWrite); using IMemoryMappedFile mappedFile = fileSystem.MemoryMappedFile.CreateFromFile( stream, mapName: null, capacity: 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true); diff --git a/Docs/pages/docs/complete-example.mdx b/Docs/pages/docs/complete-example.mdx new file mode 100644 index 000000000..870e5d729 --- /dev/null +++ b/Docs/pages/docs/complete-example.mdx @@ -0,0 +1,116 @@ +--- +sidebar_position: 5.5 +title: A complete example +description: One gallery service, tested with the mocked file system, time system and random system together. +--- + +# A complete example + +When an exhibition closes, the gallery moves its artworks into the vault. The `ExhibitionArchiver` below does that, and depends on all three abstractions: + +- `IFileSystem` to move the exhibition folder and write a note, +- `ITimeSystem` to decide whether the exhibition has closed, +- `IRandomSystem` to generate the archive number. + +```csharp title="ExhibitionArchiver.cs" +public record Exhibition(string Folder, DateTime ClosesAt); + +public class ExhibitionArchiver( + IFileSystem fileSystem, ITimeSystem timeSystem, IRandomSystem randomSystem) +{ + public string? ArchiveIfClosed(Exhibition exhibition) + { + if (timeSystem.DateTime.UtcNow < exhibition.ClosesAt) + { + return null; + } + + string archiveNumber = randomSystem.Guid.NewGuid().ToString("N").Substring(0, 8); + string target = fileSystem.Path.Combine("vault", archiveNumber); + + fileSystem.Directory.CreateDirectory("vault"); + fileSystem.Directory.Move(exhibition.Folder, target); + fileSystem.File.WriteAllText(fileSystem.Path.Combine(target, "archived-at.txt"), + timeSystem.DateTime.UtcNow.ToString("O")); + return archiveNumber; + } +} +``` + +In production, register `RealFileSystem`, `RealTimeSystem` and `RealRandomSystem` as shown in [Getting Started](./getting-started). + +## The tests + +The test class creates one mock of each system. The time system starts on the closing day of the exhibition, the random system returns a fixed `Guid`, and the file system contains the exhibition with two artworks: + +```csharp title="ExhibitionArchiverTests.cs" +public class ExhibitionArchiverTests +{ + private static readonly DateTime ClosingDay = new(2026, 4, 15, 18, 0, 0, DateTimeKind.Utc); + + private readonly MockFileSystem _fileSystem; + private readonly MockTimeSystem _timeSystem; + private readonly ExhibitionArchiver _sut; + private readonly Exhibition _exhibition = new("squares", ClosingDay); + + public ExhibitionArchiverTests() + { + _timeSystem = new MockTimeSystem(ClosingDay.AddHours(-1)); + // highlight-next-line + _fileSystem = new MockFileSystem(o => o.UseTimeSystem(_timeSystem)); + _fileSystem.Initialize() + .WithSubdirectory("squares").Initialized(d => d + .WithFile("red-square.png") + .WithFile("yellow-square.png")); + + MockRandomSystem randomSystem = new(RandomProvider.Generate( + guidGenerator: Guid.Parse("a1b2c3d4-0000-0000-0000-000000000000"))); + _sut = new ExhibitionArchiver(_fileSystem, _timeSystem, randomSystem); + } + + [Fact] + public async Task ArchiveIfClosed_WhileOpen_ShouldNotTouchTheFileSystem() + { + string? archiveNumber = _sut.ArchiveIfClosed(_exhibition); + + await Expect.That(archiveNumber).IsNull(); + await Expect.That(_fileSystem.Statistics.TotalCount).IsEqualTo(0) + .Because("seeding with Initialize() is not recorded in the statistics"); + } + + [Fact] + public async Task ArchiveIfClosed_AfterClosing_ShouldMoveTheArtworksIntoTheVault() + { + _timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromHours(2)); + + string? archiveNumber = _sut.ArchiveIfClosed(_exhibition); + + await Expect.That(archiveNumber).IsEqualTo("a1b2c3d4"); + await Expect.That(_fileSystem.Directory.Exists("squares")).IsFalse(); + await Expect.That(_fileSystem.Directory.GetFiles("vault/a1b2c3d4").Select(Path.GetFileName)) + .IsEqualTo(new[] { "archived-at.txt", "red-square.png", "yellow-square.png" }).InAnyOrder(); + await Expect.That(_fileSystem.File.ReadAllText("vault/a1b2c3d4/archived-at.txt")) + .IsEqualTo("2026-04-15T19:00:00.0000000Z"); + } + + [Fact] + public async Task ArchiveIfClosed_WhenTheVaultIsFull_ShouldKeepTheExhibition() + { + _timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromHours(2)); + // highlight-next-line + _fileSystem.Intercept.Creating(FileSystemTypes.Directory, + _ => throw new IOException("The vault is full.")); + + void Act() => _sut.ArchiveIfClosed(_exhibition); + + await Expect.That(Act).Throws().WithMessage("The vault is full."); + await Expect.That(_fileSystem.Directory.GetFiles("squares")).HasCount(2); + } +} +``` + +What each mock contributes: + +- **[Time system](./time-system):** the test starts an hour before closing and moves the clock with `AdvanceBy`, instead of waiting or depending on today's date. The `MockFileSystem` shares the same clock via `UseTimeSystem`, so file timestamps match the simulated time. +- **[Random system](./random-system/deterministic-randomness):** the fixed `Guid` makes the archive number predictable, so the test can assert the exact target folder. +- **[File system](./file-system):** [`Initialize()`](./file-system/initialization) seeds the exhibition, [`Statistics`](./file-system/statistics) proves that nothing happened while the exhibition was open, and [`Intercept`](./file-system/intercept-and-notify) simulates a full vault without filling a real disk. diff --git a/Docs/pages/docs/file-system/access-control.mdx b/Docs/pages/docs/file-system/access-control.mdx index 71e1eee84..8e678db76 100644 --- a/Docs/pages/docs/file-system/access-control.mdx +++ b/Docs/pages/docs/file-system/access-control.mdx @@ -15,11 +15,11 @@ The built-in `DefaultAccessControlStrategy` takes a callback `(fullPath, extensi MockFileSystem fileSystem = new(); // highlight-start fileSystem.WithAccessControlStrategy( - new DefaultAccessControlStrategy((path, _) => !path.EndsWith("secret.txt"))); + new DefaultAccessControlStrategy((path, _) => !path.EndsWith("provenance.txt"))); // highlight-end -fileSystem.File.WriteAllText("public.txt", "x"); // ok -fileSystem.File.WriteAllText("secret.txt", "x"); // throws UnauthorizedAccessException +fileSystem.File.WriteAllText("catalog.json", "[]"); // ok +fileSystem.File.WriteAllText("provenance.txt", ""); // throws UnauthorizedAccessException ``` A second overload of `DefaultAccessControlStrategy` additionally receives an `AccessRequest`, so you can simulate files and directories that can be read but not written, or written but not deleted: @@ -29,13 +29,13 @@ A second overload of `DefaultAccessControlStrategy` additionally receives an `Ac ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllText("readonly.txt", "x"); +fileSystem.File.WriteAllText("catalog.json", "[]"); fileSystem.WithAccessControlStrategy( new DefaultAccessControlStrategy((path, _, request) - => !(path.EndsWith("readonly.txt") && request.Access.HasFlag(FileAccess.Write)))); + => !(path.EndsWith("catalog.json") && request.Access.HasFlag(FileAccess.Write)))); -fileSystem.File.ReadAllText("readonly.txt"); // ok -fileSystem.File.WriteAllText("readonly.txt", "y"); // throws UnauthorizedAccessException +fileSystem.File.ReadAllText("catalog.json"); // ok +fileSystem.File.WriteAllText("catalog.json", "[]"); // throws UnauthorizedAccessException ``` For a custom strategy, derive from the abstract `AccessControlStrategy` base class instead of implementing `IAccessControlStrategy` directly, so that it receives the `AccessRequest`. Implementations of `IAccessControlStrategy` keep working, but do not receive the request. diff --git a/Docs/pages/docs/file-system/drives.mdx b/Docs/pages/docs/file-system/drives.mdx index 11362dd75..e81128f94 100644 --- a/Docs/pages/docs/file-system/drives.mdx +++ b/Docs/pages/docs/file-system/drives.mdx @@ -15,13 +15,13 @@ var fileSystem = new MockFileSystem(); fileSystem .WithDrive("D:", d => d.SetTotalSize(1024 * 1024)) // 1 MiB total .InitializeIn("D:") - .WithFile("foo.txt") - .WithSubdirectory("sub-dir").Initialized(s => s + .WithFile("inventory.txt") + .WithSubdirectory("vault").Initialized(s => s .WithAFile(".json").Which( - f => f.HasStringContent("{\"count\":1}"))); + f => f.HasStringContent("{\"artworks\":1}"))); ``` -This adds a `D:` drive limited to 1 MiB and seeds it with an empty `foo.txt` and a sub-directory containing one randomly named JSON file. +This adds a `D:` drive limited to 1 MiB and seeds it with an empty `inventory.txt` and a `vault` sub-directory containing one randomly named JSON file. ## Limiting the main drive @@ -32,7 +32,7 @@ var fileSystem = new MockFileSystem(); fileSystem.WithDrive(d => d.SetTotalSize(20)); // Throws IOException - not enough space on the disk -fileSystem.File.WriteAllText("foo", "some text longer than 20 bytes"); +fileSystem.File.WriteAllText("catalog.txt", "a catalogue longer than 20 bytes"); ``` When a drive runs out of space, every file operation that writes content throws `IOException`, exactly as on the real system. @@ -46,18 +46,18 @@ IDriveInfo drive = fileSystem.GetDefaultDrive(); await Expect.That(drive.AvailableFreeSpace).IsEqualTo(100); -fileSystem.File.WriteAllText("foo.txt", "This is a text with 29 bytes."); +fileSystem.File.WriteAllText("catalog.txt", "A catalogue entry of 29 bytes"); await Expect.That(drive.AvailableFreeSpace).IsEqualTo(71); -fileSystem.File.AppendAllText("foo.txt", "Another 17 bytes."); +fileSystem.File.AppendAllText("catalog.txt", "And 17 more bytes"); await Expect.That(drive.AvailableFreeSpace).IsEqualTo(54); -void WriteTooMuch() => fileSystem.File.WriteAllBytes("bar.bin", new byte[90]); +void WriteTooMuch() => fileSystem.File.WriteAllBytes("red-square.png", new byte[90]); await Expect.That(WriteTooMuch).Throws(); await Expect.That(drive.AvailableFreeSpace).IsEqualTo(54) .Because("the failed write did not consume space"); -fileSystem.File.Delete("foo.txt"); +fileSystem.File.Delete("catalog.txt"); await Expect.That(drive.AvailableFreeSpace).IsEqualTo(100); ``` @@ -70,7 +70,7 @@ MockFileSystem fileSystem = new(); fileSystem.WithUncDrive("build-server"); fileSystem.Directory.CreateDirectory("//build-server/share"); -fileSystem.File.WriteAllText("//build-server/share/foo.txt", "hi"); +fileSystem.File.WriteAllText("//build-server/share/catalog.json", "[]"); IDriveInfo drive = fileSystem.DriveInfo.New("//build-server"); await Expect.That(drive.IsReady).IsTrue(); diff --git a/Docs/pages/docs/file-system/file-system-watcher.mdx b/Docs/pages/docs/file-system/file-system-watcher.mdx index a7cc5401c..69b2f39c6 100644 --- a/Docs/pages/docs/file-system/file-system-watcher.mdx +++ b/Docs/pages/docs/file-system/file-system-watcher.mdx @@ -15,18 +15,18 @@ import TabItem from '@theme/TabItem'; ```csharp var fileSystem = new MockFileSystem(); -fileSystem.Initialize().WithSubdirectory("watched"); -fileSystem.File.WriteAllText("watched/a.txt", "hi"); +fileSystem.Initialize().WithSubdirectory("vault"); +fileSystem.File.WriteAllBytes("vault/red-square.png", []); -using var watcher = fileSystem.FileSystemWatcher.New("watched"); -var deleted = new ManualResetEventSlim(); +using var watcher = fileSystem.FileSystemWatcher.New("vault"); +var artworkRemoved = new ManualResetEventSlim(); -watcher.Deleted += (_, _) => deleted.Set(); +watcher.Deleted += (_, _) => artworkRemoved.Set(); watcher.EnableRaisingEvents = true; -fileSystem.File.Delete("watched/a.txt"); +fileSystem.File.Delete("vault/red-square.png"); -await Expect.That(deleted.Wait(TimeSpan.FromSeconds(1))).IsTrue(); +await Expect.That(artworkRemoved.Wait(TimeSpan.FromSeconds(1))).IsTrue(); ``` ## Reacting to triggered events from a test @@ -35,15 +35,15 @@ await Expect.That(deleted.Wait(TimeSpan.FromSeconds(1))).IsTrue(); ```csharp MockFileSystem fileSystem = new(); -fileSystem.Initialize().WithSubdirectory("watched"); +fileSystem.Initialize().WithSubdirectory("vault"); -using var watcher = fileSystem.FileSystemWatcher.New("watched"); +using var watcher = fileSystem.FileSystemWatcher.New("vault"); watcher.EnableRaisingEvents = true; // highlight-next-line using var triggered = fileSystem.Watcher.OnTriggered(); -fileSystem.File.WriteAllText("watched/a.txt", "hi"); +fileSystem.File.WriteAllBytes("vault/blue-circles.png", []); WatcherChangeDescription[] events = triggered.Wait(count: 1); ``` @@ -52,13 +52,13 @@ WatcherChangeDescription[] events = triggered.Wait(count: 1); When an entry is moved, the events depend on where it comes from and where it goes, relative to the watched path: ```text -outside/ ← Outside -watched/ ← the watched path -├── a.txt ← Inside -└── sub/ - ├── b.txt ← Nested - └── deeper/ - └── c.txt ← Deep +storage/ ← Outside +vault/ ← the watched path +├── red-square.png ← Inside +└── sketches/ + ├── blue-circles.png ← Nested + └── drafts/ + └── yellow-lines.png ← Deep ``` `_` stands for "nothing", i.e. the entry is created (`_ → Inside`) or deleted (`Inside → _`), and `-` means no event is raised. Pick the value of `IncludeSubdirectories`: diff --git a/Docs/pages/docs/file-system/file-version-info.mdx b/Docs/pages/docs/file-system/file-version-info.mdx index 49cddbea4..a51a3b799 100644 --- a/Docs/pages/docs/file-system/file-version-info.mdx +++ b/Docs/pages/docs/file-system/file-version-info.mdx @@ -13,16 +13,16 @@ To make a version-info-driven test deterministic, register a builder against a g ```csharp MockFileSystem fileSystem = new(); fileSystem.WithFileVersionInfo("*.dll", v => v - .SetCompanyName("Acme") - .SetProductName("Acme Widgets") + .SetCompanyName("Abstract Arts") + .SetProductName("Gallery Kiosk") .SetProductVersion("1.2.3.4") .SetFileVersion("1.2.3.0") .SetIsDebug(false)); -fileSystem.File.WriteAllText("Acme.Widgets.dll", ""); +fileSystem.File.WriteAllText("Gallery.Kiosk.dll", ""); -IFileVersionInfo info = fileSystem.FileVersionInfo.GetVersionInfo("Acme.Widgets.dll"); -await Expect.That(info.CompanyName).IsEqualTo("Acme"); +IFileVersionInfo info = fileSystem.FileVersionInfo.GetVersionInfo("Gallery.Kiosk.dll"); +await Expect.That(info.CompanyName).IsEqualTo("Abstract Arts"); await Expect.That(info.ProductVersion).IsEqualTo("1.2.3.4"); ``` diff --git a/Docs/pages/docs/file-system/index.mdx b/Docs/pages/docs/file-system/index.mdx index da3e374d5..cd461df3e 100644 --- a/Docs/pages/docs/file-system/index.mdx +++ b/Docs/pages/docs/file-system/index.mdx @@ -13,11 +13,11 @@ import DocCardList from '@theme/DocCardList'; | Static / `new` in `System.IO` | `IFileSystem` member | |--------------------------------------|-------------------------------------------------| -| `File.ReadAllText("a.txt")` | `fileSystem.File.ReadAllText("a.txt")` | -| `Directory.CreateDirectory("foo")` | `fileSystem.Directory.CreateDirectory("foo")` | -| `Path.Combine("a", "b")` | `fileSystem.Path.Combine("a", "b")` | -| `new FileInfo("a.txt")` | `fileSystem.FileInfo.New("a.txt")` | -| `new DirectoryInfo("foo")` | `fileSystem.DirectoryInfo.New("foo")` | +| `File.ReadAllText("catalog.json")` | `fileSystem.File.ReadAllText("catalog.json")` | +| `Directory.CreateDirectory("vault")` | `fileSystem.Directory.CreateDirectory("vault")` | +| `Path.Combine("vault", "red-square.png")` | `fileSystem.Path.Combine("vault", "red-square.png")` | +| `new FileInfo("catalog.json")` | `fileSystem.FileInfo.New("catalog.json")` | +| `new DirectoryInfo("vault")` | `fileSystem.DirectoryInfo.New("vault")` | | `new FileStream(...)` | `fileSystem.FileStream.New(...)` | | `new FileSystemWatcher(...)` | `fileSystem.FileSystemWatcher.New(...)` | | `DriveInfo.GetDrives()` | `fileSystem.DriveInfo.GetDrives()` | @@ -37,8 +37,8 @@ Static methods stay static on the sub-properties; constructors become factory me ```csharp IFileSystem fileSystem = new MockFileSystem(); -fileSystem.File.WriteAllText("hello.txt", "world"); -string content = fileSystem.File.ReadAllText("hello.txt"); // "world" +fileSystem.File.WriteAllText("red-square.txt", "Oil on canvas"); +string content = fileSystem.File.ReadAllText("red-square.txt"); // "Oil on canvas" ``` ## Configuring the mock @@ -47,7 +47,7 @@ string content = fileSystem.File.ReadAllText("hello.txt"); // "world" ```csharp MockFileSystem fileSystem = new(o => o - .UseCurrentDirectory("/work") // sets CurrentDirectory to "/work" + .UseCurrentDirectory("/gallery") // sets CurrentDirectory to "/gallery" .UseTimeSystem(timeSystem) // share an existing MockTimeSystem .UseRandomProvider(randomProvider) // share an existing IRandomProvider .SimulatingOperatingSystem(SimulationMode.Linux)); // simulate Linux semantics diff --git a/Docs/pages/docs/file-system/initialization.mdx b/Docs/pages/docs/file-system/initialization.mdx index c0ed4ed0b..99ddeff38 100644 --- a/Docs/pages/docs/file-system/initialization.mdx +++ b/Docs/pages/docs/file-system/initialization.mdx @@ -15,8 +15,8 @@ You can seed a `MockFileSystem` declaratively (with descriptions), fluently (wit Both styles below create: -- a directory `foo/` containing a sub-directory `bar/` and an empty file `bar.txt` -- a file `foo.txt` with content `"some file content"` +- a directory `artworks/` containing a sub-directory `sketches/` and an empty file `red-square.png` +- a file `about.txt` with content `"Welcome to the gallery"` @@ -24,10 +24,10 @@ Both styles below create: ```csharp var fileSystem = new MockFileSystem(); fileSystem.Initialize().With( - new DirectoryDescription("foo", - new DirectoryDescription("bar"), - new FileDescription("bar.txt")), - new FileDescription("foo.txt", "some file content")); + new DirectoryDescription("artworks", + new DirectoryDescription("sketches"), + new FileDescription("red-square.png")), + new FileDescription("about.txt", "Welcome to the gallery")); ``` `FileDescription` also accepts binary content and can mark a file read-only: @@ -35,8 +35,8 @@ fileSystem.Initialize().With( ```csharp var fileSystem = new MockFileSystem(); fileSystem.Initialize().With( - new FileDescription("data.bin", new byte[] { 1, 2, 3 }), - new FileDescription("config.json", "{ \"x\": 1 }") { IsReadOnly = true }); + new FileDescription("blue-circles.png", new byte[] { 0x89, 0x50, 0x4E, 0x47 }), + new FileDescription("catalog.json", "[]") { IsReadOnly = true }); ``` @@ -45,10 +45,10 @@ fileSystem.Initialize().With( ```csharp var fileSystem = new MockFileSystem(); fileSystem.Initialize() - .WithSubdirectory("foo").Initialized(d => d - .WithSubdirectory("bar") - .WithFile("bar.txt")) - .WithFile("foo.txt").Which(f => f.HasStringContent("some file content")); + .WithSubdirectory("artworks").Initialized(d => d + .WithSubdirectory("sketches") + .WithFile("red-square.png")) + .WithFile("about.txt").Which(f => f.HasStringContent("Welcome to the gallery")); ``` Use `HasStringContent(string)` or `HasBytesContent(byte[])` on the file manipulator to set content. @@ -59,18 +59,18 @@ Use `HasStringContent(string)` or `HasBytesContent(byte[])` on the file manipula ## Initializing inside a specific directory ```csharp -fileSystem.InitializeIn("current-directory") +fileSystem.InitializeIn("gallery") .WithASubdirectory() - .WithSubdirectory("foo").Initialized(s => s + .WithSubdirectory("artworks").Initialized(s => s .WithAFile()) - .WithFile("bar.txt"); + .WithFile("about.txt"); ``` -This sets `current-directory` as the working directory and seeds it with: +This sets `gallery` as the working directory and seeds it with: - a randomly named sub-directory -- a `foo/` sub-directory containing one randomly named file -- a `bar.txt` file +- an `artworks/` sub-directory containing one randomly named file +- an `about.txt` file `WithASubdirectory()` / `WithAFile()` use generated names when you don't care about the exact value - useful for tests that operate over whatever they find. `WithAFile(string extension)` lets you constrain the random name to a specific extension. @@ -80,7 +80,7 @@ This sets `current-directory` as the working directory and seeds it with: ```csharp fileSystem.Initialize() - .WithSubdirectories("a/b/c", "x/y", "logs"); + .WithSubdirectories("artworks/sketches/2026", "vault/restricted", "exports"); ``` Creates each path (and any missing parents) in one call. @@ -95,11 +95,11 @@ Creates each path (and any missing parents) in one call. ```csharp var init = fileSystem.Initialize() - .WithFile("foo.txt") - .WithSubdirectory("bar"); + .WithFile("catalog.json") + .WithSubdirectory("artworks"); -var foo = (IFileInfo)init[0]; -var bar = (IDirectoryInfo)init[1]; +var catalog = (IFileInfo)init[0]; +var artworks = (IDirectoryInfo)init[1]; ``` ## Seeding from a real directory @@ -107,7 +107,7 @@ var bar = (IDirectoryInfo)init[1]; ```csharp fileSystem.InitializeFromRealDirectory("test-data"); // or copy the source directory into a different target on the mock: -fileSystem.InitializeFromRealDirectory(@"C:\fixtures\sample-project", "project"); +fileSystem.InitializeFromRealDirectory(@"C:\fixtures\sample-collection", "collection"); ``` Recursively copies every file and sub-directory from the real path into the mock, preserving creation/last-write/last-access time and attributes. With large fixtures this can be slow - prefer it for small, hand-curated test data. @@ -117,13 +117,13 @@ Recursively copies every file and sub-directory from the real path into the mock ```csharp fileSystem.InitializeEmbeddedResourcesFromAssembly( directoryPath: "fixtures", - assembly: typeof(MyTests).Assembly, + assembly: typeof(GalleryTests).Assembly, relativePath: "TestData", searchPattern: "*.json", searchOption: SearchOption.AllDirectories); ``` -Materializes embedded resources as files inside the mock. Resource names are split on the last `.` to recover an extension (e.g. `MyTests.TestData.users.json` becomes `fixtures/users.json`). `relativePath` filters which resources are included; `searchPattern` and `searchOption` work like `Directory.EnumerateFiles`. +Materializes embedded resources as files inside the mock. Resource names are split on the last `.` to recover an extension (e.g. `GalleryTests.TestData.artworks.json` becomes `fixtures/artworks.json`). `relativePath` filters which resources are included; `searchPattern` and `searchOption` work like `Directory.EnumerateFiles`. ## Skipping the implicit temp directory @@ -135,7 +135,7 @@ fileSystem.Initialize(o => o.InitializeTempDirectory = false); ## Errors during initialization -The fluent builders throw `TestingException` (in `Testably.Abstractions.Testing.Initializer`) when used incorrectly - for example calling `WithFile("foo")` twice in the same parent scope. Catch this type if you need to surface a friendly assertion in a custom helper. +The fluent builders throw `TestingException` (in `Testably.Abstractions.Testing.Initializer`) when used incorrectly - for example calling `WithFile("catalog.json")` twice in the same parent scope. Catch this type if you need to surface a friendly assertion in a custom helper. ## Real file system: temporary directory with auto-cleanup @@ -144,7 +144,7 @@ For integration tests that hit the real disk, `SetCurrentDirectoryToEmptyTempora ```csharp IFileSystem fileSystem = new RealFileSystem(); using IDirectoryCleaner cleaner = - fileSystem.SetCurrentDirectoryToEmptyTemporaryDirectory(prefix: "MyTests-"); + fileSystem.SetCurrentDirectoryToEmptyTemporaryDirectory(prefix: "GalleryTests-"); // fileSystem.Directory.GetCurrentDirectory() is now an empty temp directory // On dispose: the directory is force-deleted (read-only flag and all) @@ -157,7 +157,7 @@ If you need a temporary directory but want to leave `Directory.GetCurrentDirecto ```csharp IFileSystem fileSystem = new RealFileSystem(); using IDirectoryCleaner cleaner = - fileSystem.CreateEmptyTemporaryDirectory(prefix: "MyTests-"); + fileSystem.CreateEmptyTemporaryDirectory(prefix: "GalleryTests-"); // fileSystem.Directory.GetCurrentDirectory() is unchanged // Use cleaner.BasePath to access the empty temp directory diff --git a/Docs/pages/docs/file-system/intercept-and-notify.mdx b/Docs/pages/docs/file-system/intercept-and-notify.mdx index ec14a14b2..36ae8ada1 100644 --- a/Docs/pages/docs/file-system/intercept-and-notify.mdx +++ b/Docs/pages/docs/file-system/intercept-and-notify.mdx @@ -26,10 +26,11 @@ The time system's [notifications](../time-system/notifications) use the same `IA MockFileSystem fileSystem = new(); fileSystem.Intercept.Creating(FileSystemTypes.File, - _ => throw new IOException("disk full")); + _ => throw new IOException("The vault is full."), + globPattern: "*.png"); -// Throws "disk full" -fileSystem.File.WriteAllText("a.txt", "x"); +fileSystem.File.WriteAllText("catalog.json", "[]"); // ok +fileSystem.File.WriteAllBytes("red-square.png", []); // throws "The vault is full." ``` Useful for simulating disk errors, permission failures or race conditions. @@ -38,16 +39,18 @@ Useful for simulating disk errors, permission failures or race conditions. ## Notify - await an event +The examples below use the `CatalogService` from [Getting Started](../getting-started), which writes `exports/catalog.json`. + ```csharp MockFileSystem fileSystem = new(); using var notify = fileSystem.Notify .OnCreated(FileSystemTypes.File); -fileSystem.File.WriteAllText("some-file.txt", "x"); +new CatalogService(fileSystem).Export("[]"); ChangeDescription[] events = notify.Wait(count: 1); -await Expect.That(events[0].Name).IsEqualTo("some-file.txt"); +await Expect.That(events[0].Path).EndsWith("catalog.json"); ``` :::tip @@ -62,13 +65,14 @@ Register the callback first, then do the work, then call `Wait` (or `WaitAsync` ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllText("early.txt", "x"); +new CatalogService(fileSystem).Export("[]"); using var notify = fileSystem.Notify.OnEventOrReplay( - predicate: c => c.ChangeType == WatcherChangeTypes.Created); + predicate: c => c.ChangeType == WatcherChangeTypes.Created + && c.FileSystemType == FileSystemTypes.File); ChangeDescription[] events = notify.Wait(count: 1); -await Expect.That(events[0].Name).IsEqualTo("early.txt"); +await Expect.That(events[0].Path).EndsWith("catalog.json"); ``` `fileSystem.Watcher.OnTriggeredOrReplay(...)` does the same for watcher events. The history is recorded by default; `new MockFileSystem(o => o.WithoutNotificationHistory())` turns it off, and both methods then throw `InvalidOperationException`. diff --git a/Docs/pages/docs/file-system/random-access.mdx b/Docs/pages/docs/file-system/random-access.mdx index 43bb9a41c..c72df3b0d 100644 --- a/Docs/pages/docs/file-system/random-access.mdx +++ b/Docs/pages/docs/file-system/random-access.mdx @@ -12,16 +12,16 @@ Every method is positionless: the offset is a parameter, not state carried on th ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllBytes("data.bin", [1, 2, 3, 4]); +fileSystem.File.WriteAllBytes("red-square.png", [1, 2, 3, 4]); -using SafeFileHandle handle = fileSystem.File.OpenHandle("data.bin", +using SafeFileHandle handle = fileSystem.File.OpenHandle("red-square.png", FileMode.Open, FileAccess.ReadWrite); byte[] buffer = new byte[2]; fileSystem.RandomAccess.Read(handle, buffer, fileOffset: 1); // buffer is [2, 3] fileSystem.RandomAccess.Write(handle, new byte[] { 9 }, fileOffset: 0); -await Expect.That(fileSystem.File.ReadAllBytes("data.bin")) +await Expect.That(fileSystem.File.ReadAllBytes("red-square.png")) .IsEqualTo(new byte[] { 9, 2, 3, 4 }); ``` @@ -54,12 +54,12 @@ Get the handle from [`IFile.OpenHandle`](./safe-file-handles), so the file syste ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllText("log", null); +fileSystem.File.WriteAllText("guard-rounds.log", null); -using (SafeFileHandle handle = fileSystem.File.OpenHandle("log", +using (SafeFileHandle handle = fileSystem.File.OpenHandle("guard-rounds.log", FileMode.Open, FileAccess.Write)) { - fileSystem.RandomAccess.Write(handle, "entry"u8.ToArray(), 0); + fileSystem.RandomAccess.Write(handle, "round"u8.ToArray(), 0); fileSystem.RandomAccess.FlushToDisk(handle); } diff --git a/Docs/pages/docs/file-system/safe-file-handles.mdx b/Docs/pages/docs/file-system/safe-file-handles.mdx index 2150bbff6..97365fce7 100644 --- a/Docs/pages/docs/file-system/safe-file-handles.mdx +++ b/Docs/pages/docs/file-system/safe-file-handles.mdx @@ -14,12 +14,12 @@ description: Use SafeFileHandle overloads against the MockFileSystem, including ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllText("file.txt", "some content"); +fileSystem.File.WriteAllText("red-square.txt", "Oil on board"); -using SafeFileHandle handle = fileSystem.File.OpenHandle("file.txt"); +using SafeFileHandle handle = fileSystem.File.OpenHandle("red-square.txt"); await Expect.That(fileSystem.File.GetLastAccessTime(handle)) - .IsEqualTo(fileSystem.File.GetLastAccessTime("file.txt")); + .IsEqualTo(fileSystem.File.GetLastAccessTime("red-square.txt")); await Expect.That(fileSystem.RandomAccess.GetLength(handle)).IsEqualTo(12); ``` @@ -106,8 +106,8 @@ mockFileSystem.WithSafeFileHandleStrategy(strategy); using IDirectoryCleaner _ = realFileSystem.SetCurrentDirectoryToEmptyTemporaryDirectory(); // Create the same file on both sides -mockFileSystem.File.WriteAllText("mock", "some content"); -realFileSystem.File.WriteAllText("real", "some content"); +mockFileSystem.File.WriteAllText("mock", "Oil on board"); +realFileSystem.File.WriteAllText("real", "Oil on board"); // Mutate the real file's last-access time DateTime expected = new DateTime(2026, 1, 1); diff --git a/Docs/pages/docs/file-system/statistics.mdx b/Docs/pages/docs/file-system/statistics.mdx index 99f7f5bde..234507c94 100644 --- a/Docs/pages/docs/file-system/statistics.mdx +++ b/Docs/pages/docs/file-system/statistics.mdx @@ -11,8 +11,8 @@ description: Assert which file system methods and properties the code under test ```csharp MockFileSystem fileSystem = new(); -fileSystem.File.WriteAllText("a.txt", "hi"); -fileSystem.File.ReadAllText("a.txt"); +fileSystem.File.WriteAllText("catalog.json", "[]"); +fileSystem.File.ReadAllText("catalog.json"); IFileSystemStatistics stats = fileSystem.Statistics; await Expect.That(stats.TotalCount).IsEqualTo(2); @@ -25,12 +25,12 @@ await Expect.That(stats.File.Methods).Contains(m => m.Name == nameof(IFile.Write Each of them has `Methods` and `Properties` collections. An entry carries the call's name, its parameters and a global `Counter` that tells the order of the calls. -The properties for types created by a factory (`DirectoryInfo`, `DriveInfo`, `FileInfo`, `FileStream`, `FileSystemWatcher`, `FileVersionInfo`) also have an indexer keyed by path - `stats.FileInfo["a.txt"]` returns just the calls made on the `IFileInfo` for that path: +The properties for types created by a factory (`DirectoryInfo`, `DriveInfo`, `FileInfo`, `FileStream`, `FileSystemWatcher`, `FileVersionInfo`) also have an indexer keyed by path - `stats.FileInfo["catalog.json"]` returns just the calls made on the `IFileInfo` for that path: ```csharp -_ = fileSystem.FileInfo.New("a.txt").Exists; +_ = fileSystem.FileInfo.New("catalog.json").Exists; -await Expect.That(stats.FileInfo["a.txt"].Properties) +await Expect.That(stats.FileInfo["catalog.json"].Properties) .Contains(p => p.Name == nameof(IFileInfo.Exists)); ``` diff --git a/Docs/pages/docs/file-system/unix-file-mode.mdx b/Docs/pages/docs/file-system/unix-file-mode.mdx index 3cc8ae090..c7563c1fa 100644 --- a/Docs/pages/docs/file-system/unix-file-mode.mdx +++ b/Docs/pages/docs/file-system/unix-file-mode.mdx @@ -89,27 +89,27 @@ MockFileSystem fileSystem = new MockFileSystem(o => o .SimulatingOperatingSystem(SimulationMode.Linux)) .WithUnixFileModeStrategy(strategy); -// "alice" creates a directory readable only by its group "editors" -strategy.SimulateUser("alice").SimulateGroup("editors"); -fileSystem.Directory.CreateDirectory("foo", UnixFileMode.GroupRead); +// "alice" creates a directory readable only by the group "curators" +strategy.SimulateUser("alice").SimulateGroup("curators"); +fileSystem.Directory.CreateDirectory("restoration", UnixFileMode.GroupRead); -// "bob" (also "editors") can read it -strategy.SimulateUser("bob").SimulateGroup("editors"); -fileSystem.Directory.GetFiles("foo"); // no exception +// "bob" (also a curator) can read it +strategy.SimulateUser("bob").SimulateGroup("curators"); +fileSystem.Directory.GetFiles("restoration"); // no exception // switch to a different group → read denied -strategy.SimulateGroup("guests"); -fileSystem.Directory.GetFiles("foo"); // throws UnauthorizedAccessException +strategy.SimulateGroup("visitors"); +fileSystem.Directory.GetFiles("restoration"); // throws UnauthorizedAccessException ``` ### Asserting denial ```csharp strategy.SimulateUser("alice"); -fileSystem.Directory.CreateDirectory("private", UnixFileMode.UserWrite); +fileSystem.Directory.CreateDirectory("vault", UnixFileMode.UserWrite); strategy.SimulateUser("bob"); -Action act = () => fileSystem.Directory.CreateDirectory("private/sub"); +Action act = () => fileSystem.Directory.CreateDirectory("vault/drafts"); await Expect.That(act).Throws(); ``` diff --git a/Docs/pages/docs/getting-started.mdx b/Docs/pages/docs/getting-started.mdx index 2d6d9c3f4..4ff87b203 100644 --- a/Docs/pages/docs/getting-started.mdx +++ b/Docs/pages/docs/getting-started.mdx @@ -45,42 +45,43 @@ builder.Services ## 3. Use the interfaces in your services -```csharp title="ReportService.cs" -public class ReportService(IFileSystem fileSystem) +```csharp title="CatalogService.cs" +public class CatalogService(IFileSystem fileSystem) { - public void Save(string content) + public void Export(string json) { - fileSystem.Directory.CreateDirectory("reports"); - fileSystem.File.WriteAllText("reports/latest.xml", content); + fileSystem.Directory.CreateDirectory("exports"); + fileSystem.File.WriteAllText("exports/catalog.json", json); } } ``` ## 4. Replace the real implementations in tests -```csharp title="ReportServiceTests.cs" +```csharp title="CatalogServiceTests.cs" [Fact] -public async Task Save_WritesReportToReportsFolder() +public async Task Export_WritesCatalogToExportsFolder() { // highlight-next-line var fileSystem = new MockFileSystem(); - var sut = new ReportService(fileSystem); + var sut = new CatalogService(fileSystem); - sut.Save(""); + sut.Export("""{ "title": "Red Square" }"""); - await Expect.That(fileSystem.File.ReadAllText("reports/latest.xml")) - .IsEqualTo(""); + await Expect.That(fileSystem.File.ReadAllText("exports/catalog.json")) + .IsEqualTo("""{ "title": "Red Square" }"""); } ``` That's it - your code now runs against an in-memory file system in tests, and against the real one in production. -:::info[Test framework] -The examples in this documentation use [xUnit](https://xunit.net/) and [aweXpect](https://docs.testably.org/aweXpect/) assertions. The mocks do not depend on either, so any test framework and assertion library works. +:::info[About the examples] +The examples in this documentation are set in a gallery of abstract art: a catalogue of artworks, exhibitions that open and close, and a night guard on patrol. They use [xUnit](https://xunit.net/) and [aweXpect](https://docs.testably.org/aweXpect/) assertions, but the mocks do not depend on either, so any test framework and assertion library works. ::: ## Next steps +- [A complete example](./complete-example) - one gallery service tested with the file system, time and random system together. - [File system](./file-system) - `IFileSystem`, `MockFileSystem`, drives, watcher, statistics, strategies. - [Time system](./time-system) - `ITimeSystem`, time providers, timers, auto-advance, notifications. - [Random system](./random-system) - `IRandomSystem` and deterministic generators. diff --git a/Docs/pages/docs/index.mdx b/Docs/pages/docs/index.mdx index 0a8956bdd..4a46f4fdc 100644 --- a/Docs/pages/docs/index.mdx +++ b/Docs/pages/docs/index.mdx @@ -20,76 +20,72 @@ Depend on `IFileSystem`, `ITimeSystem` and `IRandomSystem` in production. Swap i -```csharp title="ReportService.cs" -public class ReportService(IFileSystem fileSystem) +```csharp title="CatalogService.cs" +public class CatalogService(IFileSystem fileSystem) { - public void Save(string content) + public void Export(string json) { - fileSystem.Directory.CreateDirectory("reports"); - fileSystem.File.WriteAllText("reports/latest.xml", content); + fileSystem.Directory.CreateDirectory("exports"); + fileSystem.File.WriteAllText("exports/catalog.json", json); } } ``` -```csharp title="ReportServiceTests.cs" +```csharp title="CatalogServiceTests.cs" [Fact] -public async Task Save_WritesReportToReportsFolder() +public async Task Export_WritesCatalogToExportsFolder() { var fileSystem = new MockFileSystem(); - var sut = new ReportService(fileSystem); + var sut = new CatalogService(fileSystem); - sut.Save(""); + sut.Export("""{ "title": "Red Square" }"""); - await Expect.That(fileSystem.File.ReadAllText("reports/latest.xml")) - .IsEqualTo(""); + await Expect.That(fileSystem.File.ReadAllText("exports/catalog.json")) + .IsEqualTo("""{ "title": "Red Square" }"""); } ``` -```csharp title="CacheEntry.cs" -public class CacheEntry(ITimeSystem timeSystem, TimeSpan ttl) +```csharp title="Exhibition.cs" +public class Exhibition(ITimeSystem timeSystem, DateTime closesAt) { - private readonly DateTime _expiresAt = timeSystem.DateTime.UtcNow + ttl; - - public bool IsExpired => timeSystem.DateTime.UtcNow >= _expiresAt; + public bool IsOpen => timeSystem.DateTime.UtcNow < closesAt; } ``` -```csharp title="CacheEntryTests.cs" +```csharp title="ExhibitionTests.cs" [Fact] -public async Task IsExpired_ReturnsTrue_AfterTtlPasses() +public async Task IsOpen_ReturnsFalse_AfterClosingDate() { - MockTimeSystem timeSystem = new(new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); - var entry = new CacheEntry(timeSystem, TimeSpan.FromMinutes(5)); + MockTimeSystem timeSystem = new(new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)); + var sut = new Exhibition(timeSystem, closesAt: new DateTime(2026, 4, 15, 0, 0, 0, DateTimeKind.Utc)); - await timeSystem.Task.Delay(TimeSpan.FromMinutes(6)); + timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromDays(60)); - await Expect.That(entry.IsExpired).IsTrue(); + await Expect.That(sut.IsOpen).IsFalse(); } ``` -```csharp title="CorrelationIdProvider.cs" -public class CorrelationIdProvider(IRandomSystem randomSystem) +```csharp title="ArtworkOfTheDay.cs" +public class ArtworkOfTheDay(IRandomSystem randomSystem, string[] artworks) { - public string Next() => randomSystem.Guid.NewGuid().ToString(); + public string Pick() => artworks[randomSystem.Random.Shared.Next(artworks.Length)]; } ``` -```csharp title="CorrelationIdProviderTests.cs" +```csharp title="ArtworkOfTheDayTests.cs" [Fact] -public async Task Next_ReturnsConfiguredGuid_ForDeterministicTests() +public async Task Pick_ReturnsTheArtworkAtTheRandomIndex() { - MockRandomSystem randomSystem = new(RandomProvider.Generate( - guidGenerator: () => Guid.Parse("11111111-1111-1111-1111-111111111111"))); - var sut = new CorrelationIdProvider(randomSystem); + MockRandomSystem randomSystem = new(RandomProvider.Generate(intGenerator: 1)); + var sut = new ArtworkOfTheDay(randomSystem, ["Red Square", "Blue Circles", "Yellow Lines"]); - await Expect.That(sut.Next()) - .IsEqualTo("11111111-1111-1111-1111-111111111111"); + await Expect.That(sut.Pick()).IsEqualTo("Blue Circles"); } ``` @@ -109,5 +105,6 @@ See [Migration from TestableIO](./migration-from-testableio) if you are already ## Where to go next - **[Getting Started](./getting-started)** - install the packages and wire them up. +- **[A complete example](./complete-example)** - one gallery service tested with all three abstractions. - **[File system](./file-system)**, **[Time system](./time-system)**, **[Random system](./random-system)** - explore each abstraction. - **[Companion libraries](./companion-libraries)** - ZIP, ACL and memory-mapped file helpers. diff --git a/Docs/pages/docs/migration-from-testableio/index.mdx b/Docs/pages/docs/migration-from-testableio/index.mdx index 9e213ad6e..53adafab0 100644 --- a/Docs/pages/docs/migration-from-testableio/index.mdx +++ b/Docs/pages/docs/migration-from-testableio/index.mdx @@ -40,20 +40,20 @@ If you'd rather not introduce a build-time analyzer, swap the package and rewrit ```csharp // Before (TestableIO) var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory("some-directory"); - fileSystem.AddFile("some-file.txt", new MockFileData("content")); + fileSystem.AddDirectory("artworks"); + fileSystem.AddFile("artworks/red-square.txt", new MockFileData("Oil on canvas")); // After (Testably) - option A: imperative var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("some-directory"); - fileSystem.File.WriteAllText("some-file.txt", "content"); + fileSystem.Directory.CreateDirectory("artworks"); + fileSystem.File.WriteAllText("artworks/red-square.txt", "Oil on canvas"); // After (Testably) - option B: fluent initialization var fileSystem = new MockFileSystem(); fileSystem.Initialize() - .WithSubdirectory("some-directory") - .WithFile("some-file.txt").Which(f => f - .HasStringContent("content")); + .WithSubdirectory("artworks").Initialized(d => d + .WithFile("red-square.txt").Which(f => f + .HasStringContent("Oil on canvas"))); ``` Production code keeps using `IFileSystem` exactly as before - no changes there. diff --git a/Docs/pages/docs/random-system/deterministic-randomness.mdx b/Docs/pages/docs/random-system/deterministic-randomness.mdx index be7fbf176..f59e73920 100644 --- a/Docs/pages/docs/random-system/deterministic-randomness.mdx +++ b/Docs/pages/docs/random-system/deterministic-randomness.mdx @@ -41,7 +41,7 @@ Generator g2 = new[] { 1, 2, 3 }; Generator g3 = Generator.FromCallback(() => DateTime.Now.Millisecond); // From any IEnumerable (loops once exhausted) -Generator g4 = Generator.FromEnumerable(MyKnownGuids); +Generator g4 = Generator.FromEnumerable(catalogNumbers); ``` If you have a `Generator` directly, `g.GetNext()` returns the next value - useful when you build the generator yourself outside a `MockRandomSystem` (e.g. for parameterised test-data generation). diff --git a/Docs/pages/docs/time-system/configuring-time.mdx b/Docs/pages/docs/time-system/configuring-time.mdx index 7c7b7916a..fbc2fa311 100644 --- a/Docs/pages/docs/time-system/configuring-time.mdx +++ b/Docs/pages/docs/time-system/configuring-time.mdx @@ -72,7 +72,7 @@ Implement `ITimeProvider` directly when you need something more interesting than Wrap your provider in a factory and pass it in: ```csharp -ITimeProviderFactory factory = new MyTimeProviderFactory(...); +ITimeProviderFactory factory = new GalleryClockFactory(...); MockTimeSystem timeSystem = new(factory); ``` @@ -86,7 +86,7 @@ Pass an existing `MockTimeSystem` into a `MockFileSystem` so file-system timesta MockTimeSystem timeSystem = new(new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); MockFileSystem fileSystem = new(o => o.UseTimeSystem(timeSystem)); -fileSystem.File.WriteAllText("a.txt", "hi"); -DateTime created = fileSystem.File.GetCreationTimeUtc("a.txt"); +fileSystem.File.WriteAllText("catalog.json", "[]"); +DateTime created = fileSystem.File.GetCreationTimeUtc("catalog.json"); // created is anchored to 2026-01-01 ``` diff --git a/Docs/pages/docs/time-system/notifications.mdx b/Docs/pages/docs/time-system/notifications.mdx index f55c23e70..177a336fc 100644 --- a/Docs/pages/docs/time-system/notifications.mdx +++ b/Docs/pages/docs/time-system/notifications.mdx @@ -13,7 +13,7 @@ MockTimeSystem timeSystem = new(); using var sleeps = timeSystem.On.ThreadSleep(); -DoWorkThatSleeps(timeSystem); +new Gallery(timeSystem).CloseForTheNight(); // waits 5 seconds before switching off the lights TimeSpan[] requestedSleeps = sleeps.Wait(count: 1); await Expect.That(requestedSleeps[0]).IsEqualTo(TimeSpan.FromSeconds(5)); diff --git a/Docs/pages/docs/time-system/periodic-timer.mdx b/Docs/pages/docs/time-system/periodic-timer.mdx index c0b99a895..88f28ad75 100644 --- a/Docs/pages/docs/time-system/periodic-timer.mdx +++ b/Docs/pages/docs/time-system/periodic-timer.mdx @@ -12,17 +12,17 @@ description: Test loops built on PeriodicTimer without waiting for real time to `ITimeSystem.PeriodicTimer` is only available on .NET 8 and later. ::: -Typical use case: a hosted/background service that does work on a fixed cadence - every 30 seconds, every 5 minutes - and needs to be testable without actually sleeping for that long. +Typical use case: a hosted/background service that does work on a fixed cadence and needs to be testable without actually waiting that long - like a night guard who walks a round through the gallery every 30 minutes: -```csharp title="HeartbeatWorker.cs" -public class HeartbeatWorker(ITimeSystem timeSystem, IFileSystem fileSystem) +```csharp title="NightGuard.cs" +public class NightGuard(ITimeSystem timeSystem, IFileSystem fileSystem) { - public async Task RunAsync(CancellationToken cancellationToken) + public async Task PatrolAsync(CancellationToken cancellationToken) { - using IPeriodicTimer timer = timeSystem.PeriodicTimer.New(TimeSpan.FromSeconds(30)); + using IPeriodicTimer timer = timeSystem.PeriodicTimer.New(TimeSpan.FromMinutes(30)); while (await timer.WaitForNextTickAsync(cancellationToken)) { - fileSystem.File.AppendAllText("heartbeat.log", $"{timeSystem.DateTime.UtcNow:o}\n"); + fileSystem.File.AppendAllText("guard-rounds.log", $"{timeSystem.DateTime.UtcNow:o}\n"); } } } @@ -32,29 +32,29 @@ public class HeartbeatWorker(ITimeSystem timeSystem, IFileSystem fileSystem) To assert exactly how often the loop ran, turn auto-advance off and advance the clock by hand. `WaitForNextTickAsync` then stays pending until the simulated time reaches the next tick. -`On.PeriodicTimer.WaitingForNextTick()` fires every time the worker calls `WaitForNextTickAsync`, so waiting for it tells the test that the worker finished the previous iteration and is idle again: +`On.PeriodicTimer.WaitingForNextTick()` fires every time the guard calls `WaitForNextTickAsync`, so waiting for it tells the test that the guard finished the previous round and is waiting for the next one: ```csharp MockTimeSystem timeSystem = new(o => o.DisableAutoAdvance()); MockFileSystem fileSystem = new(o => o.UseTimeSystem(timeSystem)); -HeartbeatWorker worker = new(timeSystem, fileSystem); +NightGuard guard = new(timeSystem, fileSystem); using CancellationTokenSource cts = new(); using IAwaitableCallback waiting = timeSystem.On.PeriodicTimer.WaitingForNextTick(); -Task run = worker.RunAsync(cts.Token); +Task patrol = guard.PatrolAsync(cts.Token); -// The worker is waiting for its first tick - nothing was written yet +// The guard is waiting for the first round - nothing was logged yet waiting.Wait(); -await Expect.That(fileSystem.File.Exists("heartbeat.log")).IsFalse(); +await Expect.That(fileSystem.File.Exists("guard-rounds.log")).IsFalse(); // highlight-next-line -timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromSeconds(30)); +timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromMinutes(30)); waiting.Wait(); -await Expect.That(fileSystem.File.ReadAllLines("heartbeat.log")).HasCount(1); +await Expect.That(fileSystem.File.ReadAllLines("guard-rounds.log")).HasCount(1); cts.Cancel(); -await Expect.That(async () => await run).Throws(); +await Expect.That(async () => await patrol).Throws(); ``` Like the real `PeriodicTimer`, advancing the clock by several periods at once results in a single tick, not one tick per elapsed period. @@ -68,17 +68,17 @@ With auto-advance on (the default), every `WaitForNextTickAsync` returns immedia ```csharp MockTimeSystem timeSystem = new(); MockFileSystem fileSystem = new(o => o.UseTimeSystem(timeSystem)); -HeartbeatWorker worker = new(timeSystem, fileSystem); +NightGuard guard = new(timeSystem, fileSystem); using CancellationTokenSource cts = new(); using IAwaitableCallback waiting = timeSystem.On.PeriodicTimer.WaitingForNextTick(); -Task run = worker.RunAsync(cts.Token); -waiting.Wait(count: 5); // the worker finished at least four iterations +Task patrol = guard.PatrolAsync(cts.Token); +waiting.Wait(count: 5); // the guard finished at least four rounds cts.Cancel(); -await Expect.That(async () => await run).Throws(); +await Expect.That(async () => await patrol).Throws(); -await Expect.That(fileSystem.File.ReadAllLines("heartbeat.log").Length) +await Expect.That(fileSystem.File.ReadAllLines("guard-rounds.log").Length) .IsGreaterThanOrEqualTo(4); ```