Skip to content

Commit

Permalink
fix(test): Command microservice freeze bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
asvol committed Dec 26, 2024
1 parent ad5d8ff commit 7c04074
Show file tree
Hide file tree
Showing 32 changed files with 112 additions and 126 deletions.
2 changes: 1 addition & 1 deletion src/Asv.Mavlink.Shell/CodeGen/Parsers/MavlinkParserXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private static MessageFieldType ParseFieldType(string typeString,out string type
case "double": return MessageFieldType.Double;
case "uint8_t_mavlink_version": return MessageFieldType.Uint8;
default:
throw new Exception($"Unknown type {typeString}");
throw new MavlinkException($"Unknown type {typeString}");

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public async Task Send_ManyPackets_Success(int packetsCount)
// Act
for (var i = 0; i < packetsCount; i++)
{
await Server.Send(payload => serverResults.Add(payload), default);
await Server.Send(payload => serverResults.Add(payload), CancellationToken.None);
}

// Assert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task ReadAllInfo_WhenCalled_ShouldSynchronizeServerAndClientCharts(
p => _taskCompletionSource.TrySetResult(p));

// Act
var sync = await Client.ReadAllInfo(default, _cancellationTokenSource.Token);
var sync = await Client.ReadAllInfo(null, _cancellationTokenSource.Token);
Assert.True(sync);

// Assert
Expand Down Expand Up @@ -104,7 +104,7 @@ public async Task RequestStream_WhenSingleRequest_ShouldReturnStreamAndUpdateCha
});

// Act
var sync = await Client.ReadAllInfo(default, _cancellationTokenSource.Token);
var sync = await Client.ReadAllInfo(null, _cancellationTokenSource.Token);

// Assert
Assert.True(sync);
Expand Down Expand Up @@ -190,7 +190,7 @@ public async Task RequestStream_WhenMultipleRequests_ShouldHandleAllAndUpdateCha
});

// Act
var sync = await Client.ReadAllInfo(default, _cancellationTokenSource.Token);
var sync = await Client.ReadAllInfo(null, _cancellationTokenSource.Token);

// Assert
Assert.True(sync);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task ReadAllInfo_ShouldThrowTimeout_Exception()
var attempts = 5;
var t1 = Assert.ThrowsAsync<TimeoutException>(async () =>
{
await Client.ReadAllInfo(default, _cancellationTokenSource.Token);
await Client.ReadAllInfo(null, _cancellationTokenSource.Token);
});

var t2 = Task.Factory.StartNew(() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public void CtorAsvChartInfo_ThrowsNullReferenceException_ArgIsNull()
[Fact]
public void CtorAsvChartAxisInfo_NullReferenceException_ArgIsNull()
{
Assert.Throws<Exception>(() =>
Assert.Throws<MavlinkException>(() =>
{
var axis = new AsvChartAxisInfo("", AsvChartUnitType.AsvChartUnitTypeDbm, 0f, 0f, 10);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public async Task Client_GetRecordTagListCancelWithToken_Fail()
{
var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(3));
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
await Client.GetRecordTagList(new Guid(), 0, ushort.MaxValue, cancel.Token));
await Client.GetRecordTagList(Guid.Empty, 0, ushort.MaxValue, cancel.Token));
}

[Fact]
Expand All @@ -85,7 +85,7 @@ public async Task Client_DeleteRecordTagCancelWithToken_Fail()
{
var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(3));
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
await Client.DeleteRecordTag(new TagId(new Guid(), new Guid()), cancel.Token));
await Client.DeleteRecordTag(new TagId(Guid.Empty, Guid.Empty), cancel.Token));
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,27 +665,20 @@ public async Task CommandInt_WaitBeforeResponse_Success()
var called = 0;
Link.SetServerToClientFilter(_ => false);
_server[MavCmd.MavCmdUser1] = (_, _, _)
=> Task.FromResult(
CommandResult.FromResult(
MavResult.MavResultInProgress
)
);
using var sub = Link.Client.OnTxMessage.Subscribe(p =>
=>
{
called++;
if (called == MaxCommandAttempts - 1)
if (called >= MaxCommandAttempts)
{
// before last attempt - enable link
// last attempt => enable link
Link.SetServerToClientFilter(_ => true);
}
if (called != MaxCommandAttempts)
{
ClientTime.Advance(TimeSpan.FromMilliseconds(MaxTimeoutInMs + 1));
return;
}


});
return CommandResult.InProgressTask;
};

// Act
var task = _client.CommandInt(
Expand Down Expand Up @@ -731,25 +724,21 @@ int maxTimeoutInMs
};
var client = new CommandClient(Identity, customCfg, ClientCore);

_server[MavCmd.MavCmdUser1] = (_, _, _)
=> Task.FromResult(
CommandResult.FromResult(
MavResult.MavResultInProgress
)
);

