Skip to content

Commit 3da1cc0

Browse files
committed
test: 更新单元测试
1 parent 55e3fcf commit 3da1cc0

1 file changed

Lines changed: 56 additions & 1 deletion

File tree

test/UnitTestTcpSocket/TcpSocketFactoryTest.cs

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
1+
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33
// Website: https://www.blazor.zone or https://argozhang.github.io/
44

@@ -916,6 +916,61 @@ Task ReceivedEntityCallBack(MockEntity? entity)
916916
}
917917
}
918918

919+
[Fact]
920+
public async Task Convert_Ok()
921+
{
922+
var port = 8899;
923+
var server = StartTcpServer(port, MockSplitPackageAsync);
924+
925+
var client = CreateClient();
926+
var tcs = new TaskCompletionSource();
927+
var receivedBuffer = new byte[128];
928+
MockConverterEntity? entity = null;
929+
930+
// 连接 TCP Server
931+
var connect = await client.ConnectAsync("localhost", port);
932+
933+
client.SetDataPackageAdapter<MockConverterEntity>(new FixLengthDataPackageHandler(7), ReceivedCallBack);
934+
935+
var data = new ReadOnlyMemory<byte>([1, 2, 3, 4, 5]);
936+
await client.SendAsync(data);
937+
938+
// 等待接收数据处理完成
939+
await tcs.Task;
940+
941+
// 验证实体类不为空
942+
Assert.NotNull(entity);
943+
Assert.Equal("3.14", entity.Value1.ToString("#.##"));
944+
945+
Task ReceivedCallBack(MockConverterEntity? data)
946+
{
947+
entity = data;
948+
tcs.SetResult();
949+
return Task.CompletedTask;
950+
}
951+
}
952+
953+
[DataTypeConverter(Type = typeof(DataConverter<MockConverterEntity>))]
954+
class MockConverterEntity
955+
{
956+
[DataPropertyConverter(Type = typeof(byte[]), Offset = 0, Length = 5)]
957+
public byte[]? Header { get; set; }
958+
959+
[DataPropertyConverter(Type = typeof(byte[]), Offset = 5, Length = 2)]
960+
public byte[]? Body { get; set; }
961+
962+
[DataPropertyConverter(Type = typeof(float), Offset = 5, Length = 1, ConverterType = typeof(FloatConverter), ConverterParameters = [0.01f])]
963+
public float Value1 { get; set; }
964+
}
965+
966+
class FloatConverter(float rate) : IDataPropertyConverter
967+
{
968+
public object? Convert(ReadOnlyMemory<byte> data)
969+
{
970+
return (float)Math.Round(314 * rate, 2);
971+
}
972+
}
973+
919974
private static TcpListener StartTcpServer(int port, Func<TcpClient, Task> handler)
920975
{
921976
var server = new TcpListener(IPAddress.Loopback, port);

0 commit comments

Comments
 (0)