From 16d4129ef097eecac9e2df81b479513d03363ddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 18 Oct 2026 19:06:30 +0200 Subject: [PATCH] fix: route the remaining simulated system errors through the exception factory Some simulated system errors were built inline and their messages differed from the real system, which tests that only pinned the exception type, parameter name or HResult did not notice. They now go through `ExceptionFactory` and the tests pin the messages against the real system. - Invalid timer `dueTime` and `period` use the real message for the target framework (`ThrowIfLessThan` style on .NET 8+, with the trailing period before). - `Timer.Change` on a disposed timer (before .NET 8) no longer adds an object name, an invalid `SearchOption` reports "Enum value was out of legal range." and the `EnumerationOptions` polyfill reports "Non-negative number required.". - A search pattern with more `../` than parent directories throws "Access to the path '...' is denied." for the root instead of an invented message. - The closed file stream and the read-only directory delete errors keep their behaviour and only move into the factory. --- .../FileSystem/DirectoryInfoMock.cs | 4 +--- .../FileSystem/DirectoryMock.cs | 4 +--- .../FileSystem/FileStreamMock.cs | 2 +- .../Helpers/EnumerationOptionsHelper.cs | 2 +- .../Helpers/ExceptionFactory.cs | 20 +++++++++++++++--- .../Polyfills/EnumerationOptions.cs | 3 ++- .../Storage/StorageExtensions.cs | 3 +-- .../TimeSystem/TimerMock.cs | 14 ++++++++----- .../Helpers/EnumerationOptionsHelperTests.cs | 3 ++- .../TimeSystem/TimerMockTests.cs | 5 +---- .../FileSystem/Directory/SearchFilterTests.cs | 18 +++++++++++++++- .../TimeSystem/TimerFactoryTests.cs | 18 ++++++++++++++-- .../TimeSystem/TimerTests.cs | 21 ++++++++++++++++--- 13 files changed, 87 insertions(+), 30 deletions(-) diff --git a/Source/Testably.Abstractions.Testing/FileSystem/DirectoryInfoMock.cs b/Source/Testably.Abstractions.Testing/FileSystem/DirectoryInfoMock.cs index c93adc339..1908f03b2 100644 --- a/Source/Testably.Abstractions.Testing/FileSystem/DirectoryInfoMock.cs +++ b/Source/Testably.Abstractions.Testing/FileSystem/DirectoryInfoMock.cs @@ -497,9 +497,7 @@ private void DeleteInternal(bool recursive) } catch (UnauthorizedAccessException ex) { -#pragma warning disable MA0054 // Embed the caught exception as innerException - throw new IOException(ex.Message); -#pragma warning restore MA0054 + throw ExceptionFactory.DirectoryDeleteAccessDenied(ex.Message); } } } diff --git a/Source/Testably.Abstractions.Testing/FileSystem/DirectoryMock.cs b/Source/Testably.Abstractions.Testing/FileSystem/DirectoryMock.cs index 8d2fec5d2..c81cea4f7 100644 --- a/Source/Testably.Abstractions.Testing/FileSystem/DirectoryMock.cs +++ b/Source/Testably.Abstractions.Testing/FileSystem/DirectoryMock.cs @@ -117,9 +117,7 @@ public void Delete(string path) } catch (UnauthorizedAccessException ex) { -#pragma warning disable MA0054 // Embed the caught exception as innerException - throw new IOException(ex.Message); -#pragma warning restore MA0054 + throw ExceptionFactory.DirectoryDeleteAccessDenied(ex.Message); } } diff --git a/Source/Testably.Abstractions.Testing/FileSystem/FileStreamMock.cs b/Source/Testably.Abstractions.Testing/FileSystem/FileStreamMock.cs index c26d1699a..342aece37 100644 --- a/Source/Testably.Abstractions.Testing/FileSystem/FileStreamMock.cs +++ b/Source/Testably.Abstractions.Testing/FileSystem/FileStreamMock.cs @@ -907,7 +907,7 @@ private void ThrowIfDisposed() // A stream on a handle cannot be used once the handle is closed, even before the stream is disposed. if (_isDisposed || _ownedHandle is { IsClosed: true }) { - throw new ObjectDisposedException("", "Cannot access a closed file."); + throw ExceptionFactory.FileClosed(); } } } diff --git a/Source/Testably.Abstractions.Testing/Helpers/EnumerationOptionsHelper.cs b/Source/Testably.Abstractions.Testing/Helpers/EnumerationOptionsHelper.cs index b1169c30f..85a7b47e4 100644 --- a/Source/Testably.Abstractions.Testing/Helpers/EnumerationOptionsHelper.cs +++ b/Source/Testably.Abstractions.Testing/Helpers/EnumerationOptionsHelper.cs @@ -72,7 +72,7 @@ internal static EnumerationOptions FromSearchOption(SearchOption searchOption) if (searchOption != SearchOption.TopDirectoryOnly && searchOption != SearchOption.AllDirectories) { - throw new ArgumentOutOfRangeException(nameof(searchOption)); + throw ExceptionFactory.EnumValueOutOfRange(nameof(searchOption)); } return searchOption == SearchOption.AllDirectories diff --git a/Source/Testably.Abstractions.Testing/Helpers/ExceptionFactory.cs b/Source/Testably.Abstractions.Testing/Helpers/ExceptionFactory.cs index 0d3bf508a..5fedf7e4f 100644 --- a/Source/Testably.Abstractions.Testing/Helpers/ExceptionFactory.cs +++ b/Source/Testably.Abstractions.Testing/Helpers/ExceptionFactory.cs @@ -42,6 +42,9 @@ internal static IOException CannotCreateFileAsAlreadyExists(Execute execute, str internal static IOException CannotCreateFileWhenAlreadyExists(int hResult) => new("Cannot create a file when that file already exists.", hResult); + internal static IOException DirectoryDeleteAccessDenied(string message) + => new(message); + internal static ArgumentException DirectoryNameDoesNotExist( string path, string paramName = "path") => new($"The directory name '{path}' does not exist.", paramName) @@ -75,6 +78,9 @@ internal static ArgumentOutOfRangeException EnumValueOutOfRange(string paramName internal static IOException FileAlreadyExists(string path, int hResult) => new($"The file '{path}' already exists.", hResult); + internal static ObjectDisposedException FileClosed() + => new(null, "Cannot access a closed file."); + internal static IOException FileNameCannotBeResolved( string path, int hResult = -2147022975) => new($"The name of the file cannot be resolved by the system. : '{path}'", @@ -187,6 +193,9 @@ internal static ArgumentException NullCharacterInPath(string paramName) => new("Illegal characters in path.", paramName); #endif + internal static ObjectDisposedException ObjectDisposed() + => new(null, "Cannot access a disposed object."); + internal static PlatformNotSupportedException OperationNotSupportedOnThisPlatform() => new("Operation is not supported on this platform.") { @@ -329,14 +338,19 @@ internal static TimeoutException TimeoutExpired(int timeoutMilliseconds) internal static TimeoutException TimeoutExpired(TimeSpan timeout) => new($"The timeout of {timeout} expired in the awaitable callback."); - internal static ArgumentOutOfRangeException TimerArgumentOutOfRange(string propertyName) - => new(propertyName, - "Number must be either non-negative and less than or equal to Int32.MaxValue or -1") + internal static ArgumentOutOfRangeException TimerArgumentOutOfRange( + string paramName, long value) +#if NET8_0_OR_GREATER + => new(paramName, value, $"{paramName} ('{value}') must be greater than or equal to '-1'."); +#else + => new(paramName, + "Number must be either non-negative and less than or equal to Int32.MaxValue or -1.") { #if FEATURE_EXCEPTION_HRESULT HResult = -2146233086, #endif }; +#endif internal static TimeoutException TimerWaitTimeoutException(int executionCount, int timeout) => new($"The execution count {executionCount} was not reached in {timeout}ms."); diff --git a/Source/Testably.Abstractions.Testing/Polyfills/EnumerationOptions.cs b/Source/Testably.Abstractions.Testing/Polyfills/EnumerationOptions.cs index 0a93a5d14..fdcbc3e99 100644 --- a/Source/Testably.Abstractions.Testing/Polyfills/EnumerationOptions.cs +++ b/Source/Testably.Abstractions.Testing/Polyfills/EnumerationOptions.cs @@ -1,5 +1,6 @@ #if !FEATURE_FILESYSTEM_ENUMERATION_OPTIONS using System.Diagnostics.CodeAnalysis; +using Testably.Abstractions.Testing.Helpers; // ReSharper disable once CheckNamespace namespace System.IO; @@ -92,7 +93,7 @@ public int MaxRecursionDepth { if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(value)); + throw ExceptionFactory.NonNegativeNumberRequired(nameof(value)); } field = value; diff --git a/Source/Testably.Abstractions.Testing/Storage/StorageExtensions.cs b/Source/Testably.Abstractions.Testing/Storage/StorageExtensions.cs index e4931d0be..0b392afea 100644 --- a/Source/Testably.Abstractions.Testing/Storage/StorageExtensions.cs +++ b/Source/Testably.Abstractions.Testing/Storage/StorageExtensions.cs @@ -43,8 +43,7 @@ public static AdjustedLocation AdjustLocationFromSearchPattern( parentDirectories.Push(fileSystem.Execute.Path.GetFileName(location.FullPath)); location = location.GetParent() ?? - throw new UnauthorizedAccessException( - $"The searchPattern '{searchPattern}' has too many '../' for path '{path}'"); + throw ExceptionFactory.AccessToPathDenied(location.FullPath); #pragma warning disable CA1846 givenPathPrefix.Append(searchPattern, 0, 3); #pragma warning restore CA1846 diff --git a/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs b/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs index 5d28cd5ca..43550a3c4 100644 --- a/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs +++ b/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs @@ -39,12 +39,14 @@ internal TimerMock(MockTimeSystem timeSystem, { if (dueTime.TotalMilliseconds < -1) { - throw ExceptionFactory.TimerArgumentOutOfRange(nameof(dueTime)); + throw ExceptionFactory.TimerArgumentOutOfRange(nameof(dueTime), + (long)dueTime.TotalMilliseconds); } if (period.TotalMilliseconds < -1) { - throw new ArgumentOutOfRangeException(nameof(period)); + throw ExceptionFactory.TimerArgumentOutOfRange(nameof(period), + (long)period.TotalMilliseconds); } _mockTimeSystem = timeSystem; @@ -86,18 +88,20 @@ public bool Change(TimeSpan dueTime, TimeSpan period) #if NET8_0_OR_GREATER return false; #else - throw new ObjectDisposedException(nameof(Change), "Cannot access a disposed object."); + throw ExceptionFactory.ObjectDisposed(); #endif } if (dueTime.TotalMilliseconds < -1) { - throw ExceptionFactory.TimerArgumentOutOfRange(nameof(dueTime)); + throw ExceptionFactory.TimerArgumentOutOfRange(nameof(dueTime), + (long)dueTime.TotalMilliseconds); } if (period.TotalMilliseconds < -1) { - throw new ArgumentOutOfRangeException(nameof(period)); + throw ExceptionFactory.TimerArgumentOutOfRange(nameof(period), + (long)period.TotalMilliseconds); } try diff --git a/Tests/Testably.Abstractions.Testing.Tests/Helpers/EnumerationOptionsHelperTests.cs b/Tests/Testably.Abstractions.Testing.Tests/Helpers/EnumerationOptionsHelperTests.cs index fb9ab3be5..b8f7ccb4e 100644 --- a/Tests/Testably.Abstractions.Testing.Tests/Helpers/EnumerationOptionsHelperTests.cs +++ b/Tests/Testably.Abstractions.Testing.Tests/Helpers/EnumerationOptionsHelperTests.cs @@ -15,7 +15,8 @@ void Act() EnumerationOptionsHelper.FromSearchOption(invalidSearchOption); } - await That(Act).ThrowsExactly().WithParamName("searchOption"); + await That(Act).ThrowsExactly().WithParamName("searchOption").And + .WithMessage("Enum value was out of legal range.*").AsWildcard(); } #if NET6_0_OR_GREATER diff --git a/Tests/Testably.Abstractions.Testing.Tests/TimeSystem/TimerMockTests.cs b/Tests/Testably.Abstractions.Testing.Tests/TimeSystem/TimerMockTests.cs index 3ad1e61d8..a6951c232 100644 --- a/Tests/Testably.Abstractions.Testing.Tests/TimeSystem/TimerMockTests.cs +++ b/Tests/Testably.Abstractions.Testing.Tests/TimeSystem/TimerMockTests.cs @@ -129,10 +129,7 @@ void Act() await That(Act).DoesNotThrow(); #else await That(Act).Throws() - .Whose(x => x.Message, - it => it.Satisfies(m - => m!.Contains("Cannot access a disposed object.", StringComparison.Ordinal) && - m!.Contains(nameof(ITimer.Change), StringComparison.Ordinal))); + .WithMessage("Cannot access a disposed object."); #endif } diff --git a/Tests/Testably.Abstractions.Tests/FileSystem/Directory/SearchFilterTests.cs b/Tests/Testably.Abstractions.Tests/FileSystem/Directory/SearchFilterTests.cs index 800b904d7..f0188ad1f 100644 --- a/Tests/Testably.Abstractions.Tests/FileSystem/Directory/SearchFilterTests.cs +++ b/Tests/Testably.Abstractions.Tests/FileSystem/Directory/SearchFilterTests.cs @@ -7,6 +7,21 @@ namespace Testably.Abstractions.Tests.FileSystem.Directory; [FileSystemTests] public class SearchFilterTests(FileSystemTestData testData) : FileSystemTestBase(testData) { + [Test] + public async Task SearchOption_Invalid_ShouldThrowArgumentOutOfRangeException() + { + SearchOption invalidSearchOption = (SearchOption)(-1); + + void Act() + { + FileSystem.Directory.GetFileSystemEntries(".", "*", invalidSearchOption); + } + + await That(Act).ThrowsExactly() + .WithParamName("searchOption").And + .WithMessage("Enum value was out of legal range.*").AsWildcard(); + } + [Test] [AutoArguments("../", 4)] [AutoArguments("../*", 4)] @@ -155,7 +170,8 @@ void Act() .GetFileSystemEntries(".", searchPattern, SearchOption.AllDirectories); } - await That(Act).Throws().WithHResult(-2147024891); + await That(Act).Throws().WithHResult(-2147024891).And + .WithMessage("Access to the path '*' is denied.").AsWildcard(); } [Test] diff --git a/Tests/Testably.Abstractions.Tests/TimeSystem/TimerFactoryTests.cs b/Tests/Testably.Abstractions.Tests/TimeSystem/TimerFactoryTests.cs index 6f9cfe07f..b6c26741b 100644 --- a/Tests/Testably.Abstractions.Tests/TimeSystem/TimerFactoryTests.cs +++ b/Tests/Testably.Abstractions.Tests/TimeSystem/TimerFactoryTests.cs @@ -91,7 +91,14 @@ void Act() } await That(Act).Throws().WithHResult(-2146233086).And - .WithParamName(nameof(dueTime)); + .WithParamName(nameof(dueTime)).And +#if NETFRAMEWORK + .WithMessage( + $"Number must be either non-negative and less than or equal to Int32.MaxValue or -1.{Environment.NewLine}Parameter name: dueTime"); +#else + .WithMessage( + $"dueTime ('{dueTime}') must be greater than or equal to '-1'. (Parameter 'dueTime'){Environment.NewLine}Actual value was {dueTime}."); +#endif } [Test] @@ -107,7 +114,14 @@ void Act() } await That(Act).Throws().WithHResult(-2146233086).And - .WithParamName(nameof(period)); + .WithParamName(nameof(period)).And +#if NETFRAMEWORK + .WithMessage( + $"Number must be either non-negative and less than or equal to Int32.MaxValue or -1.{Environment.NewLine}Parameter name: period"); +#else + .WithMessage( + $"period ('{period}') must be greater than or equal to '-1'. (Parameter 'period'){Environment.NewLine}Actual value was {period}."); +#endif } [Test] diff --git a/Tests/Testably.Abstractions.Tests/TimeSystem/TimerTests.cs b/Tests/Testably.Abstractions.Tests/TimeSystem/TimerTests.cs index 19d5e4027..f7183a3cb 100644 --- a/Tests/Testably.Abstractions.Tests/TimeSystem/TimerTests.cs +++ b/Tests/Testably.Abstractions.Tests/TimeSystem/TimerTests.cs @@ -51,7 +51,8 @@ void Act() _ = timer.Change(100, 200); } - await That(Act).ThrowsExactly(); + await That(Act).ThrowsExactly() + .WithMessage("Cannot access a disposed object."); } #endif @@ -103,7 +104,14 @@ void Act() } await That(Act).Throws().WithHResult(-2146233086).And - .WithParamName(nameof(dueTime)); + .WithParamName(nameof(dueTime)).And +#if NETFRAMEWORK + .WithMessage( + $"Number must be either non-negative and less than or equal to Int32.MaxValue or -1.{Environment.NewLine}Parameter name: dueTime"); +#else + .WithMessage( + $"dueTime ('{dueTime}') must be greater than or equal to '-1'. (Parameter 'dueTime'){Environment.NewLine}Actual value was {dueTime}."); +#endif } [Test] @@ -122,7 +130,14 @@ void Act() } await That(Act).Throws().WithHResult(-2146233086).And - .WithParamName(nameof(period)); + .WithParamName(nameof(period)).And +#if NETFRAMEWORK + .WithMessage( + $"Number must be either non-negative and less than or equal to Int32.MaxValue or -1.{Environment.NewLine}Parameter name: period"); +#else + .WithMessage( + $"period ('{period}') must be greater than or equal to '-1'. (Parameter 'period'){Environment.NewLine}Actual value was {period}."); +#endif } [Test]