Files
StockSharp/Tests/OfflineMessageAdapterTests.cs
mika@stocksharp.com 6e7a7dae22 Move instrument lookups and persistence to async
Instrument lookups, configuration, credentials, CSV entities, snapshots and
the alert processing service are read and written asynchronously; the
blocking synchronous forms are obsolete wrappers.

IAsyncPersistable replaces IPersistable: every type that saves and loads its
settings has LoadAsync and SaveAsync only, and nested objects are read with
GetValueAsync, LoadEntireAsync and LoadAllAsync. The synchronous Load and Save
are the obsolete Ecng extensions. The MultiConnect sample keeps IPersistable
for two settings classes, because the settings window of the published
StockSharp.Xaml package takes it.

Copies that were made by saving and loading are made asynchronously.
IMessageAdapter, IIndicator, the risk, commission, PnL, latency, slippage and
position managers, IStorageBuffer, Strategy, DiagramElement, ICompositionModel
and its nodes get CloneAsync and no longer implement ICloneable; Clone is an
obsolete blocking wrapper. A strategy copy keeps every security and portfolio
parameter the original holds. Messages, FieldMapping, BankDetails and
WithdrawInfo are copied in memory. A CommissionRuleMessage shares its rule and
the emulator takes a copy of it. Envelope gets a constructor that takes all
three lines and CreateAsync.

ToBruteForce and ToBruteForceRandom become ToBruteForceAsync and
ToBruteForceRandomAsync and return IAsyncEnumerable; BruteForceOptimizer runs
over it and takes the next strategy through an asynchronous delegate.

Diagram elements keep their own state in SaveState, OnLoading and LoadState.
Undo restores an in-memory snapshot; a chart element holds its series and
axes in it by reference. An alert rule keeps its value in the form a message
carries it. A diagram strategy applies composition settings that were loaded
before the composition was set in SetCompositionAsync or at the start, and
saves them while they wait.

Strategies get an OnStartedAsync hook; diagram strategies resolve securities,
underlyings and strikes before the start so value processing never looks up
instruments. Paths.Serialize, SerializeInvariant, AppStartSettings.TrySave,
ICredentialsProvider.Save, ISnapshotSerializer.Serialize and the composition
registry gain async forms.

ICredentialsProvider.Delete becomes DeleteAsync, so loading, saving and
deleting the credentials wait for one another. Paths.InstalledVersion and
AppNameWithVersion are obsolete in favour of GetInstalledVersionAsync and
GetAppNameWithVersionAsync.

A file is opened for writing only after the last cancellation check, because
opening it empties it; a cancelled read reports the cancellation instead of
an empty result. A snapshot flush that failed leaves what it took due for the
next one.

The indicator templates for C#, F# and Python override LoadAsync and
SaveAsync.
2026-10-04 11:28:17 +03:00

339 lines
9.5 KiB
C#

