Skip to content

Use FluentAssertions #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions test/CLI.IPC.Test/CLI.IPC.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="FluentAssertions.Analyzers" Version="0.33.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.17">
Expand Down
7 changes: 5 additions & 2 deletions test/CLI.IPC.Test/ClientTest.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -19,7 +20,8 @@ public void AttachThrowsConnectionExceptionIfNoConnectionCanBeEstablished(int po
IHostConnectionHandler hostConnectionHandler = Substitute.For<IHostConnectionHandler>();

// act & assert
Assert.That(() => Client.Attach(transport, hostConnectionHandler), Throws.InstanceOf<ConnectionException>().With.Message.Contains("Could not connect"));
Action attach = () => Client.Attach(transport, hostConnectionHandler);
attach.Should().Throw<ConnectionException>().WithMessage("Could not connect*");
}

[Test]
Expand All @@ -33,6 +35,7 @@ public void AttachThrowsConnectionExceptionIfConnectionIsInterrupted()
ServiceProvider.MessageChannelFactory.CreateForOutgoing(transport).Returns(messageChannel);

// act & assert
Assert.That(() => Client.Attach(transport, hostConnectionHandler), Throws.InstanceOf<ConnectionException>().With.Message.Contains("There was an unexpected connection error"));
Action attach = () => Client.Attach(transport, hostConnectionHandler);
attach.Should().Throw<ConnectionException>().WithMessage("There was an unexpected connection error*");
}
}
26 changes: 12 additions & 14 deletions test/CLI.IPC.Test/DefaultHostConnectionHandlerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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
{
Expand All @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion test/CLI.IPC.Test/ExecutionTests/DynamicExecutionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TClientConnectionHandler, THostConnectionHandler>()
Expand Down
12 changes: 6 additions & 6 deletions test/CLI.IPC.Test/ExecutionTests/HostShutdownTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions test/CLI.IPC.Test/ExecutionTests/MultipleClientsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 9 additions & 9 deletions test/CLI.IPC.Test/ExecutionTests/SingletonTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
3 changes: 3 additions & 0 deletions test/CLI.IPC.Test/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
global using FluentAssertions;
global using FluentAssertions.Execution;
global using NSubstitute;
global using NUnit.Framework;
global using static FluentAssertions.FluentActions;
35 changes: 20 additions & 15 deletions test/CLI.IPC.Test/HostTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -66,18 +67,22 @@ public void TestHostInSameProcessAsClient(Func<ITransport> 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]
Expand All @@ -89,7 +94,7 @@ public void WaitUntilAllClientsDisconnectedThrowsInvalidOperationExceptionWhenCa
this.WaitForHostStartUp();

// act & assert
Assert.That(() => this.host.WaitUntilAllClientsDisconnected(), Throws.InvalidOperationException);
Invoking(() => this.host.WaitUntilAllClientsDisconnected()).Should().Throw<InvalidOperationException>();
}

[Test]
Expand All @@ -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<InvalidOperationException>();
}


Expand Down
10 changes: 5 additions & 5 deletions test/CLI.IPC.Test/Internal/DelegateTextWriterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -69,6 +69,6 @@ public void WriteStringNull()
this.writer.Write((string?)null);

// assert
Assert.That(this.writtenStrings, Is.Empty);
this.writtenStrings.Should().BeEmpty();
}
}
12 changes: 6 additions & 6 deletions test/CLI.IPC.Test/Internal/DisposableTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,29 @@ 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();
disposable.Dispose();
disposable.Dispose();

// assert
Assert.That(i, Is.EqualTo(1));
callCount.Should().Be(1);
}
}
Loading