Skip to content

Commit

Permalink
fix(test): fixed tests with FakeTimeProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
asvol committed Dec 19, 2024
1 parent 5a6ab0d commit 833f262
Show file tree
Hide file tree
Showing 17 changed files with 164 additions and 157 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,21 @@ public void Ctor_ThrowsExceptions_ArgIsNullFail()
{
Assert.Throws<ArgumentNullException>(() =>
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
var client = new AdsbVehicleClient(null, _config, Context);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
});
Assert.Throws<ArgumentNullException>(() =>
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
var client = new AdsbVehicleClient(Identity, _config, null);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
});
Assert.Throws<NullReferenceException>(() =>
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
var client = new AdsbVehicleClient(Identity, null, Context);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class AsvChartServerTest : ServerTestBase<AsvChartServer>, IDisposable

private readonly AsvChartServerConfig _config = new()
{
SendSignalDelayMs = 30,
SendSignalDelayMs = 0, // ! Important
SendCollectionUpdateMs = 100,
};

Expand Down Expand Up @@ -96,9 +96,6 @@ await Assert.ThrowsAsync<ArgumentException>(async () =>
public async Task Send_SendManyPacket_Success(int packetsCount)
{
// Arrange
var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(15));
cancel.Token.Register(() => _taskCompletionSource.TrySetCanceled());

var count = 0;
var info = new AsvChartInfo(1, "TestChart",
new AsvChartAxisInfo("X", AsvChartUnitType.AsvChartUnitTypeDbm, 0, 10, 10),
Expand All @@ -114,7 +111,7 @@ public async Task Send_SendManyPacket_Success(int packetsCount)
// Act
for (var i = 0; i < packetsCount; i++)
{
await Server.Send(DateTime.Now, data, info, cancel.Token);
await Server.Send(DateTime.Now, data, info);
}

// Assert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@
namespace Asv.Mavlink.Test;

[TestSubject(typeof(AsvSdrClientEx))]
public class AsvSdrClientExTest() : ClientTestBase<AsvSdrClientEx>(_log)
public class AsvSdrClientExTest(ITestOutputHelper log) : ClientTestBase<AsvSdrClientEx>(log)
{
private static ITestOutputHelper _log = new TestOutputHelper();

private readonly HeartbeatClientConfig _configHeartbeat = new()
{
HeartbeatTimeoutMs = 2000,
Expand Down Expand Up @@ -53,17 +51,32 @@ public async Task Client_DeleteRecordCancelWithToken_Fail()
{
var recordId = Guid.NewGuid();
var cancel = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
var t1 = Assert.ThrowsAsync<TimeoutException>(async () =>
await Client.DeleteRecord(recordId, cancel.Token));
var t2 = Task.Factory.StartNew(() =>
{
while (t1.IsCompleted == false)
{
Time.Advance(TimeSpan.FromMilliseconds(_commandConfig.CommandTimeoutMs));
}
}, cancel.Token);

await Task.WhenAll(t1, t2);
}

[Fact]
public async Task Client_StartRecordCancelWithToken_Fail()
{
var recordName = "Test_Record";
var cancel = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
var t1 = Assert.ThrowsAsync<TimeoutException>(async () =>
await Client.StartRecord(recordName, cancel.Token));
var t2 = Task.Factory.StartNew(() =>
{
Time.Advance(TimeSpan.FromMilliseconds(_commandConfig.CommandTimeoutMs * _commandConfig.CommandAttempt + 100));
}, cancel.Token);

await Task.WhenAll(t1, t2);
}

[Fact]
Expand All @@ -72,9 +85,21 @@ public async Task Client_OnRecordTagCancelWithToken_Fail()
var tagName = "tag";
var rawValue = new byte[] { 1, 0, 0, 1, 0, 0, 1, 0 };
var cancel = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(async () =>

var t1 = Assert.ThrowsAsync<TimeoutException>(async () =>
await Client.CurrentRecordSetTag(tagName, AsvSdrRecordTagType.AsvSdrRecordTagTypeInt64,
rawValue, cancel.Token));

var t2 = Task.Factory.StartNew(() =>
{
while (t1.IsCompleted == false)
{
Time.Advance(TimeSpan.FromMilliseconds(_commandConfig.CommandTimeoutMs * _commandConfig.CommandAttempt + 100));
}

}, TaskCreationOptions.LongRunning);

await Task.WhenAll(t1, t2);
}
[Fact]
public async Task Client_OnRecordTagExcptWithBadValues_Fail()
Expand Down Expand Up @@ -106,25 +131,9 @@ public void Client_CtorArgumentNull_Fail()
var identity = new MavlinkClientIdentity(1, 2, 3, 4);
var heartBeat = new HeartbeatClient(identity, _configHeartbeat, Context);
var command = new CommandClient(identity, _commandConfig, Context);
Assert.ThrowsAsync<ArgumentNullException>(() =>
{
var test = new AsvSdrClientEx(null, heartBeat, command, new AsvSdrClientExConfig());
return Task.CompletedTask;
});
Assert.ThrowsAsync<ArgumentNullException>(() =>
{
var test = new AsvSdrClientEx(Client.Base, null, command, new AsvSdrClientExConfig());
return Task.CompletedTask;
});
Assert.ThrowsAsync<ArgumentNullException>(() =>
{
var test = new AsvSdrClientEx(Client.Base, heartBeat, null, new AsvSdrClientExConfig());
return Task.CompletedTask;
});
Assert.ThrowsAsync<ArgumentNullException>(() =>
{
var test = new AsvSdrClientEx(Client.Base, heartBeat, command, null);
return Task.CompletedTask;
});
Assert.Throws<NullReferenceException>(() => new AsvSdrClientEx(null, heartBeat, command, new AsvSdrClientExConfig()));
Assert.Throws<NullReferenceException>(() => new AsvSdrClientEx(Client.Base, null, command, new AsvSdrClientExConfig()));
Assert.Throws<ArgumentNullException>(() => new AsvSdrClientEx(Client.Base, heartBeat, null, new AsvSdrClientExConfig()));
Assert.Throws<ArgumentNullException>(() => new AsvSdrClientEx(Client.Base, heartBeat, command, null));
}
}
19 changes: 15 additions & 4 deletions src/Asv.Mavlink.Test/Microservices/Params/ParamsComplexTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public ParamsComplexTest(ITestOutputHelper log) : base(log)

private readonly ParamsServerExConfig _serverExConfig = new()
{
SendingParamItemDelayMs = 100,
SendingParamItemDelayMs = 0,
CfgPrefix = "MAV_CFG_",
};

Expand Down Expand Up @@ -192,10 +192,12 @@ public async Task ReadAll_ClientShouldReadAllParamsFromServer_Success()
{
called++;
param.Add(p);
ClientTime.Advance(TimeSpan.FromMilliseconds(_clientConfig.ReadTimeouMs));
if (called == _serverEx.AllParamsList.Count)
{
_taskCompletionSource.TrySetResult(p);
}

});

// Act
Expand All @@ -216,13 +218,22 @@ public async Task ReadAll_ClientShouldReadAllParamsFromServer_Success()
public async Task ReadAll_ClientShouldSyncLocalAndRemoteCounts_Success()
{
// Arrange
using var sub = _client.Base.OnParamValue.Subscribe(p => _taskCompletionSource.TrySetResult(p));
var server = Server;
server.Start();

// Act
await _client.ReadAll(null, false, _cancellationTokenSource.Token);
var t1 = _client.ReadAll(null, false, _cancellationTokenSource.Token);
var t2 = Task.Factory.StartNew(() =>
{
// this is for chunk update
while (t1.IsCompleted == false)
{
ClientTime.Advance(TimeSpan.FromMilliseconds(_clientConfig.ReadTimeouMs));
}
});

await Task.WhenAll(t1, t2);
// Assert
await _taskCompletionSource.Task;
Assert.Equal(_serverEx.AllParamsList.Count, _client.LocalCount.CurrentValue);
Assert.Equal(_serverEx.AllParamsList.Count, _client.RemoteCount.CurrentValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public void Constructor_Null_Throws()
{
// Act
Assert.Throws<NullReferenceException>(() => new ParamsExtClientEx(null!, _config, ParamDescription));
Assert.Throws<ArgumentNullException>(() => new ParamsExtClientEx(_client, null!, ParamDescription));
Assert.Throws<ArgumentNullException>(() => new ParamsExtClientEx(_client, _config, null!));
Assert.Throws<NullReferenceException>(() => new ParamsExtClientEx(_client, null!, ParamDescription));
Assert.Throws<NullReferenceException>(() => new ParamsExtClientEx(_client, _config, null!));
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public ParamsExtComplexTest(ITestOutputHelper log) : base(log)

private readonly ParamsExtClientExConfig _clientExConfig = new()
{
ChunkUpdateBufferMs = 100,
ChunkUpdateBufferMs = 0,
};

private readonly StatusTextLoggerConfig _statusTextServerConfig = new()
Expand All @@ -47,7 +47,7 @@ public ParamsExtComplexTest(ITestOutputHelper log) : base(log)

private readonly ParamsExtServerExConfig _serverExConfig = new()
{
SendingParamItemDelayMs = 100,
SendingParamItemDelayMs = 0,
CfgPrefix = "MAV_CFG_",
};

Expand Down Expand Up @@ -274,6 +274,7 @@ public async Task ReadAll_ClientShouldReadAllParamsFromServer_Success()
param.Add(p);
if (param.Count == p.ParamCount)
_taskCompletionSource.TrySetResult(p);
ClientTime.Advance(TimeSpan.FromMilliseconds(_serverExConfig.SendingParamItemDelayMs));
});

// Act
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,7 @@ public async Task QTakeOff_SingleCall_Success(float altInMeters)
// Arrange
var called = 0;
IProtocolMessage? packetFromClient = null;
var tcs2 = new TaskCompletionSource();
_server[MavCmd.MavCmdNavVtolTakeoff] = (id, args, cancel) =>
{
called++;
Expand All @@ -707,13 +708,15 @@ public async Task QTakeOff_SingleCall_Success(float altInMeters)
using var sub = Link.Server.OnTxMessage.Cast<IProtocolMessage,MavlinkMessage>().Subscribe(p =>
{
packetFromClient = p as CommandAckPacket;
tcs2.TrySetResult();
});

// Act
await _client.QTakeOff(altInMeters, _cancellationTokenSource.Token);

// Assert
var packetFromServer = await _taskCompletionSource.Task as CommandLongPacket;
var packetFromServer = (await _taskCompletionSource.Task) as CommandLongPacket;
await tcs2.Task;
Assert.Equal(1, called);
Assert.Equal(called, (int)Link.Client.Statistic.TxMessages);
Assert.Equal((int)Link.Client.Statistic.TxMessages, (int)Link.Server.Statistic.RxMessages);
Expand Down Expand Up @@ -911,20 +914,12 @@ public async Task GetHomePosition_Timeout_Throws()
[Fact]
public async Task GetHomePosition_Unsupported_MavResultUnsupported()
{
// Arrange
var result = MavResult.MavResultAccepted;
using var sub = Link.Client
.OnRxMessage.RxFilterByType<CommandAckPacket>()
.Subscribe(p =>
{
result = p.Payload.Result;
});

// Act
await _client.GetHomePosition(_cancellationTokenSource.Token);
var t = _client.GetHomePosition(_cancellationTokenSource.Token);

// Assert
Assert.Equal(MavResult.MavResultUnsupported, result);

await Assert.ThrowsAsync<CommandException>(async () => await t);
Assert.Equal((int)Link.Client.Statistic.TxMessages, (int)Link.Server.Statistic.RxMessages);
Assert.Equal(1, (int)Link.Server.Statistic.TxMessages);
Assert.Equal((int)Link.Server.Statistic.TxMessages, (int)Link.Client.Statistic.RxMessages);
Expand Down Expand Up @@ -1051,53 +1046,53 @@ public async Task QLand_Cancel_Throws()
Assert.Equal((int)Link.Server.Statistic.TxMessages, (int)Link.Client.Statistic.RxMessages);
}

[Fact(Skip = "Test is not relevant")]
[Fact]
public async Task QLand_Timeout_Throws()
{
// Arrange
using var sub = Link.Server.OnTxMessage.Cast<IProtocolMessage,MavlinkMessage>().Subscribe(p =>
{
ClientTime.Advance(
TimeSpan.FromMilliseconds(
_commandConfig.CommandTimeoutMs *
_commandConfig.CommandAttempt *
2
)
);
});
Link.SetClientToServerFilter(x=>false);



// Act
var task = _client.QLand(
NavVtolLandOptions.NavVtolLandOptionsDefault,
10,
_cancellationTokenSource.Token
);
var t2 = Task.Factory.StartNew(() =>
{
while (task.IsCompleted == false)
{
ClientTime.Advance(
TimeSpan.FromMilliseconds(
_commandConfig.CommandTimeoutMs *
_commandConfig.CommandAttempt *
2
)
);
}

}, TaskCreationOptions.LongRunning);

// Assert
await Assert.ThrowsAsync<TimeoutException>(async () => await task);
await Assert.ThrowsAsync<TimeoutException>(async () =>
{
await Task.WhenAll(task, t2);
});
}

[Fact]
public async Task QLand_Unsupported_MavResultUnsupported()
{
// Arrange
var result = MavResult.MavResultAccepted;
using var sub = Link.Client
.OnRxMessage.RxFilterByType<CommandAckPacket>()
.Subscribe(p =>
{
result = p.Payload.Result;
});

// Act
await _client.QLand(
var t = _client.QLand(
NavVtolLandOptions.NavVtolLandOptionsDefault,
10,
_cancellationTokenSource.Token
);

// Assert
Assert.Equal(MavResult.MavResultUnsupported, result);
await Assert.ThrowsAsync<CommandException>(async () => await t);
Assert.Equal((int)Link.Client.Statistic.TxMessages, (int)Link.Server.Statistic.RxMessages);
Assert.Equal(1, (int)Link.Server.Statistic.TxMessages);
Assert.Equal((int)Link.Server.Statistic.TxMessages, (int)Link.Client.Statistic.RxMessages);
Expand Down
4 changes: 4 additions & 0 deletions src/Asv.Mavlink.Test/Tools/ListDataFile/ListDataFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ public void Ctor_Null_Reference_Fail()
using var strm = new MemoryStream();
Assert.Throws<ArgumentNullException>(() =>
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
using var file = new ListDataFile<AsvSdrRecordFileMetadata>(null, FileFormat1, false, _fileSystem);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
});
Assert.Throws<ArgumentNullException>(() =>
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
using var file = new ListDataFile<AsvSdrRecordFileMetadata>(new MemoryStream(), null, false, _fileSystem);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ await InternalSend<AsvChartDataPacket>(pkt =>
pkt.Payload.ChatInfoHash = info.InfoHash;
}, cancel).ConfigureAwait(false);
if (_config.SendSignalDelayMs > 0)
await Task.Delay(_config.SendSignalDelayMs, cancel).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromMilliseconds(_config.SendSignalDelayMs), Context.TimeProvider, cancel).ConfigureAwait(false);
}
if (lastPacketSize > 0)
{
Expand All @@ -132,7 +132,7 @@ await InternalSend<AsvChartDataPacket>(pkt =>
pkt.Payload.ChatInfoHash = info.InfoHash;
}, cancel).ConfigureAwait(false);
if (_config.SendSignalDelayMs > 0)
await Task.Delay(_config.SendSignalDelayMs, cancel).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromMilliseconds(_config.SendSignalDelayMs), Context.TimeProvider, cancel).ConfigureAwait(false);
}
}

Expand Down
Loading

0 comments on commit 833f262

Please sign in to comment.