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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Docs/pages/docs/companion-libraries/access-control.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 7 additions & 7 deletions Docs/pages/docs/companion-libraries/compression.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
```

<details>
Expand All @@ -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)
{
Expand All @@ -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);
```

Expand All @@ -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`).
Expand All @@ -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);

Expand Down
6 changes: 3 additions & 3 deletions Docs/pages/docs/companion-libraries/memory-mapped-files.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -41,15 +41,15 @@ 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);
```

The `FileStream`-based overload is exposed with a `FileSystemStream` instead of a `FileStream`, so it works against both the real and the mocked file system:

```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);
Expand Down
116 changes: 116 additions & 0 deletions Docs/pages/docs/complete-example.mdx
Original file line number Diff line number Diff line change
@@ -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<IOException>().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.
14 changes: 7 additions & 7 deletions Docs/pages/docs/file-system/access-control.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
Expand Down
20 changes: 10 additions & 10 deletions Docs/pages/docs/file-system/drives.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
Expand All @@ -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<IOException>();
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);
```

Expand All @@ -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();
Expand Down
34 changes: 17 additions & 17 deletions Docs/pages/docs/file-system/file-system-watcher.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
```

Expand All @@ -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`:
Expand Down
10 changes: 5 additions & 5 deletions Docs/pages/docs/file-system/file-version-info.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
```

Expand Down
Loading
Loading