* Refactor workflow instance deletion to use `IWorkflowRuntime` for enhanced coordination and separation of concerns. * Remove `EnumerableTypeConverter` and update related usages for serialization. - Deleted the `EnumerableTypeConverter` class and its JSON serialization logic. - Removed associated type descriptor attribute in `DefaultFormattersFeature`. - Updated `ObjectFormatter` to handle collection serialization directly with JSON. * Remove `EnumerableTypeConverter` tests and consolidate serialization logic into `ObjectFormatter`. - Deleted `EnumerableTypeConverterTests` as the related functionality was removed. - Added comprehensive tests in `ObjectFormatterTests` to handle serialization of collections and arrays with JSON. * Add integration tests for `TriggerIndexer` to handle workflows with failing materialization - Introduced comprehensive test scenarios verifying `DeleteTriggersAsync` behavior when workflows fail to load or partially succeed. - Enhanced error handling in `TriggerIndexer` to skip failed workflows while ensuring remaining workflows are processed. * Add exception handling in `TriggerIndexer.DeleteTriggersAsync` and integration tests - Enhanced `DeleteTriggersAsync` with exception handling to skip failed workflows while processing others. - Logged warnings for failed workflows without halting execution. - Added comprehensive integration tests to verify behavior across success, failure, and mixed scenarios. - Refactored tests for improved clarity, maintainability, and consistency. * Add exception handling for `ResumeWorkflowTask` to skip deleted workflow instances - Enhanced `ResumeWorkflowTask.ExecuteAsync` to handle `WorkflowInstanceNotFoundException` gracefully when a scheduled workflow instance is missing. - Logged warnings for skipped executions to improve observability. - Ensured remaining workflows and scheduled tasks are processed seamlessly without disruption. * Add thread safety to `LocalScheduler` to prevent race conditions during concurrent scheduling - Introduced a `lock` object to synchronize access to internal dictionaries. - Resolved `IndexOutOfRangeException` caused by concurrent modifications during startup. - Ensured thread-safe operations in `ScheduleAsync`, `ClearScheduleAsync`, and related methods. - Improved reliability and stability of scheduling under concurrent workloads. * Improve exception handling, thread safety, and workflow instance deletion - Added exception handling in `TriggerIndexer.DeleteTriggersAsync` to skip failed workflows while continuing processing. - Enhanced `ResumeWorkflowTask` to handle missing workflow instances gracefully and log warnings. - Introduced thread synchronization in `LocalScheduler` with `lock` to prevent concurrent access issues. - Implemented and refactored tests to ensure behavior consistency and improve maintainability. - Added component tests for workflow deletion scenarios, covering running, completed, and non-existent workflows. * Add component tests for workflow instance deletion and refactor bulk delete logic - Added comprehensive component tests for workflow instance deletion scenarios (running, completed, bulk, and non-existent instances). - Refactored `BulkDelete` API to use `IWorkflowInstanceManager` for proper cleanup of related records (execution logs, activity executions, bookmarks). * Add integration tests and fakes for `TriggerIndexer` to verify behavior with failing and successful workflows - Introduced `FailingMaterializer` and `WorkingMaterializer` for simulating failing and successful workflow materializations. - Added `TriggerDeletionTestScenario`, `TriggerTestDataBuilder`, and related test data classes to define comprehensive test cases. - Updated `DeleteTriggersAsync` tests with scenarios for materialization failures and mixed success. - Improved test coverage and maintainability with reusable test data builders and utilities. * Refactor `ActivityExecutionContextExtensions` to use instance methods for improved readability and encapsulation * Refactor extension methods to use instance methods for improved encapsulation and readability in core workflow modules * Add component tests for event-based workflows and update usages of `Event` activity - Added `BlockingEventWorkflow` and `TriggerEventWorkflow` for testing event-based workflow scenarios. - Added `EventTests` to verify workflow behavior with event publishing and triggering. - Refactored existing integration tests to use `Runtime.Activities.Event` for consistency. * Add unit tests for `EventBase` functionality - Introduced `EventBaseTests` to validate core `EventBase` logic, including bookmark creation, event stimulus handling, and callback invocation. - Added tests for scenarios involving event payloads, trigger indexing, and result output determination. - Verified behavior consistency with various event names and callback executions. * Add tests and workflows to validate event publishing and consumption - Introduced `ConsumerWorkflow`, `PublishGlobalEventWorkflow`, and `PublishAndConsumeEventWorkflow` to test global and local event publishing scenarios. - Added component tests (`PublishEventTests`) to verify event propagation and workflow triggering mechanisms. - Implemented unit tests for `PublishEvent` with various parameters (event name, payload, correlation ID). * Remove unused `using` directives in event-related component tests and workflows * Refactor `PublishEventTests` and `EventBaseTests` to improve test coverage, simplify test logic, and consolidate duplicate code. * Add `NullIfWhiteSpace` extension method and update `PublishEvent` logic to use it in correlation ID handling - Refactored `PublishEventTests` to account for cases where correlation ID is whitespace. - Improved test coverage for `PublishEvent` activity with additional inline test cases. * Refactor `PublishEventTests` to verify payload transmission and enhance `ConsumerWorkflow` to capture and validate event payloads. * Refactor `PublishEventTests` to add timeout mechanism for workflow instance retrieval; enhance `ConsumerWorkflow` to declare output variable for payload validation. * Update test/component/Elsa.Workflows.ComponentTests/Scenarios/Activities/Primitives/Event/PublishEventTests.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove `EventBaseTests` and `CancelInboundAncestorsAsync` for cleanup and redundant logic removal. --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
157 lines
5.7 KiB
C#
157 lines
5.7 KiB
C#
using Elsa.Expressions.Models;
|
|
using Elsa.Extensions;
|
|
using Elsa.Testing.Shared;
|
|
using Elsa.Workflows;
|
|
using Elsa.Workflows.Runtime;
|
|
using Elsa.Workflows.Runtime.Activities;
|
|
using Elsa.Workflows.Runtime.Stimuli;
|
|
|
|
namespace Elsa.Activities.UnitTests.Primitives;
|
|
|
|
public class EventBaseTests
|
|
{
|
|
[Fact]
|
|
public async Task ExecuteAsync_CreatesBookmark_WithCorrectEventName()
|
|
{
|
|
// Arrange
|
|
const string eventName = "MyTestEvent";
|
|
var activity = new TestEvent(eventName);
|
|
|
|
// Act
|
|
var context = await ExecuteAsync(activity);
|
|
|
|
// Assert
|
|
Assert.Equal(ActivityStatus.Running, context.Status);
|
|
var stimulus = GetEventStimulusFromContext(context);
|
|
Assert.Equal(eventName, stimulus.EventName);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExecuteAsync_CreatesBookmark_WithoutActivityInstanceId()
|
|
{
|
|
// Arrange
|
|
var activity = new TestEvent("TestEvent");
|
|
|
|
// Act
|
|
var context = await ExecuteAsync(activity);
|
|
|
|
// Assert
|
|
var bookmark = Assert.Single(context.WorkflowExecutionContext.Bookmarks);
|
|
Assert.True(string.IsNullOrEmpty(bookmark.ActivityInstanceId),
|
|
"ActivityInstanceId should be null or empty because IncludeActivityInstanceId is set to false");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("Event.Order.Created")]
|
|
[InlineData("Event.User.Registered")]
|
|
[InlineData("CustomEvent")]
|
|
public async Task ExecuteAsync_CreatesBookmark_WithCorrectEventStimulus(string eventName)
|
|
{
|
|
// Arrange & Act
|
|
var context = await ExecuteAsync(new TestEvent(eventName));
|
|
|
|
// Assert
|
|
var stimulus = GetEventStimulusFromContext(context);
|
|
Assert.Equal(eventName, stimulus.EventName);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExecuteAsync_SetsResultOutput_WhenCallbackIsInvoked()
|
|
{
|
|
// Arrange
|
|
const string expectedInput = "test payload";
|
|
var activity = new TestEvent<string>("TestEvent");
|
|
|
|
// Act
|
|
var context = await ExecuteAsync(activity);
|
|
context.WorkflowExecutionContext.Input[Event.EventInputWorkflowInputKey] = expectedInput;
|
|
await activity.InvokeCallbackAsync(context);
|
|
|
|
// Assert
|
|
var result = context.GetActivityOutput(() => activity.Result);
|
|
Assert.Equal(expectedInput, result);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task GetTriggerPayload_ReturnsEventStimulus_WithCorrectEventName()
|
|
{
|
|
// Arrange
|
|
const string eventName = "TriggerEvent";
|
|
var activity = new TestEvent(eventName);
|
|
var triggerIndexingContext = await CreateTriggerIndexingContextAsync(activity);
|
|
|
|
// Act
|
|
var payload = activity.GetTriggerPayloadPublic(triggerIndexingContext);
|
|
|
|
// Assert
|
|
var stimulus = Assert.IsType<EventStimulus>(payload);
|
|
Assert.Equal(eventName, stimulus.EventName);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task OnEventReceivedAsync_IsCalledDuringCallback()
|
|
{
|
|
// Arrange
|
|
const string testPayload = "callback-invoked";
|
|
var activity = new TestEvent<string>("TestEvent");
|
|
|
|
// Act
|
|
var context = await ExecuteAsync(activity);
|
|
context.WorkflowExecutionContext.Input[Elsa.Workflows.Runtime.Activities.Event.EventInputWorkflowInputKey] = testPayload;
|
|
await activity.InvokeCallbackAsync(context);
|
|
|
|
// Assert
|
|
Assert.True(activity.OnEventReceivedAsyncWasCalled);
|
|
Assert.Equal(testPayload, activity.ReceivedInput);
|
|
}
|
|
|
|
private static Task<ActivityExecutionContext> ExecuteAsync(IActivity activity) =>
|
|
new ActivityTestFixture(activity).ExecuteAsync();
|
|
|
|
private static EventStimulus GetEventStimulusFromContext(ActivityExecutionContext context)
|
|
{
|
|
var bookmark = Assert.Single(context.WorkflowExecutionContext.Bookmarks);
|
|
Assert.Equal(RuntimeStimulusNames.Event, bookmark.Name);
|
|
return Assert.IsType<EventStimulus>(bookmark.Payload);
|
|
}
|
|
|
|
private static async Task<TriggerIndexingContext> CreateTriggerIndexingContextAsync(IActivity activity)
|
|
{
|
|
var fixture = new ActivityTestFixture(activity);
|
|
var activityContext = await fixture.BuildAsync();
|
|
var workflowExecutionContext = activityContext.WorkflowExecutionContext;
|
|
var expressionExecutionContext = new ExpressionExecutionContext(workflowExecutionContext.ServiceProvider, workflowExecutionContext.MemoryRegister);
|
|
var workflowIndexingContext = new WorkflowIndexingContext(workflowExecutionContext.Workflow, CancellationToken.None);
|
|
return new(
|
|
workflowIndexingContext,
|
|
expressionExecutionContext,
|
|
(ITrigger)activity,
|
|
CancellationToken.None);
|
|
}
|
|
|
|
// Test implementation of EventBase for unit testing
|
|
private class TestEvent(string eventName) : EventBase<object?>
|
|
{
|
|
protected override string GetEventName(ExpressionExecutionContext context) => eventName;
|
|
|
|
public object GetTriggerPayloadPublic(TriggerIndexingContext context) => GetTriggerPayload(context);
|
|
}
|
|
|
|
// Test implementation with generic type and callback tracking
|
|
private class TestEvent<TResult>(string eventName) : EventBase<TResult>
|
|
{
|
|
public bool OnEventReceivedAsyncWasCalled { get; private set; }
|
|
public TResult? ReceivedInput { get; private set; }
|
|
|
|
protected override string GetEventName(ExpressionExecutionContext context) => eventName;
|
|
|
|
protected override ValueTask OnEventReceivedAsync(ActivityExecutionContext context, TResult? input)
|
|
{
|
|
OnEventReceivedAsyncWasCalled = true;
|
|
ReceivedInput = input;
|
|
return base.OnEventReceivedAsync(context, input);
|
|
}
|
|
|
|
public ValueTask InvokeCallbackAsync(ActivityExecutionContext context) => EventReceivedAsync(context);
|
|
}
|
|
} |