From b3eaac7d013dd26c6829b41fe8156bbf0095b6d1 Mon Sep 17 00:00:00 2001 From: spkl Date: Sun, 29 Sep 2024 19:47:04 +0200 Subject: [PATCH] Use FluentAssertions --- test/CLI.IPC.Test/CLI.IPC.Test.csproj | 5 ++ test/CLI.IPC.Test/ClientTest.cs | 7 +- .../DefaultHostConnectionHandlerTest.cs | 26 ++++--- .../DefaultHostConnectionHandlerTest.cs | 14 ++-- .../ExecutionTests/DynamicExecutionTest.cs | 2 +- .../ExecutionTests/HostShutdownTest.cs | 12 ++-- .../ExecutionTests/MultipleClientsTest.cs | 10 +-- .../ExecutionTests/SingletonTest.cs | 18 ++--- test/CLI.IPC.Test/GlobalUsings.cs | 3 + test/CLI.IPC.Test/HostTest.cs | 35 ++++++---- .../Internal/DelegateTextWriterTest.cs | 10 +-- test/CLI.IPC.Test/Internal/DisposableTest.cs | 12 ++-- test/CLI.IPC.Test/Internal/FileLockTest.cs | 70 +++++++++---------- test/CLI.IPC.Test/Internal/FileLocker.cs | 2 +- test/CLI.IPC.Test/ListenerErrorTest.cs | 8 +-- .../Messaging/MessageChannelHostTest.cs | 16 ++--- .../Messaging/MessageReceiverTest.cs | 6 +- .../Messaging/MessageSenderTest.cs | 2 +- .../Startup/AutoTransportSingletonAppTest.cs | 52 +++++++------- test/CLI.IPC.Test/Startup/SingletonAppTest.cs | 30 ++++---- .../Startup/StartupBehaviorTest.cs | 8 +-- test/CLI.IPC.Test/TcpLoopbackTransportTest.cs | 18 ++--- test/CLI.IPC.Test/UdsTransportTest.cs | 20 +++--- 23 files changed, 198 insertions(+), 188 deletions(-) diff --git a/test/CLI.IPC.Test/CLI.IPC.Test.csproj b/test/CLI.IPC.Test/CLI.IPC.Test.csproj index 050fbf4..483330a 100644 --- a/test/CLI.IPC.Test/CLI.IPC.Test.csproj +++ b/test/CLI.IPC.Test/CLI.IPC.Test.csproj @@ -17,6 +17,11 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/test/CLI.IPC.Test/ClientTest.cs b/test/CLI.IPC.Test/ClientTest.cs index cb07dd4..3b1128d 100644 --- a/test/CLI.IPC.Test/ClientTest.cs +++ b/test/CLI.IPC.Test/ClientTest.cs @@ -1,5 +1,6 @@ using spkl.CLI.IPC.Messaging; using spkl.CLI.IPC.Services; +using System; using System.Net.Sockets; namespace spkl.CLI.IPC.Test; @@ -19,7 +20,8 @@ public void AttachThrowsConnectionExceptionIfNoConnectionCanBeEstablished(int po IHostConnectionHandler hostConnectionHandler = Substitute.For(); // act & assert - Assert.That(() => Client.Attach(transport, hostConnectionHandler), Throws.InstanceOf().With.Message.Contains("Could not connect")); + Action attach = () => Client.Attach(transport, hostConnectionHandler); + attach.Should().Throw().WithMessage("Could not connect*"); } [Test] @@ -33,6 +35,7 @@ public void AttachThrowsConnectionExceptionIfConnectionIsInterrupted() ServiceProvider.MessageChannelFactory.CreateForOutgoing(transport).Returns(messageChannel); // act & assert - Assert.That(() => Client.Attach(transport, hostConnectionHandler), Throws.InstanceOf().With.Message.Contains("There was an unexpected connection error")); + Action attach = () => Client.Attach(transport, hostConnectionHandler); + attach.Should().Throw().WithMessage("There was an unexpected connection error*"); } } diff --git a/test/CLI.IPC.Test/DefaultHostConnectionHandlerTest.cs b/test/CLI.IPC.Test/DefaultHostConnectionHandlerTest.cs index 0acd5c8..4270b18 100644 --- a/test/CLI.IPC.Test/DefaultHostConnectionHandlerTest.cs +++ b/test/CLI.IPC.Test/DefaultHostConnectionHandlerTest.cs @@ -17,31 +17,31 @@ public void SetUp() public void Arguments() { // act - string[] result = this.handler.Arguments; + string[] arguments = this.handler.Arguments; // assert - Assert.That(result, Is.EqualTo(Environment.GetCommandLineArgs())); + arguments.Should().Equal(Environment.GetCommandLineArgs()); } [Test] public void CurrentDirectory() { // act - string result = this.handler.CurrentDirectory; + string currentDirectory = this.handler.CurrentDirectory; // assert - Assert.That(result, Is.EqualTo(Environment.CurrentDirectory)); + currentDirectory.Should().Be(Environment.CurrentDirectory); } [Test] public void ProcessID() { // act - int result = this.handler.ProcessID; + int processId = this.handler.ProcessID; // assert using Process p = Process.GetCurrentProcess(); - Assert.That(result, Is.EqualTo(p.Id)); + processId.Should().Be(p.Id); } [Test] @@ -51,15 +51,14 @@ public void HandleOutString() TextWriter defaultWriter = Console.Out; try { - using StringWriter stringWriter = new(); - Console.SetOut(stringWriter); + using StringWriter consoleOut = new(); + Console.SetOut(consoleOut); // act this.handler.HandleOutString("MyOutString"); // arrange - Assert.That(stringWriter.ToString(), Is.EqualTo("MyOutString")); - + consoleOut.ToString().Should().Be("MyOutString"); } finally { @@ -74,15 +73,14 @@ public void HandleErrorString() TextWriter defaultWriter = Console.Error; try { - using StringWriter stringWriter = new(); - Console.SetError(stringWriter); + using StringWriter consoleError = new(); + Console.SetError(consoleError); // act this.handler.HandleErrorString("MyErrorString"); // arrange - Assert.That(stringWriter.ToString(), Is.EqualTo("MyErrorString")); - + consoleError.ToString().Should().Be("MyErrorString"); } finally { diff --git a/test/CLI.IPC.Test/ExecutionTests/DefaultHostConnectionHandlerTest.cs b/test/CLI.IPC.Test/ExecutionTests/DefaultHostConnectionHandlerTest.cs index ee58b0e..2aeac37 100644 --- a/test/CLI.IPC.Test/ExecutionTests/DefaultHostConnectionHandlerTest.cs +++ b/test/CLI.IPC.Test/ExecutionTests/DefaultHostConnectionHandlerTest.cs @@ -28,17 +28,17 @@ public void TestDefaultHostConnectionHandler() } #endif - Assert.Multiple(() => + using (new AssertionScope()) { - Assert.That(this.Client.ExitCode, Is.EqualTo(42)); - Assert.That(this.Client.StandardOutput.ReadToEnd(), Is.EqualTo( + this.Client.ExitCode.Should().Be(42); + this.Client.StandardOutput.ReadToEnd().Should().Be( @$"Arguments: {expectedExecutable},{string.Join(",", this.ClientArguments)}. CurrentDirectory: {TestContext.CurrentContext.TestDirectory}. -")); - Assert.That(this.Client.StandardError.ReadToEnd(), Is.EqualTo( +"); + this.Client.StandardError.ReadToEnd().Should().Be( @"This is an error output. -")); - }); +"); + } } private class ClientConnectionHandler : IClientConnectionHandler diff --git a/test/CLI.IPC.Test/ExecutionTests/DynamicExecutionTest.cs b/test/CLI.IPC.Test/ExecutionTests/DynamicExecutionTest.cs index 3e921df..0c38a80 100644 --- a/test/CLI.IPC.Test/ExecutionTests/DynamicExecutionTest.cs +++ b/test/CLI.IPC.Test/ExecutionTests/DynamicExecutionTest.cs @@ -133,7 +133,7 @@ protected void WaitForClientExit(Process client) () => $"Host has exited" + $"{Environment.NewLine}-- Out:{this.Host.StandardOutput.ReadToEnd()}" + $"{Environment.NewLine}-- Error:{this.Host.StandardError.ReadToEnd()}"); - Assert.That(client.WaitForExit(5_000), Is.True, "Client has exited"); + client.WaitForExit(5_000).Should().BeTrue("client should have exited"); } protected void RunHostAndClient() diff --git a/test/CLI.IPC.Test/ExecutionTests/HostShutdownTest.cs b/test/CLI.IPC.Test/ExecutionTests/HostShutdownTest.cs index fcf351d..067c878 100644 --- a/test/CLI.IPC.Test/ExecutionTests/HostShutdownTest.cs +++ b/test/CLI.IPC.Test/ExecutionTests/HostShutdownTest.cs @@ -18,13 +18,13 @@ public void TestHostShutdown() this.Host.StandardInput.WriteLine(); // assert - Assert.That(this.Host.WaitForExit(5_000), Is.True); - Assert.Multiple(() => + this.Host.WaitForExit(5_000).Should().BeTrue(); + using (new AssertionScope()) { - Assert.That(this.Host.ExitCode, Is.Zero); - Assert.That(this.Host.StandardOutput.ReadToEnd(), Is.Empty); - Assert.That(this.Host.StandardError.ReadToEnd(), Is.Empty); - }); + this.Host.ExitCode.Should().Be(0); + this.Host.StandardOutput.ReadToEnd().Should().BeEmpty(); + this.Host.StandardError.ReadToEnd().Should().BeEmpty(); + } } private class ClientConnectionHandler : IClientConnectionHandler diff --git a/test/CLI.IPC.Test/ExecutionTests/MultipleClientsTest.cs b/test/CLI.IPC.Test/ExecutionTests/MultipleClientsTest.cs index b5053eb..4914595 100644 --- a/test/CLI.IPC.Test/ExecutionTests/MultipleClientsTest.cs +++ b/test/CLI.IPC.Test/ExecutionTests/MultipleClientsTest.cs @@ -28,15 +28,15 @@ public void TestMultipleClients() } // assert - Assert.Multiple(() => + using (new AssertionScope()) { foreach (Process client in clients) { - Assert.That(client.ExitCode, Is.EqualTo(0)); - Assert.That(client.StandardOutput.ReadToEnd(), Is.EqualTo("Done")); - Assert.That(client.StandardError.ReadToEnd(), Is.Empty); + client.ExitCode.Should().Be(0); + client.StandardOutput.ReadToEnd().Should().Be("Done"); + client.StandardError.ReadToEnd().Should().BeEmpty(); } - }); + } } private class ClientConnectionHandler : IClientConnectionHandler diff --git a/test/CLI.IPC.Test/ExecutionTests/SingletonTest.cs b/test/CLI.IPC.Test/ExecutionTests/SingletonTest.cs index 20a9009..6cb3094 100644 --- a/test/CLI.IPC.Test/ExecutionTests/SingletonTest.cs +++ b/test/CLI.IPC.Test/ExecutionTests/SingletonTest.cs @@ -76,16 +76,16 @@ public void TestSingleton(string timeoutBehavior, int expectedProcesses) // assert TestContext.Out.WriteLine($"{startedProcesses} processes were started."); - Assert.Multiple(() => + using (new AssertionScope()) { - Assert.That(exitCodes, Has.Count.EqualTo(startedProcesses), "Number of exit codes"); - Assert.That(stdOutputs, Has.Count.EqualTo(startedProcesses), "Number of std outputs"); - Assert.That(errOutputs, Has.Count.EqualTo(startedProcesses), "Number of err outputs"); - Assert.That(exitCodes, Has.All.EqualTo(0), "Exit codes"); - Assert.That(stdOutputs.Distinct().ToArray(), Has.Exactly(expectedProcesses).Items.And.All.StartsWith("PID "), "Std outputs"); - Assert.That(errOutputs, Has.All.Empty, "Err outputs"); - Assert.That(Process.GetProcessesByName("spkl.CLI.IPC.Test.Singleton").Length, Is.EqualTo(0), "There should be no leftover process."); - }); + exitCodes.Should().HaveCount(startedProcesses); + stdOutputs.Should().HaveCount(startedProcesses); + errOutputs.Should().HaveCount(startedProcesses); + exitCodes.Should().AllSatisfy(exitCode => exitCode.Should().Be(0)); + stdOutputs.Distinct().Should().HaveCount(expectedProcesses).And.AllSatisfy(output => output.Should().StartWith("PID ")); + errOutputs.Should().AllSatisfy(errOutput => errOutput.Should().BeEmpty()); + Process.GetProcessesByName("spkl.CLI.IPC.Test.Singleton").Should().BeEmpty("there should be no leftover process"); + } } [TearDown] diff --git a/test/CLI.IPC.Test/GlobalUsings.cs b/test/CLI.IPC.Test/GlobalUsings.cs index 3e4da1d..5f78f34 100644 --- a/test/CLI.IPC.Test/GlobalUsings.cs +++ b/test/CLI.IPC.Test/GlobalUsings.cs @@ -1,2 +1,5 @@ +global using FluentAssertions; +global using FluentAssertions.Execution; global using NSubstitute; global using NUnit.Framework; +global using static FluentAssertions.FluentActions; diff --git a/test/CLI.IPC.Test/HostTest.cs b/test/CLI.IPC.Test/HostTest.cs index daa6bf7..026eba3 100644 --- a/test/CLI.IPC.Test/HostTest.cs +++ b/test/CLI.IPC.Test/HostTest.cs @@ -42,7 +42,8 @@ public void CanStartHostOnExistingFile() File.WriteAllText(fileName, ""); // act & assert - Assert.That(() => this.host = Host.Start(new UdsTransport(fileName), new ClientConnectionHandler()), Throws.Nothing); + Action startHost = () => this.host = Host.Start(new UdsTransport(fileName), new ClientConnectionHandler()); + startHost.Should().NotThrow(); this.WaitForHostStartUp(); } #endif @@ -66,18 +67,22 @@ public void TestHostInSameProcessAsClient(Func createTransport, Host this.host.WaitUntilAllClientsDisconnected(); // assert - Assert.That(clientConnectionHandler.ReceivedClientProperties, Is.Not.Null); - Assert.That(clientConnectionHandler.ReceivedClientProperties.Arguments, Is.EqualTo(hostConnectionHandler.Arguments)); - Assert.That(clientConnectionHandler.ReceivedClientProperties.CurrentDirectory, Is.EqualTo(hostConnectionHandler.CurrentDirectory)); - Assert.That(clientConnectionHandler.ReceivedClientProperties.ProcessID, Is.EqualTo(hostConnectionHandler.ExpectedProcessID)); - - Assert.That(hostConnectionHandler.ReceivedOutString, Is.EqualTo("Out1Out2" + Environment.NewLine)); - Assert.That(hostConnectionHandler.ReceivedErrorString, Is.EqualTo("Error1Error2" + Environment.NewLine)); - Assert.That(hostConnectionHandler.ReceivedExitCode, Is.EqualTo(42)); - - Assert.That(connectedClientsBefore, Is.EqualTo(0), "Number of connected clients before connecting"); - Assert.That(connectedClientsDuring, Is.EqualTo(1), "Number of connected clients during connection"); - Assert.That(this.host.ConnectedClients, Is.EqualTo(0), "Number of connected clients after shutdown"); + ClientProperties expectedClientProperties = new() + { + Arguments = hostConnectionHandler.Arguments, + CurrentDirectory = hostConnectionHandler.CurrentDirectory, + ProcessID = hostConnectionHandler.ExpectedProcessID + }; + + clientConnectionHandler.ReceivedClientProperties.Should().BeEquivalentTo(expectedClientProperties); + + hostConnectionHandler.ReceivedOutString.Should().Be("Out1Out2" + Environment.NewLine); + hostConnectionHandler.ReceivedErrorString.Should().Be("Error1Error2" + Environment.NewLine); + hostConnectionHandler.ReceivedExitCode.Should().Be(42); + + connectedClientsBefore.Should().Be(0); + connectedClientsDuring.Should().Be(1); + this.host.ConnectedClients.Should().Be(0, "host was shut down"); } [Test] @@ -89,7 +94,7 @@ public void WaitUntilAllClientsDisconnectedThrowsInvalidOperationExceptionWhenCa this.WaitForHostStartUp(); // act & assert - Assert.That(() => this.host.WaitUntilAllClientsDisconnected(), Throws.InvalidOperationException); + Invoking(() => this.host.WaitUntilAllClientsDisconnected()).Should().Throw(); } [Test] @@ -103,7 +108,7 @@ public void WaitUntilAllClientsDisconnectedThrowsInvalidOperationExceptionWhenCa this.host.WaitUntilAllClientsDisconnected(); // act & assert - Assert.That(() => this.host.WaitUntilAllClientsDisconnected(), Throws.InvalidOperationException); + Invoking(() => this.host.WaitUntilAllClientsDisconnected()).Should().Throw(); } diff --git a/test/CLI.IPC.Test/Internal/DelegateTextWriterTest.cs b/test/CLI.IPC.Test/Internal/DelegateTextWriterTest.cs index 326a37d..8ac950e 100644 --- a/test/CLI.IPC.Test/Internal/DelegateTextWriterTest.cs +++ b/test/CLI.IPC.Test/Internal/DelegateTextWriterTest.cs @@ -29,7 +29,7 @@ public void EncodingIsUtf8() Encoding result = this.writer.Encoding; // assert - Assert.That(result, Is.EqualTo(Encoding.UTF8)); + result.Should().Be(Encoding.UTF8); } [Test] @@ -39,7 +39,7 @@ public void WriteChar() this.writer.Write('x'); // assert - Assert.That(this.writtenStrings, Is.EqualTo(new string[] { "x" })); + this.writtenStrings.Should().Equal(new string[] { "x" }); } [Test] @@ -49,7 +49,7 @@ public void WriteCharArrayIntInt() this.writer.Write("foobar".ToCharArray(), 1, 4); // assert - Assert.That(this.writtenStrings, Is.EqualTo(new string[] { "ooba" })); + this.writtenStrings.Should().Equal(new string[] { "ooba" }); } [Test] @@ -59,7 +59,7 @@ public void WriteString() this.writer.Write("foobar"); // assert - Assert.That(this.writtenStrings, Is.EqualTo(new string[] { "foobar" })); + this.writtenStrings.Should().Equal(new string[] { "foobar" }); } [Test] @@ -69,6 +69,6 @@ public void WriteStringNull() this.writer.Write((string?)null); // assert - Assert.That(this.writtenStrings, Is.Empty); + this.writtenStrings.Should().BeEmpty(); } } diff --git a/test/CLI.IPC.Test/Internal/DisposableTest.cs b/test/CLI.IPC.Test/Internal/DisposableTest.cs index 9ca0aa3..7462967 100644 --- a/test/CLI.IPC.Test/Internal/DisposableTest.cs +++ b/test/CLI.IPC.Test/Internal/DisposableTest.cs @@ -7,22 +7,22 @@ internal class DisposableTest : TestBase public void DisposeCallsCallback() { // arrange - int i = 0; - Disposable disposable = new(() => i++); + int callCount = 0; + Disposable disposable = new(() => callCount++); // act disposable.Dispose(); // assert - Assert.That(i, Is.EqualTo(1)); + callCount.Should().Be(1); } [Test] public void DisposeCallsCallbackOnlyOnce() { // arrange - int i = 0; - Disposable disposable = new(() => i++); + int callCount = 0; + Disposable disposable = new(() => callCount++); // act disposable.Dispose(); @@ -30,6 +30,6 @@ public void DisposeCallsCallbackOnlyOnce() disposable.Dispose(); // assert - Assert.That(i, Is.EqualTo(1)); + callCount.Should().Be(1); } } diff --git a/test/CLI.IPC.Test/Internal/FileLockTest.cs b/test/CLI.IPC.Test/Internal/FileLockTest.cs index ad1832d..50c85ae 100644 --- a/test/CLI.IPC.Test/Internal/FileLockTest.cs +++ b/test/CLI.IPC.Test/Internal/FileLockTest.cs @@ -29,20 +29,20 @@ public void TearDown() public void IsNotLockedInitially() { // act - bool result = this.fileLock.IsLocked(); + bool isLocked = this.fileLock.IsLocked(); // assert - Assert.That(result, Is.False); + isLocked.Should().BeFalse(); } [Test] public void IsNotHoldingLockInitially() { // act - bool result = this.fileLock.IsHoldingLock(); + bool isHoldingLock = this.fileLock.IsHoldingLock(); // assert - Assert.That(result, Is.False); + isHoldingLock.Should().BeFalse(); } [Test] @@ -52,23 +52,23 @@ public void LockLocksTheFile() this.fileLock.Lock(); // assert - Assert.That(this.fileLock.Path, Does.Exist); - Assert.That(() => FileStreams.OpenForSharedReading(this.fileLock.Path), Throws.Exception); - Assert.That(this.fileLock.IsHoldingLock(), Is.True); - Assert.That(this.fileLock.IsLocked(), Is.True); + File.Exists(this.fileLock.Path).Should().BeTrue(); + Invoking(() => FileStreams.OpenForSharedReading(this.fileLock.Path)).Should().Throw(); + this.fileLock.IsHoldingLock().Should().BeTrue(); + this.fileLock.IsLocked().Should().BeTrue(); } [Test] public void TryLockLocksTheFileIfItIsNotLocked() { // act - bool result = this.fileLock.TryLock(); + bool tryLock = this.fileLock.TryLock(); // assert - Assert.That(result, Is.True); - Assert.That(() => FileStreams.OpenForSharedReading(this.fileLock.Path), Throws.Exception); - Assert.That(this.fileLock.IsHoldingLock(), Is.True); - Assert.That(this.fileLock.IsLocked(), Is.True); + tryLock.Should().BeTrue(); + Invoking(() => FileStreams.OpenForSharedReading(this.fileLock.Path)).Should().Throw(); + this.fileLock.IsHoldingLock().Should().BeTrue(); + this.fileLock.IsLocked().Should().BeTrue(); } [Test] @@ -78,11 +78,11 @@ public void TryLockReturnsFalseIfTheFileIsAlreadyLocked() using FileLocker _ = FileLocker.Lock(this.fileLock.Path); // act - bool result = this.fileLock.TryLock(); + bool tryLock = this.fileLock.TryLock(); // assert - Assert.That(result, Is.False); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + tryLock.Should().BeFalse(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } [Test] @@ -97,12 +97,12 @@ public void TryLockWithTimeoutLocksTheFileAsSoonAsItIsNotLocked() }); // act - bool result = this.fileLock.TryLock(TimeSpan.FromSeconds(3)); + bool tryLock = this.fileLock.TryLock(TimeSpan.FromSeconds(3)); // assert - Assert.That(result, Is.True); - Assert.That(() => FileStreams.OpenForSharedReading(this.fileLock.Path), Throws.Exception); - Assert.That(this.fileLock.IsHoldingLock(), Is.True); + tryLock.Should().BeTrue(); + Invoking(() => FileStreams.OpenForSharedReading(this.fileLock.Path)).Should().Throw(); + this.fileLock.IsHoldingLock().Should().BeTrue(); } [Test] @@ -112,11 +112,11 @@ public void TryLockWithTimeoutReturnsFalseIfTheLockCannotBeObtained() using FileLocker _ = FileLocker.Lock(this.fileLock.Path); // act - bool result = this.fileLock.TryLock(TimeSpan.FromSeconds(1)); + bool tryLock = this.fileLock.TryLock(TimeSpan.FromSeconds(1)); // assert - Assert.That(result, Is.False); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + tryLock.Should().BeFalse(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } [Test] @@ -126,11 +126,11 @@ public void IsLockedReturnsTrueIfFileIsLocked() using FileLocker _ = FileLocker.Lock(this.fileLock.Path); // act - bool result = this.fileLock.IsLocked(); + bool isLocked = this.fileLock.IsLocked(); // assert - Assert.That(result, Is.True); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + isLocked.Should().BeTrue(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } [Test] @@ -141,11 +141,11 @@ public void IsLockedReturnsFalseAfterFileIsUnlocked() this.fileLock.Unlock(); // act - bool result = this.fileLock.IsLocked(); + bool isLocked = this.fileLock.IsLocked(); // assert - Assert.That(result, Is.False); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + isLocked.Should().BeFalse(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } [Test] @@ -155,11 +155,11 @@ public void IsLockedReturnsFalseIsFileExistsButIsNotLocked() File.WriteAllText(this.fileLock.Path, string.Empty); // act - bool result = this.fileLock.IsLocked(); + bool isLocked = this.fileLock.IsLocked(); // assert - Assert.That(result, Is.False); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + isLocked.Should().BeFalse(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } [Test] @@ -172,8 +172,8 @@ public void UnlockUnlocksAndDeletesTheFile() this.fileLock.Unlock(); // assert - Assert.That(this.fileLock.Path, Does.Not.Exist); - Assert.That(() => FileStreams.OpenForExclusiveWriting(this.fileLock.Path).Dispose(), Throws.Nothing); - Assert.That(this.fileLock.IsHoldingLock(), Is.False); + File.Exists(this.fileLock.Path).Should().BeFalse(); + Invoking(() => FileStreams.OpenForExclusiveWriting(this.fileLock.Path).Dispose()).Should().NotThrow(); + this.fileLock.IsHoldingLock().Should().BeFalse(); } } diff --git a/test/CLI.IPC.Test/Internal/FileLocker.cs b/test/CLI.IPC.Test/Internal/FileLocker.cs index 1038b24..178d8a8 100644 --- a/test/CLI.IPC.Test/Internal/FileLocker.cs +++ b/test/CLI.IPC.Test/Internal/FileLocker.cs @@ -24,7 +24,7 @@ public static FileLocker Lock(string path) process.Start(); string? output = process.StandardOutput.ReadLine(); - Assert.That(output, Is.EqualTo("locked")); + output.Should().Be("locked"); return new FileLocker(process); } diff --git a/test/CLI.IPC.Test/ListenerErrorTest.cs b/test/CLI.IPC.Test/ListenerErrorTest.cs index 7166b63..7a1f1b1 100644 --- a/test/CLI.IPC.Test/ListenerErrorTest.cs +++ b/test/CLI.IPC.Test/ListenerErrorTest.cs @@ -14,7 +14,7 @@ public void Exception() Exception result = error.Exception; // assert - Assert.That(result, Is.EqualTo(exception)); + result.Should().BeSameAs(exception); } [Theory] @@ -27,7 +27,7 @@ public void ErrorPoint(ListenerErrorPoint value) ListenerErrorPoint result = error.ErrorPoint; // assert - Assert.That(result, Is.EqualTo(value)); + result.Should().Be(value); } [Test] @@ -43,7 +43,7 @@ public void IsHostInterrupted(ListenerErrorPoint errorPoint, bool expected) bool result = error.IsHostInterrupted; // assert - Assert.That(result, Is.EqualTo(expected)); + result.Should().Be(expected); } [Test] @@ -57,6 +57,6 @@ public void ToStringReturnsExceptionToString() string result = error.ToString(); // assert - Assert.That(result, Is.EqualTo(exception.ToString())); + result.Should().Be(exception.ToString()); } } diff --git a/test/CLI.IPC.Test/Messaging/MessageChannelHostTest.cs b/test/CLI.IPC.Test/Messaging/MessageChannelHostTest.cs index b6487f5..53547b6 100644 --- a/test/CLI.IPC.Test/Messaging/MessageChannelHostTest.cs +++ b/test/CLI.IPC.Test/Messaging/MessageChannelHostTest.cs @@ -46,12 +46,12 @@ void HandleListenerException(Exception exception, ListenerErrorPoint errorPoint) // act this.messageChannelHost.AcceptConnections(); new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp).Connect(new IPEndPoint(IPAddress.Loopback, port)); - bool timeout = !waitHandle.WaitOne(TimeSpan.FromSeconds(5)); + bool timedOut = !waitHandle.WaitOne(TimeSpan.FromSeconds(5)); // assert - Assert.That(timeout, Is.False, "Timeout"); - Assert.That(receivedException, Is.EqualTo(exception)); - Assert.That(receivedErrorPoint, Is.EqualTo(ListenerErrorPoint.ConnectionAccept)); + timedOut.Should().BeFalse(); + receivedException.Should().BeSameAs(exception); + receivedErrorPoint.Should().Be(ListenerErrorPoint.ConnectionAccept); } [Test] @@ -85,11 +85,11 @@ void HandleListenerException(Exception exception, ListenerErrorPoint errorPoint) // act this.messageChannelHost.AcceptConnections(); new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp).Connect(new IPEndPoint(IPAddress.Loopback, port)); - bool timeout = !waitHandle.WaitOne(TimeSpan.FromSeconds(5)); + bool timedOut = !waitHandle.WaitOne(TimeSpan.FromSeconds(5)); // assert - Assert.That(timeout, Is.False, "Timeout"); - Assert.That(receivedException, Is.EqualTo(exception)); - Assert.That(receivedErrorPoint, Is.EqualTo(ListenerErrorPoint.ClientConnectionHandler)); + timedOut.Should().BeFalse(); + receivedException.Should().BeSameAs(exception); + receivedErrorPoint.Should().Be(ListenerErrorPoint.ClientConnectionHandler); } } diff --git a/test/CLI.IPC.Test/Messaging/MessageReceiverTest.cs b/test/CLI.IPC.Test/Messaging/MessageReceiverTest.cs index e461e72..5339dd0 100644 --- a/test/CLI.IPC.Test/Messaging/MessageReceiverTest.cs +++ b/test/CLI.IPC.Test/Messaging/MessageReceiverTest.cs @@ -29,7 +29,7 @@ public void ReceiveMethodsThrowConnectionExceptionIfDifferentMessageTypeWasRecei sendSocket.SendTo(new byte[] { (byte)MessageType.Exit }, endPoint); // act & assert - Assert.That(() => callReceiveMethod(messageReceiver), Throws.InstanceOf()); + Invoking(() => callReceiveMethod(messageReceiver)).Should().Throw(); } [Test] @@ -43,7 +43,7 @@ public void ExpectStringCanReceiveZeroLengthString() string result = messageReceiver.ExpectString(); // assert - Assert.That(result, Is.Not.Null.And.Empty); + result.Should().NotBeNull().And.BeEmpty(); } [Test] @@ -54,7 +54,7 @@ public void ExpectBytesThrowsConnectionExceptionIfBytesWereExpectedButNotReceive sendSocket.SendTo(Array.Empty(), endPoint); // act & assert - Assert.That(() => messageReceiver.ExpectBytes(1), Throws.InstanceOf()); + Invoking(() => messageReceiver.ExpectBytes(1)).Should().Throw(); } private Socket CreateUdpSocket() diff --git a/test/CLI.IPC.Test/Messaging/MessageSenderTest.cs b/test/CLI.IPC.Test/Messaging/MessageSenderTest.cs index 565cd0e..c83adc5 100644 --- a/test/CLI.IPC.Test/Messaging/MessageSenderTest.cs +++ b/test/CLI.IPC.Test/Messaging/MessageSenderTest.cs @@ -11,6 +11,6 @@ public void SendBytesThrowsConnectionExceptionForSocketError() MessageSender messageSender = new(new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)); // act & assert - Assert.That(() => messageSender.SendOutStr(""), Throws.InstanceOf().With.InnerException.InstanceOf()); + Invoking(() => messageSender.SendOutStr("")).Should().Throw().WithInnerException(); } } diff --git a/test/CLI.IPC.Test/Startup/AutoTransportSingletonAppTest.cs b/test/CLI.IPC.Test/Startup/AutoTransportSingletonAppTest.cs index d3c7cf0..29addf8 100644 --- a/test/CLI.IPC.Test/Startup/AutoTransportSingletonAppTest.cs +++ b/test/CLI.IPC.Test/Startup/AutoTransportSingletonAppTest.cs @@ -1,5 +1,6 @@ using spkl.CLI.IPC.Internal; using spkl.CLI.IPC.Startup; +using System; using System.IO; namespace spkl.CLI.IPC.Test.Startup; @@ -38,8 +39,8 @@ public void RequestInstanceReturnsWithDeserializedTransportIfApplicationRunning( ITransport transport = this.singletonApp.Transport; // assert - Assert.That(transport, Is.InstanceOf()); - Assert.That(((TcpLoopbackTransport)transport).Port, Is.EqualTo(1234)); + transport.Should().BeOfType(); + transport.As().Port.Should().Be(1234); } [Test] @@ -49,7 +50,7 @@ public void RequestInstanceThrowsExceptionIfTransportDataIsNotReady() this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create)); // act & assert - Assert.That(() => this.singletonApp.RequestInstance(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.RequestInstance()).Should().Throw(); } [Test] @@ -61,7 +62,7 @@ public void RequestInstanceThrowsExceptionIfTransportDataIsReadyButMissing() this.disposables.Add(File.Open(this.negotiationFile + ".transport_ready", FileMode.Create)); // act & assert - Assert.That(() => this.singletonApp.RequestInstance(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.RequestInstance()).Should().Throw(); } [Test] @@ -71,12 +72,10 @@ public void ReportInstanceRunningLocksFiles() this.singletonApp.ReportInstanceRunning(); // assert - Assert.That( - () => this.disposables.Add(File.Open(this.negotiationFile + ".transport_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)), - Throws.InstanceOf()); - Assert.That( - () => this.disposables.Add(File.Open(this.negotiationFile + ".transport_ready", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)), - Throws.InstanceOf()); + Action openTransportLockShared = () => this.disposables.Add(File.Open(this.negotiationFile + ".transport_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)); + openTransportLockShared.Should().Throw(); + Action openTransportReadyShared = () => this.disposables.Add(File.Open(this.negotiationFile + ".transport_ready", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)); + openTransportReadyShared.Should().Throw(); } [Test] @@ -94,8 +93,8 @@ public void ReportInstanceRunningSerializesTransport() { ITransport transport = Serializer.Read(type, data); - Assert.That(transport, Is.InstanceOf()); - Assert.That(((TcpLoopbackTransport)transport).Port, Is.EqualTo(2345)); + transport.Should().BeOfType(); + transport.As().Port.Should().Be(2345); } } @@ -106,7 +105,7 @@ public void ReportInstanceRunningThrowsExceptionIfFileIsLocked() this.disposables.Add(File.Open(this.negotiationFile + ".transport_lock", FileMode.Create)); // act & assert - Assert.That(() => this.singletonApp.ReportInstanceRunning(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.ReportInstanceRunning()).Should().Throw(); } [Test] @@ -119,10 +118,10 @@ public void ReportInstanceShuttingDownUnlocksFiles() this.singletonApp.ReportInstanceShuttingDown(); // assert - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_type", FileMode.Create)), Throws.Nothing); - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_data", FileMode.Create)), Throws.Nothing); - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_ready", FileMode.Create)), Throws.Nothing); - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_lock", FileMode.Create)), Throws.Nothing); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_type", FileMode.Create))).Should().NotThrow(); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_data", FileMode.Create))).Should().NotThrow(); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_ready", FileMode.Create))).Should().NotThrow(); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".transport_lock", FileMode.Create))).Should().NotThrow(); } [Test] @@ -134,9 +133,8 @@ public void SuspendStartupLocksFile() ); // assert - Assert.That( - () => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)), - Throws.InstanceOf()); + Action openStartLockShared = () => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)); + openStartLockShared.Should().Throw(); } [Theory] @@ -149,10 +147,10 @@ public void IsInstanceRunningReflectsFileLockState(bool fileLocked) } // act - bool result = this.singletonApp.IsInstanceRunning(); + bool isInstanceRunning = this.singletonApp.IsInstanceRunning(); // assert - Assert.That(result, Is.EqualTo(fileLocked)); + isInstanceRunning.Should().Be(fileLocked); } [Theory] @@ -165,10 +163,10 @@ public void IsInstanceStartingReflectsFileLockState(bool fileLocked) } // act - bool result = this.singletonApp.IsInstanceStarting(); + bool isInstanceStarting = this.singletonApp.IsInstanceStarting(); // assert - Assert.That(result, Is.EqualTo(fileLocked)); + isInstanceStarting.Should().Be(fileLocked); } #if NET6_0_OR_GREATER @@ -179,7 +177,7 @@ public void TransportIsUdsIfPathShortEnough() ITransport transport = this.singletonApp.Transport; // assert - Assert.That(transport, Is.InstanceOf()); + transport.Should().BeOfType(); } [Test] @@ -194,7 +192,7 @@ public void TransportIsTcpIfPathTooLong() ITransport transport = this.singletonApp.Transport; // assert - Assert.That(transport, Is.InstanceOf()); + transport.Should().BeOfType(); } #else [Test] @@ -204,7 +202,7 @@ public void TransportIsTcp() ITransport transport = this.singletonApp.Transport; // assert - Assert.That(transport, Is.InstanceOf()); + transport.Should().BeOfType(); } #endif diff --git a/test/CLI.IPC.Test/Startup/SingletonAppTest.cs b/test/CLI.IPC.Test/Startup/SingletonAppTest.cs index 7e0628e..32448db 100644 --- a/test/CLI.IPC.Test/Startup/SingletonAppTest.cs +++ b/test/CLI.IPC.Test/Startup/SingletonAppTest.cs @@ -72,7 +72,7 @@ public void RequestInstanceCallsStartInstanceIfNoApplicationRunningOrStarting() public void RequestInstanceThrowsExceptionIfNoApplicationIsStartedBeforeTimeout() { // act & assert - Assert.That(() => this.singletonApp.RequestInstance(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.RequestInstance()).Should().Throw(); } [Test] @@ -82,9 +82,8 @@ public void ReportInstanceRunningLocksFile() this.singletonApp.ReportInstanceRunning(); // assert - Assert.That( - () => this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)), - Throws.InstanceOf()); + Action openRunLockShared = () => this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)); + openRunLockShared.Should().Throw(); } [Test] @@ -94,14 +93,14 @@ public void ReportInstanceRunningThrowsExceptionIfFileLockCannotBeObtained() this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create)); // act & assert - Assert.That(() => this.singletonApp.ReportInstanceRunning(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.ReportInstanceRunning()).Should().Throw(); } [Test] public void ReportInstanceShuttingDownThrowsExceptionIfReportInstanceRunningWasNotCalled() { // act & assert - Assert.That(() => this.singletonApp.ReportInstanceShuttingDown(), Throws.InstanceOf()); + Invoking(() => this.singletonApp.ReportInstanceShuttingDown()).Should().Throw(); } [Test] @@ -114,7 +113,7 @@ public void ReportInstanceShuttingDownUnlocksFile() this.singletonApp.ReportInstanceShuttingDown(); // assert - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create)), Throws.Nothing); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".run_lock", FileMode.Create))).Should().NotThrow(); } [Test] @@ -126,9 +125,8 @@ public void SuspendStartupLocksFile() ); // assert - Assert.That( - () => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)), - Throws.InstanceOf()); + Action openStartLockShared = () => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)); + openStartLockShared.Should().Throw(); } [Test] @@ -138,7 +136,7 @@ public void SuspendStartupTwiceThrowsException() this.disposables.Add(this.singletonApp.SuspendStartup()); // act & assert - Assert.That(() => this.disposables.Add(this.singletonApp.SuspendStartup()), Throws.InstanceOf()); + Invoking(() => this.disposables.Add(this.singletonApp.SuspendStartup())).Should().Throw(); } [Test] @@ -151,7 +149,7 @@ public void SuspendStartupDisposeUnlocksFile() disposable.Dispose(); // assert - Assert.That(() => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create)), Throws.Nothing); + Invoking(() => this.disposables.Add(File.Open(this.negotiationFile + ".start_lock", FileMode.Create))).Should().NotThrow(); } [Theory] @@ -164,10 +162,10 @@ public void IsInstanceRunningReflectsFileLockState(bool fileLocked) } // act - bool result = this.singletonApp.IsInstanceRunning(); + bool isInstanceRunning = this.singletonApp.IsInstanceRunning(); // assert - Assert.That(result, Is.EqualTo(fileLocked)); + isInstanceRunning.Should().Be(fileLocked); } @@ -182,9 +180,9 @@ public void IsInstanceStartingReflectsFileLockState(bool fileLocked) } // act - bool result = this.singletonApp.IsInstanceStarting(); + bool isInstanceStarting = this.singletonApp.IsInstanceStarting(); // assert - Assert.That(result, Is.EqualTo(fileLocked)); + isInstanceStarting.Should().Be(fileLocked); } } diff --git a/test/CLI.IPC.Test/Startup/StartupBehaviorTest.cs b/test/CLI.IPC.Test/Startup/StartupBehaviorTest.cs index 3870b4c..ea62422 100644 --- a/test/CLI.IPC.Test/Startup/StartupBehaviorTest.cs +++ b/test/CLI.IPC.Test/Startup/StartupBehaviorTest.cs @@ -19,9 +19,9 @@ public void Ctor() startupBehavior.StartInstance(); // assert - Assert.That(startupBehavior.NegotiationFileBasePath, Is.EqualTo(arg1)); - Assert.That(startupBehavior.PollingPeriod, Is.EqualTo(arg2)); - Assert.That(startupBehavior.TimeoutThreshold, Is.EqualTo(arg3)); - Assert.That(calls, Is.EqualTo(1)); + startupBehavior.NegotiationFileBasePath.Should().Be(arg1); + startupBehavior.PollingPeriod.Should().Be(arg2); + startupBehavior.TimeoutThreshold.Should().Be(arg3); + calls.Should().Be(1); } } diff --git a/test/CLI.IPC.Test/TcpLoopbackTransportTest.cs b/test/CLI.IPC.Test/TcpLoopbackTransportTest.cs index 8ba1039..09a847b 100644 --- a/test/CLI.IPC.Test/TcpLoopbackTransportTest.cs +++ b/test/CLI.IPC.Test/TcpLoopbackTransportTest.cs @@ -16,8 +16,8 @@ public void EndPointIsIPEndPointWithChosenPort() EndPoint result = t.EndPoint; // assert - Assert.That(result, Is.InstanceOf()); - Assert.That(((IPEndPoint)result).Port, Is.EqualTo(23230)); + result.Should().BeOfType(); + result.As().Port.Should().Be(23230); } [Test] @@ -27,28 +27,28 @@ public void SocketIsNotNull() TcpLoopbackTransport t = new(0); // act - Socket result = t.Socket; + Socket socket = t.Socket; // assert - Assert.That(result, Is.Not.Null); + socket.Should().NotBeNull(); } [Test] public void CanSerialize() { // arrange - TcpLoopbackTransport t = new(23230); + TcpLoopbackTransport transport = new(23230); using MemoryStream typeStream = new MemoryStream(); using MemoryStream dataStream = new MemoryStream(); // act - Serializer.Write(t, typeStream, dataStream); + Serializer.Write(transport, typeStream, dataStream); typeStream.Seek(0, SeekOrigin.Begin); dataStream.Seek(0, SeekOrigin.Begin); - t = Serializer.Read(typeStream, dataStream); + transport = Serializer.Read(typeStream, dataStream); // assert - Assert.That(t, Is.Not.Null); - Assert.That(t.Port, Is.EqualTo(23230)); + transport.Should().NotBeNull(); + transport.Port.Should().Be(23230); } } diff --git a/test/CLI.IPC.Test/UdsTransportTest.cs b/test/CLI.IPC.Test/UdsTransportTest.cs index c239d76..68b308c 100644 --- a/test/CLI.IPC.Test/UdsTransportTest.cs +++ b/test/CLI.IPC.Test/UdsTransportTest.cs @@ -14,11 +14,11 @@ public void EndPointIsUdsEndPointWithChosenPath() UdsTransport t = new("test"); // act - EndPoint result = t.EndPoint; + EndPoint endPoint = t.EndPoint; // assert - Assert.That(result, Is.InstanceOf()); - Assert.That(((UnixDomainSocketEndPoint)result).ToString(), Is.EqualTo("test")); + endPoint.Should().BeOfType(); + endPoint.ToString().Should().Be("test"); } [Test] @@ -28,29 +28,29 @@ public void SocketIsNotNull() UdsTransport t = new("test"); // act - Socket result = t.Socket; + Socket socket = t.Socket; // assert - Assert.That(result, Is.Not.Null); + socket.Should().NotBeNull(); } [Test] public void CanSerialize() { // arrange - UdsTransport t = new("test"); + UdsTransport transport = new("test"); using MemoryStream typeStream = new MemoryStream(); using MemoryStream dataStream = new MemoryStream(); // act - Serializer.Write(t, typeStream, dataStream); + Serializer.Write(transport, typeStream, dataStream); typeStream.Seek(0, SeekOrigin.Begin); dataStream.Seek(0, SeekOrigin.Begin); - t = Serializer.Read(typeStream, dataStream); + transport = Serializer.Read(typeStream, dataStream); // assert - Assert.That(t, Is.Not.Null); - Assert.That(t.FilePath, Is.EqualTo("test")); + transport.Should().NotBeNull(); + transport.FilePath.Should().Be("test"); } } #endif