Files
2026-07-14 19:00:35 +03:00

76 lines
2.8 KiB
C#

// <copyright file="ConnectionTests.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.Network.Tests;
using System.IO.Pipelines;
using Microsoft.Extensions.Logging.Abstractions;
/// <summary>
/// Tests for <see cref="Connection"/>.
/// </summary>
[TestFixture]
public class ConnectionTests
{
/// <summary>
/// Tests if the connection is disconnected after a malformed packet was received.
/// </summary>
/// <returns>The async task.</returns>
[Test]
public async Task DisconnectedByMalformedPacketReceivedAsync()
{
var malformedData = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
var duplexPipe = new DuplexPipe();
using var connection = new Connection(duplexPipe, null, null, new NullLogger<Connection>());
var disconnected = false;
connection.Disconnected += async () => disconnected = true;
_ = connection.BeginReceiveAsync();
try
{
await duplexPipe.ReceivePipe.Writer.WriteAsync(malformedData).ConfigureAwait(false);
}
catch
{
// we need to swallow the exception for this test, so we can check the connected flag afterwards.
}
for (int i = 0; i < 10 && !disconnected; i++)
{
await Task.Delay(10).ConfigureAwait(false);
}
Assert.That(connection.Connected, Is.False);
}
/// <summary>
/// Tests if the reader (e.g. SocketConnection) gets an exception when it reads a malformed packet which leads to an exception.
/// The consumer (e.g. SocketConnection) will take care to call <see cref="PipeReader.Complete"/> or <see cref="PipeReader.CompleteAsync"/>.
/// </summary>
/// <returns>The async task.</returns>
[Test]
public async Task ExceptionWhenFailingToEncryptSentPacketAsync()
{
var malformedData = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
var duplexPipe = new DuplexPipe();
using var connection = new Connection(duplexPipe, null, new Xor.PipelinedXor32Encryptor(duplexPipe.Output), new NullLogger<Connection>());
_ = connection.BeginReceiveAsync();
await connection.Output.WriteAsync(malformedData).ConfigureAwait(false);
Assert.That(
async () => await duplexPipe.SendPipe.Reader.ReadAsync().ConfigureAwait(false),
Throws.TypeOf<InvalidPacketHeaderException>());
}
/// <summary>
/// Tests if the connection is initially connected.
/// </summary>
[Test]
public void InitiallyConnected()
{
var duplexPipe = new DuplexPipe();
using var connection = new Connection(duplexPipe, null, null, new NullLogger<Connection>());
Assert.That(connection.Connected, Is.True);
}
}