using var sub = Link.Client.OnTxMessage.Subscribe(p =>
_server[MavCmd.MavCmdUser1] = (_, _, _) =>
{
called++;

if (called != maxCommandAttempts)
if (called >= maxCommandAttempts)
{
// last attempt => enable link
Link.SetServerToClientFilter(_ => true);
}
else
{
ClientTime.Advance(TimeSpan.FromMilliseconds(maxTimeoutInMs + 1));
return;
}

Link.SetServerToClientFilter(_ => true);
});
return CommandResult.InProgressTask;
};


// Act
var task = client.CommandInt(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ public async Task CommandLong_WaitBeforeResponse_Success()
ClientTime.Advance(TimeSpan.FromMilliseconds((MaxCommandAttempts+1) * MaxTimeoutInMs));
}

return Task.FromResult(CommandResult.FromResult(MavResult.MavResultInProgress));
return CommandResult.InProgressTask;
};

// Act
Expand Down Expand Up @@ -603,7 +603,7 @@ public async Task CommandLong_TimeoutHappened_Throws()
5,
6,
7,
default
CancellationToken.None
);

// Assert
Expand Down Expand Up @@ -642,7 +642,7 @@ public async Task CommandLong_TimeoutWithCustomConfig_Throws(int maxCommandAttem
5,
6,
7,
default
CancellationToken.None
);

// Assert
Expand Down Expand Up @@ -673,16 +673,18 @@ int maxTimeoutInMs
{
called++;
Log.WriteLine($"confirmation______ === {args.Payload.Confirmation}");
if (called != maxCommandAttempts)
if (called >= maxCommandAttempts)
{
ClientTime.Advance(TimeSpan.FromMilliseconds(maxTimeoutInMs + 1));
// enable link for last attempt
Link.SetServerToClientFilter(_ => true);
}
else
{
Link.SetServerToClientFilter(_ => true);
// advance time for timeout
ClientTime.Advance(TimeSpan.FromMilliseconds(maxTimeoutInMs + 1));
}

return Task.FromResult(CommandResult.FromResult(MavResult.MavResultInProgress));
return CommandResult.InProgressTask;
};

// Act
Expand Down Expand Up @@ -731,13 +733,9 @@ int maxTimeoutInMs
called++;
var result = MavResult.MavResultAccepted;
_taskCompletionSource.TrySetResult(args);
return Task.FromResult(CommandResult.FromResult(result));
packetFromClient = args;
return CommandResult.AsTaskResult(result);
};
using var sub = Link.Client.OnTxMessage.Subscribe(p =>
{
packetFromClient = p as CommandLongPacket;
});

// Act
var result = await client.CommandLong(
MavCmd.MavCmdUser1,
Expand Down Expand Up @@ -773,22 +771,22 @@ public async Task CommandLong_ConfirmationValueIncreases_Success()
{
packetsFromServer.Add(args);
_taskCompletionSource.TrySetResult(args);

return Task.FromResult(CommandResult.FromResult(MavResult.MavResultAccepted));
};

using var sub = Link.Client.OnTxMessage.Subscribe(p =>
{
called++;

if (called != MaxCommandAttempts)
if (called >= MaxCommandAttempts)
{
ClientTime.Advance(TimeSpan.FromMilliseconds(MaxTimeoutInMs + 1));
return;
// enable link for last attempt
Link.SetServerToClientFilter(_ => true);
}
else
{
// advance time for timeout
ClientTime.Advance(TimeSpan.FromMilliseconds(MaxTimeoutInMs + 1));
}

Link.SetServerToClientFilter(_ => true);
});
return CommandResult.AcceptedTask;
};


// Act
var result = await _client.CommandLong(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;

using System.Threading;
using System.Threading.Tasks;
using Asv.Mavlink.Minimal;
using R3;
Expand Down Expand Up @@ -42,7 +42,7 @@ public async Task LinkQuality_Changed_Success(int packetCount, int skip, double
ComponentId = 4,
Sequence = seq.GetNextSequenceNumber(),
};
await Link.Server.Send(p, default);
await Link.Server.Send(p, CancellationToken.None);
for (var j = 0; j < skip; j++)
{
seq.GetNextSequenceNumber();
Expand Down Expand Up @@ -78,7 +78,7 @@ public async Task PacketRateHz_Changed_Success(int delayMs, int count)
ComponentId = 4,
Sequence = seq.GetNextSequenceNumber(),
};
await Link.Server.Send(p, default);
await Link.Server.Send(p, CancellationToken.None);
Time.Advance(TimeSpan.FromMilliseconds(delayMs));
}