namespace StockSharp.Tests;
[TestClass]
public class OfflineMessageAdapterTests : BaseTestClass
{
[TestMethod]
public async Task SendInMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
var toInner = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
};
var toOut = new SubscriptionResponseMessage { OriginalTransactionId = 1 };
manager
.Setup(m => m.ProcessInMessage(It.IsAny<Message>()))
.Returns((toInner: (Message[])[toInner], toOut: (Message[])[toOut], shouldForward: false));
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ResetMessage(), CancellationToken);
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertSame(toInner);
output.Count.AssertEqual(1);
output[0].AssertSame(toOut);
manager.Verify(m => m.ProcessInMessage(It.IsAny<Message>()), Times.Once);
}
[TestMethod]
public async Task SendInMessage_ShouldForward_ForwardsOriginalMessage()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
manager
.Setup(m => m.ProcessInMessage(It.IsAny<Message>()))
.Returns((toInner: (Message[])[], toOut: (Message[])[], shouldForward: true));
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
var connectMsg = new ConnectMessage();
await adapter.SendInMessageAsync(connectMsg, CancellationToken);
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertSame(connectMsg);
}
[TestMethod]
public async Task SendInMessage_MultipleToInner_SendsAll()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
var msg1 = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
};
var msg2 = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 2,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.OrderLog,
};
manager
.Setup(m => m.ProcessInMessage(It.IsAny<Message>()))
.Returns((toInner: (Message[])[msg1, msg2], toOut: (Message[])[], shouldForward: false));
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
await adapter.SendInMessageAsync(new ProcessSuspendedMessage(), CancellationToken);
inner.InMessages.Count.AssertEqual(2);
inner.InMessages[0].AssertSame(msg1);
inner.InMessages[1].AssertSame(msg2);
}
[TestMethod]
public async Task InnerMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
var extra = new ProcessSuspendedMessage();
manager
.Setup(m => m.ProcessOutMessage(It.IsAny<Message>()))
.Returns((suppressOriginal: false, extraOut: (Message[])[extra]));
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var connectMsg = new ConnectMessage();
await inner.SendOutMessageAsync(connectMsg, CancellationToken);
// Original message + extra message
output.Count.AssertEqual(2);
output[0].AssertSame(connectMsg);
output[1].AssertSame(extra);
manager.Verify(m => m.ProcessOutMessage(It.IsAny<Message>()), Times.Once);
}
[TestMethod]
public async Task InnerMessage_SuppressOriginal_DoesNotForwardOriginal()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
manager
.Setup(m => m.ProcessOutMessage(It.IsAny<Message>()))
.Returns((suppressOriginal: true, extraOut: (Message[])[]));
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await inner.SendOutMessageAsync(new ConnectionLostMessage { IsResetState = true }, CancellationToken);
output.Count.AssertEqual(0);
}
[TestMethod]
public void MaxMessageCount_DelegatesToManager()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<IOfflineManager>();
manager.SetupProperty(m => m.MaxMessageCount, 10000);
using var adapter = new OfflineMessageAdapter(inner, manager.Object);
adapter.MaxMessageCount.AssertEqual(10000);
adapter.MaxMessageCount = 5000;
manager.VerifySet(m => m.MaxMessageCount = 5000, Times.Once);
}
[TestMethod]
public async Task FullWorkflow_StoreAndReplay()
{
var inner = new RecordingMessageAdapter();
using var adapter = new OfflineMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var secId = Helper.CreateSecurityId();
// Send subscription while offline
var subscription = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 100,
SecurityId = secId,
DataType2 = DataType.Ticks,
};
await adapter.SendInMessageAsync(subscription, CancellationToken);
// Message should not be forwarded (stored in offline)
inner.InMessages.Count.AssertEqual(0);
// Simulate connection success
await inner.SendOutMessageAsync(new ConnectMessage(), CancellationToken);
// Should receive connect message and ProcessSuspended
output.Count(m => m.Type == MessageTypes.Connect).AssertEqual(1);
output.Count(m => m.Type == MessageTypes.ProcessSuspended).AssertEqual(1);
// Clear for next check
output.Clear();
inner.InMessages.Clear();
// Now process the suspended message that was sent back
var processSuspended = new ProcessSuspendedMessage(adapter);
await adapter.SendInMessageAsync(processSuspended, CancellationToken);
// Now the stored subscription should be forwarded
inner.InMessages.Count.AssertEqual(1);
var forwarded = (MarketDataMessage)inner.InMessages[0];
forwarded.SecurityId.AssertEqual(secId);
}
[TestMethod]
public async Task OrderCancel_WhileOffline_PendingOrder_ReturnsExecutionMessage()
{
var inner = new RecordingMessageAdapter();
using var adapter = new OfflineMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
// Register order while offline
var orderMsg = new OrderRegisterMessage
{
TransactionId = 100,
SecurityId = Helper.CreateSecurityId(),
Side = Sides.Buy,
Price = 100m,
Volume = 10,
OrderType = OrderTypes.Limit,
};
await adapter.SendInMessageAsync(orderMsg, CancellationToken);
// Cancel order while still offline
var cancelMsg = new OrderCancelMessage
{
TransactionId = 101,
OriginalTransactionId = 100,
};
await adapter.SendInMessageAsync(cancelMsg, CancellationToken);
// Should receive an ExecutionMessage indicating cancellation
output.Count.AssertEqual(1);
var execMsg = (ExecutionMessage)output[0];
execMsg.OriginalTransactionId.AssertEqual(101);
execMsg.OrderState.AssertEqual(OrderStates.Done);
}
[TestMethod]
public async Task OrderReplace_WhileOffline_PendingOrder_ReturnsExecutionMessage()
{
var inner = new RecordingMessageAdapter();
using var adapter = new OfflineMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
// Register order while offline
var orderMsg = new OrderRegisterMessage
{
TransactionId = 100,
SecurityId = Helper.CreateSecurityId(),
Side = Sides.Buy,
Price = 100m,
Volume = 10,
OrderType = OrderTypes.Limit,
};
await adapter.SendInMessageAsync(orderMsg, CancellationToken);
// Replace order while still offline
var replaceMsg = new OrderReplaceMessage
{
TransactionId = 201,
OriginalTransactionId = 100,
Price = 105m,
Volume = 10,
};
await adapter.SendInMessageAsync(replaceMsg, CancellationToken);
// Should receive an ExecutionMessage indicating old order is Done
output.Count.AssertEqual(1);
var execMsg = (ExecutionMessage)output[0];
execMsg.OrderState.AssertEqual(OrderStates.Done);
execMsg.OriginalTransactionId.AssertEqual(orderMsg.TransactionId);
inner.InMessages.Count.AssertEqual(0);
await inner.SendOutMessageAsync(new ConnectMessage(), CancellationToken);
await adapter.SendInMessageAsync(new ProcessSuspendedMessage(adapter), CancellationToken);
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertOfType<OrderRegisterMessage>();
var replayed = (OrderRegisterMessage)inner.InMessages[0];
replayed.TransactionId.AssertEqual(replaceMsg.TransactionId);
replayed.Price.AssertEqual(replaceMsg.Price);
}
[TestMethod]
public async Task Clone_CreatesNewAdapter()
{
var inner = new RecordingMessageAdapter();
using var adapter = new OfflineMessageAdapter(inner);
var cloned = await adapter.CloneAsync(CancellationToken);
cloned.AssertNotNull();
cloned.AssertNotSame(adapter);
(cloned is OfflineMessageAdapter).AssertTrue();
}
[TestMethod]
public void Constructor_NullManager_Throws()
{
var inner = new RecordingMessageAdapter();
var thrown = false;
try
{
new OfflineMessageAdapter(inner, null);
}
catch (ArgumentNullException)
{
thrown = true;
}
thrown.AssertTrue();
}
}