feat: 添加单元测试

This commit is contained in:
zerlei 2024-09-22 16:12:30 +08:00
parent 9c9ffdd77e
commit 002a99589b
3 changed files with 97 additions and 8 deletions

View file

@ -2,7 +2,6 @@ using System.Security.Cryptography;
namespace Common;
/// <summary>
/// 与目标服务器通信将会加密
/// </summary>
@ -55,7 +54,7 @@ public class AESHelper
0xB6,
];
public static byte[] EncryptStringToBytes_Aes(string plainText)
public static byte[] EncryptStringToBytes_Aes(byte[] plainText)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
@ -74,11 +73,7 @@ public class AESHelper
// Create the streams used for encryption.
using MemoryStream msEncrypt = new();
using CryptoStream csEncrypt = new(
msEncrypt,
encryptor,
CryptoStreamMode.Write
);
using CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write);
using (StreamWriter swEncrypt = new(csEncrypt))
{
//Write all data to the stream.

View file

@ -126,7 +126,7 @@ public class WebSocPipeLine<TSocket>(TSocket socket, bool isAES) : AbsPipeLine(i
string msgStr = JsonSerializer.Serialize(msg);
await Socket.SendAsync(
IsAES
? AESHelper.EncryptStringToBytes_Aes(msgStr)
? AESHelper.EncryptStringToBytes_Aes(Encoding.UTF8.GetBytes(msgStr))
: new ArraySegment<byte>(Encoding.UTF8.GetBytes(msgStr)),
WebSocketMessageType.Text,
true,

View file

@ -0,0 +1,94 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Common;
namespace ServerTest
{
public class TestPipe(bool isAES) : AbsPipeLine(isAES)
{
private readonly BlockingCollection<Func<byte[]>> EventQueue =
new BlockingCollection<Func<byte[]>>();
private readonly CancellationTokenSource Cts = new CancellationTokenSource();
public TestPipe? Other;
public override async IAsyncEnumerable<int> Work(
Func<byte[], bool> receiveCb,
string addr = ""
)
{
yield return 0;
await Listen(receiveCb);
yield return 1;
}
public override async Task UploadFile(
string filePath,
string dst,
Func<double, bool> progressCb
)
{
await Task.Run(() =>
{
progressCb(100);
System.IO.File.Copy(filePath, dst, true);
});
}
public override async Task Close(string? CloseReason)
{
await Task.Run(() =>
{
Cts.Cancel();
});
}
public new async Task ReceiveMsg(SyncMsg msg)
{
await Task.Run(() =>
{
EventQueue.Add(() =>
{
var r = JsonSerializer.SerializeToUtf8Bytes(msg);
if (IsAES)
{
return AESHelper.EncryptStringToBytes_Aes(r);
}
else
{
return r;
}
});
});
}
public override async Task SendMsg(SyncMsg msg)
{
if (Other == null)
{
throw new Exception("can't be null");
}
await Other.ReceiveMsg(msg);
}
protected override async Task Listen(Func<byte[], bool> receiveCb)
{
while (!Cts.Token.IsCancellationRequested)
{
Func<byte[]> eventTask = EventQueue.Take(Cts.Token);
if (eventTask != null)
{
await Task.Run(() =>
{
var r = eventTask();
receiveCb(r);
});
}
}
}
}
}