Expand Down Expand Up @@ -107,7 +107,7 @@ public async Task RawPackets_Client_Catch_All_Packets_Success(int packets)
ComponentId = 4,
Sequence = seq.GetNextSequenceNumber(),
};
await Link.Server.Send(p, default);
await Link.Server.Send(p, CancellationToken.None);
Time.Advance(TimeSpan.FromMilliseconds(100));
}
Assert.Equal(packets,count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public async Task SetCurrent_DifferentMissionItemsIds_Success(ushort missionItem
[InlineData(2)]
[InlineData(10)]
[InlineData(400)]
[InlineData(90_000)]
[InlineData(ushort.MaxValue + 1)]
public async Task SetCurrent_SeveralCallsWithTheSameId_Success(int callsCount)
{
// Arrange
Expand Down Expand Up @@ -520,17 +520,17 @@ public async Task UploadAndStartMission_StrictSequenceExecuting_Success(ushort s
MavCmd.MavCmdUser3, // 8
};
var executed = new List<MavCmd>();
_server[MavCmd.MavCmdUser1] = (item, cancel) =>
_server[MavCmd.MavCmdUser1] = (item, _) =>
{
executed.Add(item.Command);
return Task.CompletedTask;
};
_server[MavCmd.MavCmdUser2] = (item, cancel) =>
_server[MavCmd.MavCmdUser2] = (item, _) =>
{
executed.Add(item.Command);
return Task.CompletedTask;
};
_server[MavCmd.MavCmdUser3] = (item, cancel) =>
_server[MavCmd.MavCmdUser3] = (item, _) =>
{
executed.Add(item.Command);
return Task.CompletedTask;
Expand All @@ -541,7 +541,7 @@ public async Task UploadAndStartMission_StrictSequenceExecuting_Success(ushort s
}
await _client.Upload(CancellationToken.None);
var tcs = new TaskCompletionSource();
_server.Reached.Subscribe(x =>
_client.Reached.Subscribe(x =>
{
if (x == (originMission.Count - 1))
{
Expand All @@ -550,10 +550,9 @@ public async Task UploadAndStartMission_StrictSequenceExecuting_Success(ushort s
});

// Act

_server.StartMission(skip);
await tcs.Task;

// Assert
Assert.Equal(originMission.Skip(skip),executed);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public async Task SendReached_DifferentSeq_Success(ushort seq)
});

// Act
await _server.SendReached(seq);
await _server.SendReached(seq, CancellationToken.None);

// Assert
var result = await _taskCompletionSource.Task as MissionItemReachedPacket;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public async Task ReadAll_ShouldThrowTimeout_Exception()
// Act
var t1 = Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
await Client.ReadAll(default, default, _cancellationTokenSource.Token);
await Client.ReadAll(null, false, _cancellationTokenSource.Token);
});

var t2 = Task.Factory.StartNew(() =>
Expand Down
2 changes: 1 addition & 1 deletion src/Asv.Mavlink/Microservices/AsvAudio/AudioDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private async void InternalSendEncodedAudio(ReadOnlyMemory<byte> encodedData)
byte packetIndex = 0;
var packetsInFrame = fullPackets + (lastPacketSize > 0 ? 1 : 0);
if (packetsInFrame == 0) return; // no data to send
if (packetsInFrame > byte.MaxValue) throw new Exception($"Too many packets in frame. Expected: less then {byte.MaxValue}, actual: {packetsInFrame}");
if (packetsInFrame > byte.MaxValue) throw new MavlinkException($"Too many packets in frame. Expected: less then {byte.MaxValue}, actual: {packetsInFrame}");
for (var i = 0; i < fullPackets; i++)
{
var index = packetIndex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,22 @@ public CompositeAudioCodecFactory(IEnumerable<IAudioCodecFactory> parts)
var codecs = _parts.GroupBy(x => x.AvailableCodecs).Where(x => x.Count() > 1).ToImmutableArray();
if (codecs.Any())
{
throw new Exception($"Codec {codecs.First().Key} duplicated");
throw new MavlinkException($"Codec {codecs.First().Key} duplicated");
}
}


public IAudioEncoder CreateEncoder(AsvAudioCodec codec, Observable<ReadOnlyMemory<byte>> input)
{
var result = _parts.FirstOrDefault(part => part.AvailableCodecs.Contains(codec))?.CreateEncoder(codec, input);
if (result == null) throw new Exception($"Codec {codec} not supported");
if (result == null) throw new MavlinkException($"Codec {codec} not supported");
return result;
}

public IAudioDecoder CreateDecoder(AsvAudioCodec codec, Observable<ReadOnlyMemory<byte>> input)
{
var result = _parts.FirstOrDefault(part => part.AvailableCodecs.Contains(codec))?.CreateDecoder(codec, input);
if (result == null) throw new Exception($"Codec {codec} not supported");
if (result == null) throw new MavlinkException($"Codec {codec} not supported");
return result;
}

Expand Down
Loading

0 comments on commit 7c04074

Please sign in to comment.