Class TestOrchestrationContext
- Namespace
- XBullet.EasyTesting.AzureFunctions
- Assembly
- XBullet.EasyTesting.AzureFunctions.dll
Context object used by orchestrators to perform actions such as scheduling tasks, durable timers, waiting for external events, and for getting basic information about the current orchestration.
public sealed class TestOrchestrationContext : TaskOrchestrationContext
- Inheritance
-
TestOrchestrationContext
- Inherited Members
- Extension Methods
Remarks
Timers use manually advanced UTC time, events are buffered in memory, and replay state is a test flag. Durable history, persistence, retries, and automatic replay are not emulated. Configure input, identity, handlers, and logging before starting the orchestrator.
Constructors
TestOrchestrationContext()
Creates an in-memory context whose activity and child handlers return default result values.
public TestOrchestrationContext()
TestOrchestrationContext(Func<RecordedActivityCall, Task<object?>>)
Initializes a context that dispatches activity calls through activityHandler.
public TestOrchestrationContext(Func<RecordedActivityCall, Task<object?>> activityHandler)
Parameters
activityHandlerFunc<RecordedActivityCall, Task<object>>A non-null asynchronous callback retained by the context and invoked once for every scheduled activity after the call is recorded. It must return a value assignable to the requested result type.
Properties
ActivityCalls
Gets activity calls in scheduling order.
public IReadOnlyList<RecordedActivityCall> ActivityCalls { get; }
Property Value
- IReadOnlyList<RecordedActivityCall>
A live read-only view in scheduling order. Calls retain their input and options without cloning.
ActivityHandler
Gets or sets the delegate used to execute scheduled activities.
public Func<RecordedActivityCall, Task<object?>> ActivityHandler { get; set; }
Property Value
- Func<RecordedActivityCall, Task<object>>
The non-null callback used for future calls. Assigning a new callback does not affect calls already recorded or awaiting a previous handler. Named activity registrations take precedence.
ContinueAsNewRequests
Gets continuation requests in invocation order without restarting the orchestrator.
public IReadOnlyList<ContinueAsNewOptions> ContinueAsNewRequests { get; }
Property Value
- IReadOnlyList<ContinueAsNewOptions>
Options copied on invocation; input objects are retained without cloning.
CurrentUtcDateTime
Gets the current orchestration time in UTC.
public override DateTime CurrentUtcDateTime { get; }
Property Value
Remarks
The current orchestration time is stored in the orchestration history and this API will return the same value each time it is called from a particular point in the orchestration's execution. It is a deterministic, replay-safe replacement for existing .NET APIs for getting the current time, such as UtcNow and UtcNow.
CustomStatus
Gets the most recent custom status supplied by the test or orchestrator.
public object? CustomStatus { get; }
Property Value
- object
The retained status object, initially null.
Entities
Gets the entity feature, for interacting with entities.
public override TaskOrchestrationEntityFeature Entities { get; }
Property Value
InstanceId
Gets the unique ID of the current orchestration instance.
public override string InstanceId { get; }
Property Value
IsReplaying
Gets the test-controlled replay flag.
public override bool IsReplaying { get; }
Property Value
- bool
False by default; set with WithReplayState(bool). Durable history is not replayed.
LoggerFactory
Gets the logger factory for this context.
protected override ILoggerFactory LoggerFactory { get; }
Property Value
Name
Gets the name of the task orchestration.
public override TaskName Name { get; }
Property Value
Parent
Gets the parent instance or null if there is no parent orchestration.
public override ParentOrchestrationInstance? Parent { get; }
Property Value
Properties
Gets the configuration settings for the orchestration context.
public override IReadOnlyDictionary<string, object?> Properties { get; }
Property Value
ReplaySafeLoggerFactory
Gets an ILoggerFactory whose loggers are replay-safe, meaning they suppress log output during orchestration replay. This is the recommended way to expose logger functionality when wrapping a TaskOrchestrationContext instance.
public override ILoggerFactory ReplaySafeLoggerFactory { get; }
Property Value
Remarks
Loggers created by this factory automatically check IsReplaying and suppress duplicate log messages during replay. This is equivalent to calling CreateReplaySafeLogger(string) for each logger category.
Context wrapper implementations can delegate LoggerFactory to this property
on the inner context: protected override ILoggerFactory LoggerFactory => inner.ReplaySafeLoggerFactory;.
SentEvents
Gets outbound events in sending order.
public IReadOnlyList<RecordedOrchestrationEvent> SentEvents { get; }
Property Value
- IReadOnlyList<RecordedOrchestrationEvent>
A live read-only view. Events sent to this context's instance are also delivered locally.
SubOrchestrationCalls
Gets child orchestration calls in scheduling order.
public IReadOnlyList<RecordedSubOrchestrationCall> SubOrchestrationCalls { get; }
Property Value
- IReadOnlyList<RecordedSubOrchestrationCall>
A live read-only view; inputs and options are retained without cloning.
SubOrchestratorHandler
Gets or sets the callback invoked for each recorded sub-orchestrator call.
public Func<RecordedSubOrchestrationCall, Task<object?>> SubOrchestratorHandler { get; set; }
Property Value
- Func<RecordedSubOrchestrationCall, Task<object>>
A non-null callback. The default returns the requested result type's default value.
Version
Gets the version of the current orchestration instance, which was set when the instance was created.
public override string Version { get; }
Property Value
Methods
AdvanceTimeBy(TimeSpan)
Advances simulated UTC time by a non-negative interval and completes due timers.
public TestOrchestrationContext AdvanceTimeBy(TimeSpan duration)
Parameters
durationTimeSpanThe non-negative simulated interval; no wall-clock delay occurs.
Returns
- TestOrchestrationContext
This context, for chaining. Timer continuations run asynchronously.
AdvanceTimeTo(DateTime)
Advances simulated time and completes timers already scheduled on or before the new time.
public TestOrchestrationContext AdvanceTimeTo(DateTime utcDateTime)
Parameters
utcDateTimeDateTimeA UTC timestamp at or after the current time, initially the Unix epoch.
Returns
- TestOrchestrationContext
This context, for chaining. Timer continuations run asynchronously.
CallActivityAsync<TResult>(TaskName, object?, TaskOptions?)
Asynchronously invokes an activity by name and with the specified input value.
public override Task<TResult> CallActivityAsync<TResult>(TaskName name, object? input = null, TaskOptions? options = null)
Parameters
nameTaskNameThe name of the activity to call.
inputobjectThe serializable input to pass to the activity.
optionsTaskOptionsAdditional options that control the execution and processing of the activity.
Returns
- Task<TResult>
A task that completes when the activity completes or fails. The result of the task is the activity's return value.
Type Parameters
TResultThe type into which to deserialize the activity's output.
Remarks
Activities are the basic unit of work in a durable task orchestration. Unlike orchestrators, which are not allowed to do any I/O or call non-deterministic APIs, activities have no implementation restrictions.
An activity may execute in the local machine or a remote machine. The exact behavior depends on the underlying storage provider, which is responsible for distributing tasks across machines. In general, you should never make any assumptions about where an activity will run. You should also assume at-least-once execution guarantees for activities, meaning that an activity may be executed twice if, for example, there is a process failure before the activities result is saved into storage.
Both the inputs and outputs of activities are serialized and stored in durable storage. It's highly recommended to not include any sensitive data in activity inputs or outputs. It's also recommended to not use large payloads for activity inputs and outputs, which can result in expensive serialization and network utilization. For data that cannot be cheaply or safely persisted to storage, it's recommended to instead pass references (for example, a URL to a storage blob) to the data and have activities fetch the data directly as part of their implementation.
Exceptions
- ArgumentException
The specified activity does not exist.
- InvalidOperationException
Thrown if the calling thread is anything other than the main orchestrator thread.
- TaskFailedException
The activity failed with an unhandled exception. The details of the failure can be found in the FailureDetails property.
CallSubOrchestratorAsync<TResult>(TaskName, object?, TaskOptions?)
Records a child orchestration call and dispatches it to SubOrchestratorHandler.
public override Task<TResult> CallSubOrchestratorAsync<TResult>(TaskName orchestratorName, object? input = null, TaskOptions? options = null)
Parameters
orchestratorNameTaskNameThe child orchestrator's task name.
inputobjectThe input retained without cloning.
optionsTaskOptionsOptional task or child-instance options, recorded without executing retry policies.
Returns
- Task<TResult>
The handler result. Handler failures propagate and incompatible results fault the task.
Type Parameters
TResultThe type assignable from the handler result.
CompareVersionTo(string)
Compares the configured version using ordinal ordering or a custom comparison.
public override int CompareVersionTo(string version)
Parameters
versionstringThe non-null version to compare with. Empty strings are allowed.
Returns
- int
A negative, zero, or positive result for the configured version relative to version.
ContinueAsNew(ContinueAsNewOptions)
Copies and records a continuation request, then invokes an optional callback.
public override void ContinueAsNew(ContinueAsNewOptions options)
Parameters
optionsContinueAsNewOptionsNon-null next-execution options. No history reset or runtime restart occurs.
ContinueAsNew(object?, bool)
Records a continuation request without restarting or modifying the current execution.
public override void ContinueAsNew(object? newInput = null, bool preserveUnprocessedEvents = true)
Parameters
newInputobjectInput for the requested next execution, retained without cloning.
preserveUnprocessedEventsboolThe recorded event-preservation decision; current event queues are unchanged.
CreateTimer(DateTime, CancellationToken)
Schedules an in-memory timer driven by manual time advancement.
public override Task CreateTimer(DateTime fireAt, CancellationToken cancellationToken)
Parameters
fireAtDateTimeA UTC timestamp. Past or current timestamps complete immediately.
cancellationTokenCancellationTokenCancels the pending timer with the caller's token.
Returns
- Task
A task completed when simulated time reaches fireAt, or canceled when cancellation wins.
GetInput<T>()
Gets configured input, deserializing when attached to a workflow with serialization enabled.
public override T GetInput<T>()
Returns
- T
The retained or deserialized input, or default when no input was supplied.
Type Parameters
TThe assignable input type, or the deserialization target for serialized workflows.
Exceptions
- InvalidOperationException
The non-null input cannot be assigned to T.
NewGuid()
Creates a repeatable GUID from the instance ID and sequence, or invokes the configured generator.
public override Guid NewGuid()
Returns
- Guid
A test GUID. The default sequence is not the Durable runtime's GUID algorithm.
RaiseEvent(string, object?)
Delivers an external event to the oldest matching wait or buffers it until a wait is created.
public void RaiseEvent(string eventName, object? payload)
Parameters
eventNamestringA non-empty case-insensitive event name.
payloadobjectThe event payload retained without cloning; null is allowed for nullable result types.
SendEvent(string, string, object)
Records an outbound event and delivers it locally when the target is this instance.
public override void SendEvent(string instanceId, string eventName, object payload)
Parameters
instanceIdstringThe non-empty target instance ID. Remote delivery is left to the test.
eventNamestringThe non-empty case-insensitive event name.
payloadobjectThe non-null payload retained without cloning.
SetCustomStatus(object?)
Records the latest custom status and invokes an optional configured callback.
public override void SetCustomStatus(object? customStatus)
Parameters
customStatusobjectThe status retained without cloning; null clears the status.
WaitForExternalEvent<T>(string, CancellationToken)
Waits for the next matching buffered or raised event.
public override Task<T> WaitForExternalEvent<T>(string eventName, CancellationToken cancellationToken = default)
Parameters
eventNamestringA non-empty case-insensitive event name. Each event completes one wait in FIFO order.
cancellationTokenCancellationTokenCancels and removes this wait without consuming a future event.
Returns
- Task<T>
The next event payload. Incompatible payloads fault the wait with InvalidOperationException.
Type Parameters
TThe type assignable from the event payload.
WithActivityHandler(Func<RecordedActivityCall, Task<object?>>)
Overrides the fallback activity dispatch callback.
public TestOrchestrationContext WithActivityHandler(Func<RecordedActivityCall, Task<object?>> handler)
Parameters
handlerFunc<RecordedActivityCall, Task<object>>The non-null handler used for activity names without a named registration.
Returns
- TestOrchestrationContext
This context, for chaining.
WithActivityHandler(string, Func<string, object?, Task<object?>>)
Configures the handler invoked for the activity named activityName.
public TestOrchestrationContext WithActivityHandler(string activityName, Func<string, object?, Task<object?>> handler)
Parameters
activityNamestringThe non-empty registered function name, matched case-sensitively with ordinal comparison.
handlerFunc<string, object, Task<object>>A non-null callback receiving the activity name and original input, returning its typed result.
Returns
- TestOrchestrationContext
This context, for chaining. Registering a name again replaces its handler for future calls.
WithContinueAsNewHandler(Action<ContinueAsNewOptions>)
Overrides the callback invoked after each continuation request is recorded.
public TestOrchestrationContext WithContinueAsNewHandler(Action<ContinueAsNewOptions> handler)
Parameters
handlerAction<ContinueAsNewOptions>A non-null callback. Callback failures propagate; no automatic restart occurs.
Returns
- TestOrchestrationContext
This context, for chaining.
WithCustomStatus(object?)
Sets initial custom status using the same recording behavior as SetCustomStatus.
public TestOrchestrationContext WithCustomStatus(object? status)
Parameters
statusobjectThe retained status object; null clears it.
Returns
- TestOrchestrationContext
This context, for chaining.
WithCustomStatusHandler(Action<object?>)
Overrides the callback invoked after each custom-status update.
public TestOrchestrationContext WithCustomStatusHandler(Action<object?> handler)
Parameters
handlerAction<object>A non-null callback. Callback failures propagate after the status is recorded.
Returns
- TestOrchestrationContext
This context, for chaining.
WithEntities(TaskOrchestrationEntityFeature)
Overrides the default entity stub with a caller-supplied feature.
public TestOrchestrationContext WithEntities(TaskOrchestrationEntityFeature entities)
Parameters
entitiesTaskOrchestrationEntityFeatureThe non-null caller-owned feature. The context does not dispose it.
Returns
- TestOrchestrationContext
This context, for chaining.
WithGuidGenerator(Func<Guid>)
Overrides GUID generation for future calls.
public TestOrchestrationContext WithGuidGenerator(Func<Guid> generator)
Parameters
Returns
- TestOrchestrationContext
This context, for chaining.
WithInput(object?)
Sets the input returned by GetInput<T>().
public TestOrchestrationContext WithInput(object? input)
Parameters
inputobjectThe input retained without serialization or cloning; null represents absent input.
Returns
- TestOrchestrationContext
This context, for chaining.
WithInstanceId(string)
Sets the orchestration instance identifier.
public TestOrchestrationContext WithInstanceId(string instanceId)
Parameters
instanceIdstringA non-empty identifier, compared ordinally when delivering self-directed events.
Returns
- TestOrchestrationContext
This context, for chaining.
WithLoggerFactory(ILoggerFactory)
Configures the underlying logger factory before replay-safe loggers are created.
public TestOrchestrationContext WithLoggerFactory(ILoggerFactory loggerFactory)
Parameters
loggerFactoryILoggerFactoryThe non-null caller-owned factory. The context does not dispose it.
Returns
- TestOrchestrationContext
This context, for chaining.
WithName(TaskName)
Overrides the orchestration name, initially TestOrchestrator.
public TestOrchestrationContext WithName(TaskName name)
Parameters
nameTaskNameA task name with a non-empty Name value.
Returns
- TestOrchestrationContext
This context, for chaining.
WithParent(ParentOrchestrationInstance?)
Overrides parent metadata, initially null.
public TestOrchestrationContext WithParent(ParentOrchestrationInstance? parent)
Parameters
parentParentOrchestrationInstanceThe parent descriptor retained by reference; null clears it.
Returns
- TestOrchestrationContext
This context, for chaining.
WithProperties(IReadOnlyDictionary<string, object?>)
Overrides configuration properties, initially empty.
public TestOrchestrationContext WithProperties(IReadOnlyDictionary<string, object?> properties)
Parameters
propertiesIReadOnlyDictionary<string, object>A non-null dictionary shallow-copied into a read-only ordinal dictionary.
Returns
- TestOrchestrationContext
This context, for chaining.
WithReplayState(bool)
Sets the replay flag without replaying history or caching dispatch results.
public TestOrchestrationContext WithReplayState(bool isReplaying)
Parameters
isReplayingboolWhether replay-aware branches and logging should observe replay state.
Returns
- TestOrchestrationContext
This context, for chaining. Existing replay-safe loggers observe subsequent flag changes.
WithSubOrchestratorHandler(Func<RecordedSubOrchestrationCall, Task<object?>>)
Overrides the child orchestration dispatch callback.
public TestOrchestrationContext WithSubOrchestratorHandler(Func<RecordedSubOrchestrationCall, Task<object?>> handler)
Parameters
handlerFunc<RecordedSubOrchestrationCall, Task<object>>The non-null handler used for future recorded child calls.
Returns
- TestOrchestrationContext
This context, for chaining.
WithVersion(string)
Overrides the orchestration version, initially empty.
public TestOrchestrationContext WithVersion(string version)
Parameters
versionstringThe non-null version; an empty string represents an unversioned execution.
Returns
- TestOrchestrationContext
This context, for chaining.
WithVersionComparer(Func<string, string, int>)
Overrides ordinal version ordering with a custom comparison.
public TestOrchestrationContext WithVersionComparer(Func<string, string, int> comparer)
Parameters
comparerFunc<string, string, int>A non-null callback receiving the current version and comparison version.
Returns
- TestOrchestrationContext
This context, for chaining.