94 lines
3.4 KiB
C#
94 lines
3.4 KiB
C#
using PLCSharp.Models;
|
|
using PLCSharp.VVMs.Workflows;
|
|
using Prism.Container.DryIoc;
|
|
using Prism.Ioc;
|
|
using System.IO;
|
|
|
|
namespace PLCSharp.Tests;
|
|
|
|
public class WorkflowRegressionTests
|
|
{
|
|
private static readonly Lazy<bool> Compiler = new(() =>
|
|
{
|
|
NatashaManagement.GetInitializer().WithMemoryUsing().WithMemoryReference()
|
|
.Preheating<NatashaDomainCreator>();
|
|
return true;
|
|
});
|
|
|
|
private static Workflow Compile(string members)
|
|
{
|
|
_ = Compiler.Value;
|
|
var flow = new Workflow { CompiledTime = DateTime.MinValue };
|
|
flow.Code = $"public class Extension_{flow.ID:N} {{ {members} }}";
|
|
flow.Compile.Execute();
|
|
return flow;
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task RecipeChangeWaitsForInFlightScriptAsync(bool automatic)
|
|
{
|
|
var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.db");
|
|
try
|
|
{
|
|
using var db = new DatasContext(path);
|
|
IContainerExtension container = new DryIocContainerExtension();
|
|
container.RegisterInstance(db);
|
|
var model = new WorkflowsModel(container, null!, null!);
|
|
var flow = Compile("""
|
|
public static System.Threading.ManualResetEventSlim Release;
|
|
public void Run(PLCSharp.Models.GlobalModel model, PLCSharp.Core.Common.FlowModel flow)
|
|
{
|
|
flow.Step++;
|
|
Release.Wait();
|
|
flow.Completed = true;
|
|
}
|
|
""");
|
|
Assert.True(flow.IsCompiled, flow.DebugLog);
|
|
using var release = new ManualResetEventSlim();
|
|
flow.Assembly.GetTypes().Single(t => t.Name.StartsWith("Extension_"))
|
|
.GetField("Release")!.SetValue(null, release);
|
|
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
flow.PropertyChanged += (_, e) =>
|
|
{
|
|
if (e.PropertyName == nameof(flow.IsRuning) && flow.IsRuning)
|
|
entered.TrySetResult();
|
|
};
|
|
flow.AutomaticExecution = automatic;
|
|
model.Workflows.Add(flow);
|
|
flow.Start(null!);
|
|
var manual = automatic ? Task.CompletedTask : Task.Run(() => flow.Run(null!));
|
|
try
|
|
{
|
|
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
|
bool loaded = false;
|
|
var change = model.ChangeRecipeAsync(() =>
|
|
{
|
|
Assert.True(flow.Flow.Completed);
|
|
loaded = true;
|
|
});
|
|
Assert.False(loaded);
|
|
Assert.False(change.IsCompleted);
|
|
await model.ChangeRecipeAsync(() => Assert.Fail("重复加载配方"));
|
|
release.Set();
|
|
await change.WaitAsync(TimeSpan.FromSeconds(10));
|
|
Assert.True(loaded);
|
|
flow.Run(null!);
|
|
Assert.Equal(1, flow.Flow.Step);
|
|
Assert.False(flow.IsRuning);
|
|
}
|
|
finally
|
|
{
|
|
release.Set();
|
|
await Task.WhenAll(manual, flow.StopAsync()).WaitAsync(TimeSpan.FromSeconds(10));
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
File.Delete(path);
|
|
}
|
|
}
|
|
}
|