//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Network.Tests;
using System.IO.Pipelines;
using Microsoft.Extensions.Logging.Abstractions;
///
/// Tests for .
///
[TestFixture]
public class ConnectionTests
{
///
/// Tests if the connection is disconnected after a malformed packet was received.
///
/// The async task.
[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());
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);
}
///
/// 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 or .
///
/// The async task.
[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.BeginReceiveAsync();
await connection.Output.WriteAsync(malformedData).ConfigureAwait(false);
Assert.That(
async () => await duplexPipe.SendPipe.Reader.ReadAsync().ConfigureAwait(false),
Throws.TypeOf());
}
///
/// Tests if the connection is initially connected.
///
[Test]
public void InitiallyConnected()
{
var duplexPipe = new DuplexPipe();
using var connection = new Connection(duplexPipe, null, null, new NullLogger());
Assert.That(connection.Connected, Is.True);
}
}