How to use GetOrCreateActorOperation method of Microsoft.Coyote.Actors.ActorExecutionContext class

Best Coyote code snippet using Microsoft.Coyote.Actors.ActorExecutionContext.GetOrCreateActorOperation

ActorExecutionContext.cs

Source:ActorExecutionContext.cs Github

copy

Full Screen

...213 eventGroup = creator.EventGroup;214 }215 Actor actor = ActorFactory.Create(type);216 ActorOperation op = this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing ?217 this.GetOrCreateActorOperation(id, actor) : null;218 IEventQueue eventQueue = new EventQueue(actor);219 actor.Configure(this, id, op, eventQueue, eventGroup);220 actor.SetupEventHandlers();221 if (!this.ActorMap.TryAdd(id, actor))222 {223 throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");224 }225 return actor;226 }227 /// <summary>228 /// Returns the operation for the specified actor id, or creates a new229 /// operation if it does not exist yet.230 /// </summary>231 protected ActorOperation GetOrCreateActorOperation(ActorId id, Actor actor)232 {233 var op = this.Runtime.GetOperationWithId<ActorOperation>(id.Value);234 return op ?? new ActorOperation(id.Value, id.Name, actor, this.Runtime);235 }236 /// <inheritdoc/>237 public virtual void SendEvent(ActorId targetId, Event initialEvent, EventGroup eventGroup = default, SendOptions options = null) =>238 this.SendEvent(targetId, initialEvent, null, eventGroup, options);239 /// <inheritdoc/>240 public virtual Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event initialEvent,241 EventGroup eventGroup = null, SendOptions options = null) =>242 this.SendEventAndExecuteAsync(targetId, initialEvent, null, eventGroup, options);243 /// <summary>244 /// Sends an asynchronous <see cref="Event"/> to an actor.245 /// </summary>246 internal virtual void SendEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, SendOptions options)247 {248 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, out Actor target);249 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)250 {251 this.OnActorEventHandlerStarted(target.Id);252 this.RunActorEventHandler(target, null, false);253 }254 }255 /// <summary>256 /// Sends an asynchronous <see cref="Event"/> to an actor. Returns immediately if the target was257 /// already running. Otherwise blocks until the target handles the event and reaches quiescence.258 /// </summary>259 internal virtual async Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event e, Actor sender,260 EventGroup eventGroup, SendOptions options)261 {262 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, out Actor target);263 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)264 {265 this.OnActorEventHandlerStarted(target.Id);266 await this.RunActorEventHandlerAsync(target, null, false);267 return true;268 }269 return enqueueStatus is EnqueueStatus.Dropped;270 }271 /// <summary>272 /// Enqueues an event to the actor with the specified id.273 /// </summary>274 private EnqueueStatus EnqueueEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, out Actor target)275 {276 if (e is null)277 {278 string message = sender != null ?279 string.Format("{0} is sending a null event.", sender.Id.ToString()) :280 "Cannot send a null event.";281 this.Assert(false, message);282 }283 if (targetId is null)284 {285 string message = (sender != null) ?286 string.Format("{0} is sending event {1} to a null actor.", sender.Id.ToString(), e.ToString())287 : string.Format("Cannot send event {0} to a null actor.", e.ToString());288 this.Assert(false, message);289 }290 if (this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing &&291 this.Runtime.TryGetExecutingOperation(out ControlledOperation current))292 {293 this.Runtime.DelayOperation(current);294 }295 target = this.GetActorWithId<Actor>(targetId);296 // If no group is provided we default to passing along the group from the sender.297 if (eventGroup is null && sender != null)298 {299 eventGroup = sender.EventGroup;300 }301 Guid opId = eventGroup is null ? Guid.Empty : eventGroup.Id;302 if (target is null || target.IsHalted)303 {304 this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,305 (sender as StateMachine)?.CurrentStateName ?? default, e, opId, isTargetHalted: true);306 this.HandleDroppedEvent(e, targetId);307 return EnqueueStatus.Dropped;308 }309 this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,310 (sender as StateMachine)?.CurrentStateName ?? default, e, opId, isTargetHalted: false);311 EnqueueStatus enqueueStatus = target.Enqueue(e, eventGroup, null);312 if (enqueueStatus == EnqueueStatus.Dropped)313 {314 this.HandleDroppedEvent(e, targetId);315 }316 return enqueueStatus;317 }318 /// <summary>319 /// Runs a new asynchronous actor event handler.320 /// This is a fire and forget invocation.321 /// </summary>322 private void RunActorEventHandler(Actor actor, Event initialEvent, bool isFresh)323 {324 if (this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing)325 {326 this.Runtime.TaskFactory.StartNew(async state =>327 {328 await this.RunActorEventHandlerAsync(actor, initialEvent, isFresh);329 },330 actor.Operation,331 default,332 this.Runtime.TaskFactory.CreationOptions | TaskCreationOptions.DenyChildAttach,333 this.Runtime.TaskFactory.Scheduler);334 }335 else336 {337 Task.Run(async () => await this.RunActorEventHandlerAsync(actor, initialEvent, isFresh));338 }339 }340 /// <summary>341 /// Runs a new asynchronous actor event handler.342 /// </summary>343 private async Task RunActorEventHandlerAsync(Actor actor, Event initialEvent, bool isFresh)344 {345 try346 {347 if (isFresh)348 {349 await actor.InitializeAsync(initialEvent);350 }351 await actor.RunEventHandlerAsync();352 }353 catch (Exception ex)354 {355 this.Runtime.IsRunning = false;356 this.RaiseOnFailureEvent(ex);357 }358 finally359 {360 if (actor.IsHalted)361 {362 this.ActorMap.TryRemove(actor.Id, out Actor _);363 }364 this.OnActorEventHandlerCompleted(actor.Id);365 }366 }367 /// <summary>368 /// Invoked when the event handler of the specified actor starts.369 /// </summary>370 protected void OnActorEventHandlerStarted(ActorId actorId)371 {372 if (this.Runtime.SchedulingPolicy != SchedulingPolicy.None)373 {374 lock (this.QuiescenceSyncObject)375 {376 this.EnabledActors.Add(actorId);377 }378 }379 }380 /// <summary>381 /// Invoked when the event handler of the specified actor completes.382 /// </summary>383 protected void OnActorEventHandlerCompleted(ActorId actorId)384 {385 if (this.Runtime.SchedulingPolicy != SchedulingPolicy.None)386 {387 lock (this.QuiescenceSyncObject)388 {389 this.EnabledActors.Remove(actorId);390 if (this.IsActorQuiescenceAwaited && this.EnabledActors.Count is 0)391 {392 this.QuiescenceCompletionSource.TrySetResult(true);393 }394 }395 }396 }397 /// <summary>398 /// Creates a new timer that sends a <see cref="TimerElapsedEvent"/> to its owner actor.399 /// </summary>400 internal virtual IActorTimer CreateActorTimer(TimerInfo info, Actor owner) => new ActorTimer(info, owner);401 /// <inheritdoc/>402 public virtual EventGroup GetCurrentEventGroup(ActorId currentActorId)403 {404 Actor actor = this.GetActorWithId<Actor>(currentActorId);405 return actor?.CurrentEventGroup;406 }407 /// <summary>408 /// Gets the actor of type <typeparamref name="TActor"/> with the specified id,409 /// or null if no such actor exists.410 /// </summary>411 private TActor GetActorWithId<TActor>(ActorId id)412 where TActor : Actor =>413 id != null && this.ActorMap.TryGetValue(id, out Actor value) &&414 value is TActor actor ? actor : null;415 /// <summary>416 /// Returns the next available unique operation id.417 /// </summary>418 /// <returns>Value representing the next available unique operation id.</returns>419 private ulong GetNextOperationId() => this.Runtime.GetNextOperationId();420 /// <inheritdoc/>421 public bool RandomBoolean() => this.GetNondeterministicBooleanChoice(null, null);422 /// <summary>423 /// Returns a controlled nondeterministic boolean choice.424 /// </summary>425 internal virtual bool GetNondeterministicBooleanChoice(string callerName, string callerType) =>426 this.Runtime.GetNextNondeterministicBooleanChoice(callerName, callerType);427 /// <inheritdoc/>428 public int RandomInteger(int maxValue) => this.GetNondeterministicIntegerChoice(maxValue, null, null);429 /// <summary>430 /// Returns a controlled nondeterministic integer choice.431 /// </summary>432 internal virtual int GetNondeterministicIntegerChoice(int maxValue, string callerName, string callerType) =>433 this.Runtime.GetNextNondeterministicIntegerChoice(maxValue, callerName, callerType);434 /// <summary>435 /// Logs that the specified actor invoked an action.436 /// </summary>437 internal virtual void LogInvokedAction(Actor actor, MethodInfo action, string handlingStateName, string currentStateName)438 {439 if (this.Configuration.IsVerbose)440 {441 this.LogWriter.LogExecuteAction(actor.Id, handlingStateName, currentStateName, action.Name);442 }443 }444 /// <summary>445 /// Logs that the specified actor enqueued an <see cref="Event"/>.446 /// </summary>447 internal virtual void LogEnqueuedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo)448 {449 if (this.Configuration.IsVerbose)450 {451 this.LogWriter.LogEnqueueEvent(actor.Id, e);452 }453 }454 /// <summary>455 /// Logs that the specified actor dequeued an <see cref="Event"/>.456 /// </summary>457 internal virtual void LogDequeuedEvent(Actor actor, Event e, EventInfo eventInfo, bool isFreshDequeue)458 {459 if (this.Configuration.IsVerbose)460 {461 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;462 this.LogWriter.LogDequeueEvent(actor.Id, stateName, e);463 }464 }465 /// <summary>466 /// Logs that the specified actor dequeued the default <see cref="Event"/>.467 /// </summary>468 [MethodImpl(MethodImplOptions.AggressiveInlining)]469 internal virtual void LogDefaultEventDequeued(Actor actor)470 {471 }472 /// <summary>473 /// Logs that the specified actor raised an <see cref="Event"/>.474 /// </summary>475 internal virtual void LogRaisedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo)476 {477 if (this.Configuration.IsVerbose)478 {479 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;480 this.LogWriter.LogRaiseEvent(actor.Id, stateName, e);481 }482 }483 /// <summary>484 /// Logs that the specified actor is handling a raised <see cref="Event"/>.485 /// </summary>486 internal virtual void LogHandleRaisedEvent(Actor actor, Event e)487 {488 if (this.Configuration.IsVerbose)489 {490 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;491 this.LogWriter.LogHandleRaisedEvent(actor.Id, stateName, e);492 }493 }494 /// <summary>495 /// Logs that the specified actor is handling a raised <see cref="HaltEvent"/>.496 /// </summary>497 internal virtual void LogHandleHaltEvent(Actor actor, int inboxSize)498 {499 if (this.Configuration.IsVerbose)500 {501 this.LogWriter.LogHalt(actor.Id, inboxSize);502 }503 }504 /// <summary>505 /// Logs that the specified actor called <see cref="Actor.ReceiveEventAsync(Type[])"/>506 /// or one of its overloaded methods.507 /// </summary>508 [MethodImpl(MethodImplOptions.AggressiveInlining)]509 internal virtual void LogReceiveCalled(Actor actor)510 {511 }512 /// <summary>513 /// Logs that the specified actor enqueued an event that it was waiting to receive.514 /// </summary>515 internal virtual void LogReceivedEvent(Actor actor, Event e, EventInfo eventInfo)516 {517 if (this.Configuration.IsVerbose)518 {519 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;520 this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: true);521 }522 }523 /// <summary>524 /// Logs that the specified actor received an event without waiting because the event525 /// was already in the inbox when the actor invoked the receive statement.526 /// </summary>527 internal virtual void LogReceivedEventWithoutWaiting(Actor actor, Event e, EventInfo eventInfo)528 {529 if (this.Configuration.IsVerbose)530 {531 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;532 this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: false);533 }534 }535 /// <summary>536 /// Logs that the specified actor is waiting to receive an event of one of the specified types.537 /// </summary>538 internal virtual void LogWaitEvent(Actor actor, IEnumerable<Type> eventTypes)539 {540 if (this.Configuration.IsVerbose)541 {542 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;543 var eventWaitTypesArray = eventTypes.ToArray();544 if (eventWaitTypesArray.Length is 1)545 {546 this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray[0]);547 }548 else549 {550 this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray);551 }552 }553 }554 /// <summary>555 /// Logs that the event handler of the specified actor terminated.556 /// </summary>557 internal virtual void LogEventHandlerTerminated(Actor actor, DequeueStatus dequeueStatus)558 {559 if (this.Configuration.IsVerbose)560 {561 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;562 this.LogWriter.LogEventHandlerTerminated(actor.Id, stateName, dequeueStatus);563 }564 }565 /// <summary>566 /// Logs that the specified state machine entered a state.567 /// </summary>568 internal virtual void LogEnteredState(StateMachine stateMachine)569 {570 if (this.Configuration.IsVerbose)571 {572 this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: true);573 }574 }575 /// <summary>576 /// Logs that the specified state machine exited a state.577 /// </summary>578 internal virtual void LogExitedState(StateMachine stateMachine)579 {580 if (this.Configuration.IsVerbose)581 {582 this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: false);583 }584 }585 /// <summary>586 /// Logs that the specified state machine invoked pop.587 /// </summary>588 [MethodImpl(MethodImplOptions.AggressiveInlining)]589 internal virtual void LogPopState(StateMachine stateMachine)590 {591 }592 /// <summary>593 /// Logs that the specified state machine invoked an action.594 /// </summary>595 internal virtual void LogInvokedOnEntryAction(StateMachine stateMachine, MethodInfo action)596 {597 if (this.Configuration.IsVerbose)598 {599 this.LogWriter.LogExecuteAction(stateMachine.Id, stateMachine.CurrentStateName,600 stateMachine.CurrentStateName, action.Name);601 }602 }603 /// <summary>604 /// Logs that the specified state machine invoked an action.605 /// </summary>606 internal virtual void LogInvokedOnExitAction(StateMachine stateMachine, MethodInfo action)607 {608 if (this.Configuration.IsVerbose)609 {610 this.LogWriter.LogExecuteAction(stateMachine.Id, stateMachine.CurrentStateName,611 stateMachine.CurrentStateName, action.Name);612 }613 }614 /// <summary>615 /// Builds the coverage graph information, if any. This information is only available616 /// when <see cref="Configuration.IsActivityCoverageReported"/> is enabled.617 /// </summary>618 internal CoverageInfo BuildCoverageInfo()619 {620 var result = this.CoverageInfo;621 if (result != null)622 {623 var builder = this.LogWriter.GetLogsOfType<ActorRuntimeLogGraphBuilder>()624 .FirstOrDefault(builder => builder.CollapseInstances);625 if (builder != null)626 {627 result.CoverageGraph = builder.SnapshotGraph(false);628 }629 var eventCoverage = this.LogWriter.GetLogsOfType<ActorRuntimeLogEventCoverage>().FirstOrDefault();630 if (eventCoverage != null)631 {632 result.EventInfo = eventCoverage.EventCoverage;633 }634 }635 return result;636 }637 /// <summary>638 /// Returns the DGML graph of the current execution, if there is any.639 /// </summary>640 internal Graph GetExecutionGraph()641 {642 Graph result = null;643 var builder = this.LogWriter.GetLogsOfType<ActorRuntimeLogGraphBuilder>()644 .FirstOrDefault(builder => !builder.CollapseInstances);645 if (builder != null)646 {647 result = builder.SnapshotGraph(true);648 }649 return result;650 }651 /// <summary>652 /// Returns the program counter of the specified actor.653 /// </summary>654 [MethodImpl(MethodImplOptions.AggressiveInlining)]655 internal virtual int GetActorProgramCounter(ActorId actorId) => 0;656 /// <inheritdoc/>657 public void RegisterMonitor<T>()658 where T : Monitor =>659 this.Runtime.RegisterMonitor<T>();660 /// <inheritdoc/>661 public void Monitor<T>(Event e)662 where T : Monitor =>663 this.Runtime.Monitor<T>(e);664 /// <summary>665 /// Invokes the specified <see cref="Specifications.Monitor"/> with the specified <see cref="Event"/>.666 /// </summary>667 internal void InvokeMonitor(Type type, Event e, string senderName, string senderType, string senderStateName) =>668 this.Runtime.InvokeMonitor(type, e, senderName, senderType, senderStateName);669 /// <inheritdoc/>670 [MethodImpl(MethodImplOptions.AggressiveInlining)]671 public void Assert(bool predicate) => this.Runtime.Assert(predicate);672 /// <inheritdoc/>673 [MethodImpl(MethodImplOptions.AggressiveInlining)]674 public void Assert(bool predicate, string s, object arg0) => this.Runtime.Assert(predicate, s, arg0);675 /// <inheritdoc/>676 [MethodImpl(MethodImplOptions.AggressiveInlining)]677 public void Assert(bool predicate, string s, object arg0, object arg1) => this.Runtime.Assert(predicate, s, arg0, arg1);678 /// <inheritdoc/>679 [MethodImpl(MethodImplOptions.AggressiveInlining)]680 public void Assert(bool predicate, string s, object arg0, object arg1, object arg2) =>681 this.Runtime.Assert(predicate, s, arg0, arg1, arg2);682 /// <inheritdoc/>683 [MethodImpl(MethodImplOptions.AggressiveInlining)]684 public void Assert(bool predicate, string s, params object[] args) => this.Runtime.Assert(predicate, s, args);685 /// <summary>686 /// Asserts that the actor calling an actor method is also the actor that is currently executing.687 /// </summary>688 [MethodImpl(MethodImplOptions.AggressiveInlining)]689 internal virtual void AssertExpectedCallerActor(Actor caller, string calledAPI)690 {691 }692 /// <summary>693 /// Raises the <see cref="OnFailure"/> event with the specified <see cref="Exception"/>.694 /// </summary>695 internal void RaiseOnFailureEvent(Exception exception) => this.Runtime.RaiseOnFailureEvent(exception);696 /// <summary>697 /// Handle the specified dropped <see cref="Event"/>.698 /// </summary>699 internal void HandleDroppedEvent(Event e, ActorId id) => this.OnEventDropped?.Invoke(e, id);700 /// <summary>701 /// Throws an <see cref="AssertionFailureException"/> exception containing the specified exception.702 /// </summary>703#if !DEBUG704 [DebuggerHidden]705#endif706 internal void WrapAndThrowException(Exception exception, string s, params object[] args) =>707 this.Runtime.WrapAndThrowException(exception, s, args);708 /// <inheritdoc/>709 [Obsolete("Please set the Logger property directory instead of calling this method.")]710 public TextWriter SetLogger(TextWriter logger)711 {712 var result = this.LogWriter.SetLogger(new TextWriterLogger(logger));713 if (result != null)714 {715 return result.TextWriter;716 }717 return null;718 }719 /// <inheritdoc/>720 public void RegisterLog(IRuntimeLog log) => this.Runtime.RegisterLog(log);721 /// <inheritdoc/>722 public void RemoveLog(IRuntimeLog log) => this.Runtime.RemoveLog(log);723 /// <summary>724 /// Returns a task that completes once all actors reach quiescence.725 /// </summary>726 internal Task WaitUntilQuiescenceAsync()727 {728 lock (this.QuiescenceSyncObject)729 {730 if (this.EnabledActors.Count > 0)731 {732 this.IsActorQuiescenceAwaited = true;733 return this.QuiescenceCompletionSource.Task;734 }735 else736 {737 return Task.CompletedTask;738 }739 }740 }741 /// <inheritdoc/>742 public void Stop() => this.Runtime.Stop();743 /// <summary>744 /// Disposes runtime resources.745 /// </summary>746 protected virtual void Dispose(bool disposing)747 {748 if (disposing)749 {750 this.ActorMap.Clear();751 this.EnabledActors.Clear();752 }753 }754 /// <inheritdoc/>755 public void Dispose()756 {757 this.Dispose(true);758 GC.SuppressFinalize(this);759 }760 /// <summary>761 /// The mocked execution context of an actor program.762 /// </summary>763 internal sealed class Mock : ActorExecutionContext764 {765 /// <summary>766 /// Set of all created actor ids.767 /// </summary>768 private readonly ConcurrentDictionary<ActorId, byte> ActorIds;769 /// <summary>770 /// Map that stores all unique names and their corresponding actor ids.771 /// </summary>772 private readonly ConcurrentDictionary<string, ActorId> NameValueToActorId;773 /// <summary>774 /// Map of program counters used for state-caching to distinguish775 /// scheduling from non-deterministic choices.776 /// </summary>777 private readonly ConcurrentDictionary<ActorId, int> ProgramCounterMap;778 /// <summary>779 /// If true, the actor execution is controlled, else false.780 /// </summary>781 internal override bool IsExecutionControlled => true;782 /// <summary>783 /// Initializes a new instance of the <see cref="Mock"/> class.784 /// </summary>785 internal Mock(Configuration configuration, CoyoteRuntime runtime)786 : base(configuration, runtime)787 {788 this.ActorIds = new ConcurrentDictionary<ActorId, byte>();789 this.NameValueToActorId = new ConcurrentDictionary<string, ActorId>();790 this.ProgramCounterMap = new ConcurrentDictionary<ActorId, int>();791 }792 /// <inheritdoc/>793 public override ActorId CreateActorIdFromName(Type type, string name)794 {795 // It is important that all actor ids use the monotonically incrementing796 // value as the id during testing, and not the unique name.797 var id = this.NameValueToActorId.GetOrAdd(name, key => this.CreateActorId(type, key));798 this.ActorIds.TryAdd(id, 0);799 return id;800 }801 /// <inheritdoc/>802 public override ActorId CreateActor(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>803 this.CreateActor(null, type, null, initialEvent, eventGroup);804 /// <inheritdoc/>805 public override ActorId CreateActor(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>806 this.CreateActor(null, type, name, initialEvent, eventGroup);807 /// <inheritdoc/>808 public override ActorId CreateActor(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)809 {810 this.Assert(id != null, "Cannot create an actor using a null actor id.");811 return this.CreateActor(id, type, null, initialEvent, eventGroup);812 }813 /// <inheritdoc/>814 public override Task<ActorId> CreateActorAndExecuteAsync(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>815 this.CreateActorAndExecuteAsync(null, type, null, initialEvent, eventGroup);816 /// <inheritdoc/>817 public override Task<ActorId> CreateActorAndExecuteAsync(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>818 this.CreateActorAndExecuteAsync(null, type, name, initialEvent, eventGroup);819 /// <inheritdoc/>820 public override Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)821 {822 this.Assert(id != null, "Cannot create an actor using a null actor id.");823 return this.CreateActorAndExecuteAsync(id, type, null, initialEvent, eventGroup);824 }825 /// <summary>826 /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified827 /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event828 /// can only be used to access its payload, and cannot be handled.829 /// </summary>830 internal ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent = null, EventGroup eventGroup = null)831 {832 var creatorOp = this.Runtime.GetExecutingOperation<ActorOperation>();833 return this.CreateActor(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);834 }835 /// <summary>836 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.837 /// </summary>838 internal override ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent, Actor creator, EventGroup eventGroup)839 {840 this.AssertExpectedCallerActor(creator, "CreateActor");841 Actor actor = this.CreateActor(id, type, name, creator, eventGroup);842 this.OnActorEventHandlerStarted(actor.Id);843 this.RunActorEventHandler(actor, initialEvent, true, null);844 return actor.Id;845 }846 /// <summary>847 /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified848 /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event849 /// can only be used to access its payload, and cannot be handled. The method returns only850 /// when the actor is initialized and the <see cref="Event"/> (if any) is handled.851 /// </summary>852 internal Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent = null,853 EventGroup eventGroup = null)854 {855 var creatorOp = this.Runtime.GetExecutingOperation<ActorOperation>();856 return this.CreateActorAndExecuteAsync(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);857 }858 /// <summary>859 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>. The method860 /// returns only when the actor is initialized and the <see cref="Event"/> (if any)861 /// is handled.862 /// </summary>863 internal override async Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent,864 Actor creator, EventGroup eventGroup)865 {866 this.AssertExpectedCallerActor(creator, "CreateActorAndExecuteAsync");867 this.Assert(creator != null, "Only an actor can call 'CreateActorAndExecuteAsync': avoid calling " +868 "it directly from the test method; instead call it through a test driver actor.");869 Actor actor = this.CreateActor(id, type, name, creator, eventGroup);870 this.OnActorEventHandlerStarted(actor.Id);871 this.RunActorEventHandler(actor, initialEvent, true, creator);872 // Wait until the actor reaches quiescence.873 await creator.ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == actor.Id);874 return await Task.FromResult(actor.Id);875 }876 /// <summary>877 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.878 /// </summary>879 internal override Actor CreateActor(ActorId id, Type type, string name, Actor creator, EventGroup eventGroup)880 {881 this.Assert(type.IsSubclassOf(typeof(Actor)), "Type '{0}' is not an actor.", type.FullName);882 // Using ulong.MaxValue because a Create operation cannot specify883 // the id of its target, because the id does not exist yet.884 this.Runtime.ScheduleNextOperation(creator?.Operation, SchedulingPointType.Create);885 this.ResetProgramCounter(creator);886 if (id is null)887 {888 id = this.CreateActorId(type, name);889 this.ActorIds.TryAdd(id, 0);890 }891 else892 {893 if (this.ActorMap.ContainsKey(id))894 {895 throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");896 }897 this.Assert(id.Runtime is null || id.Runtime == this, "Unbound actor id '{0}' was created by another runtime.", id.Value);898 this.Assert(id.Type == type.FullName, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",899 id.Value, id.Type, type.FullName);900 id.Bind(this);901 }902 // If a group was not provided, inherit the current event group from the creator (if any).903 if (eventGroup is null && creator != null)904 {905 eventGroup = creator.EventGroup;906 }907 Actor actor = ActorFactory.Create(type);908 ActorOperation op = this.GetOrCreateActorOperation(id, actor);909 IEventQueue eventQueue = new MockEventQueue(actor);910 actor.Configure(this, id, op, eventQueue, eventGroup);911 actor.SetupEventHandlers();912 // This should always succeed, because it is either a new id or it has already passed913 // the assertion check, which still holds due to the schedule serialization during914 // systematic testing, but we still do the check defensively.915 if (!this.ActorMap.TryAdd(id, actor))916 {917 throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");918 }919 if (this.Configuration.IsActivityCoverageReported)920 {921 actor.ReportActivityCoverage(this.CoverageInfo);922 }...

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Actors.Timers;6using Microsoft.Coyote.Specifications;7using Microsoft.Coyote.Tasks;8using Microsoft.Coyote.TestingServices;9using Microsoft.Coyote.TestingServices.SchedulingStrategies;10using Microsoft.Coyote.TestingServices.SchedulingStrategies.DPOR;11using Microsoft.Coyote.TestingServices.SchedulingStrategies.Probabilistic;12using Microsoft.Coyote.TestingServices.SchedulingStrategies.RandomExecution;13using Microsoft.Coyote.TestingServices.SchedulingStrategies.StateExploration;14using Microsoft.Coyote.TestingServices.SchedulingStrategies.UnfairScheduling;15using Microsoft.Coyote.TestingServices.SchedulingStrategies.UnfairScheduling.Strategies;16using Microsoft.Coyote.TestingServices.Tracing.Schedule;17using Microsoft.Coyote.Tests.Common;18using Microsoft.Coyote.Tests.Common.Actors;19using Microsoft.Coyote.Tests.Common.Runtime;20using Microsoft.Coyote.Tests.Common.TestReporters;21using Microsoft.Coyote.Tests.Common.TestingServices;22using Microsoft.Coyote.Tests.Common.Utilities;23using Microsoft.Coyote.Tests.Tasks.Actors;24using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithSend;25using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWait;26using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAny;27using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAll;28using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAll;29using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndSend;30using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceive;31using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceiveAndSend;32using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceiveAndSendAndCreateActor;33using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceiveAndSendAndCreateActorAndReceive;34using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceiveAndSendAndCreateActorAndReceiveAndSend;35using Microsoft.Coyote.Tests.Tasks.Actors.TaskWithWaitAnyAllAndReceiveAndSendAndCreateActorAndReceiveAndSendAndCreateActor;

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Specifications;6using Microsoft.Coyote.Tasks;7{8 {9 static void Main(string[] args)10 {11 Console.WriteLine("Hello World!");12 Task.Run(async () =>13 {14 using (var runtime = RuntimeFactory.Create())15 {16 var actorRuntime = runtime.CreateActorRuntime();17 var id = new ActorId();18 var helloActor = await actorRuntime.GetOrCreateActorAsync<HelloActor>(id);19 await actorRuntime.SendEventAsync(helloActor, new HelloEvent());20 }21 }).GetAwaiter().GetResult();22 }23 }24 {25 }26 {27 [OnEventDoAction(typeof(HelloEvent), nameof(SayHello))]28 {29 }30 private void SayHello()31 {32 Console.WriteLine("Hello!");33 }34 }35}36using System;37using System.Threading.Tasks;38using Microsoft.Coyote;39using Microsoft.Coyote.Actors;40using Microsoft.Coyote.Specifications;41using Microsoft.Coyote.Tasks;42{43 {44 static void Main(string[] args)45 {46 Console.WriteLine("Hello World!");47 Task.Run(async () =>48 {49 using (var runtime = RuntimeFactory.Create())50 {51 var actorRuntime = runtime.CreateActorRuntime();52 var id = new ActorId();53 var helloActor = await actorRuntime.CreateActorAsync<HelloActor>(id);54 await actorRuntime.SendEventAsync(helloActor, new HelloEvent());

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Specifications;5{6 {7 public static void Main(string[] args)8 {9 var runtime = RuntimeFactory.Create();10 runtime.CreateActor(typeof(Actor1));11 runtime.Run();12 }13 }14 {15 protected override Task OnInitializeAsync(Event initialEvent)16 {17 this.CreateActor(typeof(Actor2));18 this.SendEvent(this.Id, new Event1());19 return Task.CompletedTask;20 }21 private Task OnEvent1ReceivedAsync(Event1 e)22 {23 this.SendEvent(this.Id, new Event2());24 return Task.CompletedTask;25 }26 private Task OnEvent2ReceivedAsync(Event2 e)27 {28 this.SendEvent(this.Id, new Event3());29 return Task.CompletedTask;30 }31 private Task OnEvent3ReceivedAsync(Event3 e)32 {33 this.SendEvent(this.Id, new Event4());34 return Task.CompletedTask;35 }36 private Task OnEvent4ReceivedAsync(Event4 e)37 {38 this.SendEvent(this.Id, new Event5());39 return Task.CompletedTask;40 }41 private Task OnEvent5ReceivedAsync(Event5 e)42 {43 this.SendEvent(this.Id, new Event6());44 return Task.CompletedTask;45 }46 private Task OnEvent6ReceivedAsync(Event6 e)47 {48 this.SendEvent(this.Id, new Event7());49 return Task.CompletedTask;50 }51 private Task OnEvent7ReceivedAsync(Event7 e)52 {53 this.SendEvent(this.Id, new Event8());54 return Task.CompletedTask;55 }56 private Task OnEvent8ReceivedAsync(Event8 e)57 {58 this.SendEvent(this.Id, new Event9());59 return Task.CompletedTask;60 }61 private Task OnEvent9ReceivedAsync(Event9 e)62 {63 this.SendEvent(this.Id, new Event10());64 return Task.CompletedTask;65 }66 private Task OnEvent10ReceivedAsync(Event10 e)67 {68 this.SendEvent(this.Id, new Event11());69 return Task.CompletedTask;70 }71 private Task OnEvent11ReceivedAsync(Event11 e)72 {73 this.SendEvent(this.Id, new Event12());74 return Task.CompletedTask;75 }76 private Task OnEvent12ReceivedAsync(Event12 e

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1{2 using Microsoft.Coyote.Actors;3 using System;4 using System.Threading.Tasks;5 {6 public static void Main(string[] args)7 {8 var runtime = RuntimeFactory.Create();9 runtime.CreateActor(typeof(MyActor));10 runtime.Run();11 }12 }13}14{15 using Microsoft.Coyote.Actors;16 using System;17 using System.Threading.Tasks;18 {19 public static void Main(string[] args)20 {21 var runtime = RuntimeFactory.Create();22 runtime.CreateActor(typeof(MyActor));23 runtime.Run();24 }25 }26}27{28 using Microsoft.Coyote.Actors;29 using System;30 using System.Threading.Tasks;31 {32 public static void Main(string[] args)33 {34 var runtime = RuntimeFactory.Create();35 runtime.CreateActor(typeof(MyActor));36 runtime.Run();37 }38 }39}40{41 using Microsoft.Coyote.Actors;42 using System;43 using System.Threading.Tasks;44 {45 public static void Main(string[] args)46 {47 var runtime = RuntimeFactory.Create();48 runtime.CreateActor(typeof(MyActor));49 runtime.Run();50 }51 }52}53{54 using Microsoft.Coyote.Actors;55 using System;56 using System.Threading.Tasks;57 {58 public static void Main(string[] args)59 {60 var runtime = RuntimeFactory.Create();61 runtime.CreateActor(typeof(MyActor));62 runtime.Run();63 }64 }65}

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Actors.Timers;5{6 {7 private static void Main(string[] args)8 {9 var runtime = RuntimeFactory.Create();10 var id = new ActorId();11 var actor = runtime.CreateActor(typeof(MyActor), id);12 runtime.SendEvent(id, new MyEvent());13 Console.ReadLine();14 }15 }16 {17 private readonly ActorId actorId;18 public MyActor(ActorId id)19 {20 this.actorId = id;21 }22 protected override Task OnInitializeAsync(Event initialEvent)23 {24 this.SendEvent(this.actorId, new MyEvent());25 return Task.CompletedTask;26 }27 }28 {29 }30}31using System;32using System.Threading.Tasks;33using Microsoft.Coyote.Actors;34using Microsoft.Coyote.Actors.Timers;35{36 {37 private static void Main(string[] args)38 {39 var runtime = RuntimeFactory.Create();40 var id = new ActorId();41 var actor = runtime.CreateActor(typeof(MyActor), id);42 runtime.SendEvent(id, new MyEvent());43 Console.ReadLine();44 }45 }46 {47 private readonly ActorId actorId;48 public MyActor(ActorId id)49 {50 this.actorId = id;51 }52 protected override Task OnInitializeAsync(Event initialEvent)53 {54 this.SendEvent(this.actorId, new MyEvent());55 return Task.CompletedTask;56 }57 }58 {59 }60}61using System;62using System.Threading.Tasks;63using Microsoft.Coyote.Actors;64using Microsoft.Coyote.Actors.Timers;65{66 {67 private static void Main(string[] args)68 {69 var runtime = RuntimeFactory.Create();70 var id = new ActorId();

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Specifications;5using Microsoft.Coyote.Tasks;6using Microsoft.Coyote.Testing;7using Microsoft.Coyote.TestingServices;8using Microsoft.Coyote.TestingServices.Runtime;9using Microsoft.Coyote.TestingServices.SchedulingStrategies;10using Microsoft.Coyote.TestingServices.Tracing.Schedule;11using Microsoft.Coyote.Tests.Common;12using Microsoft.Coyote.Tests.Common.Runtime;13using Microsoft.Coyote.Tests.Common.TestingServices;14using Microsoft.Coyote.Tests.Common.TestingServices.SchedulingStrategies;15using Microsoft.Coyote.Tests.Common.TestingServices.Tracing.Schedule;16using Microsoft.Coyote.Tests.Common.Utilities;17using Microsoft.Coyote.Tests.Common.Utilities.System;18using Microsoft.Coyote.Tests.Common.Utilities.System.Collections.Generic;19using Microsoft.Coyote.Tests.Common.Utilities.System.IO;20using Microsoft.Coyote.Tests.Common.Utilities.System.Threading;21using Microsoft.Coyote.Tests.Common.Utilities.System.Threading.Tasks;22using Microsoft.Coyote.Tests.Common.Utilities.System.Timers;23using Microsoft.Coyote.Tests.Common.Utilities.System.Xml;24using Microsoft.Coyote.Tests.Common.Utilities.System.Xml.Linq;25using Microsoft.Coyote.Tests.Common.Utilities.System.Xml.Serialization;26using Microsoft.Coyote.Tests.Common.Utilities.System.Linq;27using Microsoft.Coyote.Tests.Common.Utilities.System.Linq.Expressions;28using Microsoft.Coyote.Tests.Common.Utilities.System.Linq.Parallel;29using Microsoft.Coyote.Tests.Common.Utilities.System.Linq.Queryable;30using Microsoft.Coyote.Tests.Common.Utilities.System.Reflection;31using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.CompilerServices;32using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.InteropServices;33using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.InteropServices.WindowsRuntime;34using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.Serialization;35using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.Serialization.Json;36using Microsoft.Coyote.Tests.Common.Utilities.System.Runtime.Serialization.Xml;37using Microsoft.Coyote.Tests.Common.Utilities.System.Security;38using Microsoft.Coyote.Tests.Common.Utilities.System.Security.Cryptography;39using Microsoft.Coyote.Tests.Common.Utilities.System.Security.Cryptography.X509Certificates;40using Microsoft.Coyote.Tests.Common.Utilities.System.Security.Principal;41using Microsoft.Coyote.Tests.Common.Utilities.System.Text;42using Microsoft.Coyote.Tests.Common.Utilities.System.Text.RegularExpressions;43using Microsoft.Coyote.Tests.Common.Utilities.System.Threading.Channels;44using Microsoft.Coyote.Tests.Common.Utilities.System.Threading.Tasks.Dataflow;

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Actors.Timers;5using Microsoft.Coyote.Specifications;6{7 {8 private static void Main(string[] args)9 {10 var configuration = Configuration.Create();11 configuration.MaxSchedulingSteps = 100000;12 configuration.MaxFairSchedulingSteps = 100000;13 configuration.MaxStepsFromEntryToExit = 100000;14 configuration.EnableCycleDetection = true;15 configuration.EnableDataRaceDetection = true;16 configuration.EnableIntegerOverflowChecks = true;17 using (var runtime = RuntimeFactory.Create(configuration))18 {19 var a = runtime.CreateActor(typeof(A));20 runtime.SendEvent(a, new e());21 runtime.WaitCompletion(a);22 Console.WriteLine("Number of scheduling steps: {0}", runtime.GetSchedulingSteps());23 }24 }25 }26 {27 }28 {29 [OnEventDoAction(typeof(e), nameof(Foo))]30 {31 }32 private void Foo()33 {34 var b = this.Runtime.GetOrCreateActor(typeof(B), "B");35 this.SendEvent(b, new e());36 }37 }38 {39 [OnEventDoAction(typeof(e), nameof(Foo))]40 {41 }42 private void Foo()43 {44 var c = this.Runtime.GetOrCreateActor(typeof(C), "C");45 this.SendEvent(c, new e());46 }47 }48 {49 [OnEventDoAction(typeof(e), nameof(Foo))]50 {51 }52 private void Foo()53 {54 }55 }56}

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Specifications;5using Microsoft.Coyote.SystematicTesting;6{7 {8 public static void Main()9 {10 var runtime = RuntimeFactory.Create();11 var test = new SystematicTestingEngine(runtime);12 test.Run(async () =>13 {14 var actor = runtime.CreateActor(typeof(Actor1));15 await runtime.SendEventAsync(actor, new E());16 });17 }18 }19 {20 protected override Task OnInitializeAsync(Event initialEvent)21 {22 this.SendEvent(this.Id, new E());23 return Task.CompletedTask;24 }25 private Task OnEvent(Event e)26 {27 this.SendEvent(t

Full Screen

Full Screen

GetOrCreateActorOperation

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote;2using Microsoft.Coyote.Actors;3using Microsoft.Coyote.Actors.Timers;4using System;5{6 {7 public static void Main(string[] args)8 {9 using (var runtime = RuntimeFactory.Create())10 {11 var counterActor = runtime.CreateActor(typeof(Counter));12 runtime.SendEvent(counterActor, new Increment());13 runtime.Wait();14 }15 }16 }17 {18 }19 {20 private int count = 0;21 protected override Task OnInitializeAsync(Event initialEvent)22 {23 Console.WriteLine("Counter initialized");24 return Task.CompletedTask;25 }26 protected override Task OnEventAsync(Event e)27 {28 if (e is Increment)29 {30 count++;31 Console.WriteLine("Counter incremented to {0}", count);32 }33 return Task.CompletedTask;34 }35 }36}37using Microsoft.Coyote;38using Microsoft.Coyote.Actors;39using Microsoft.Coyote.Actors.Timers;40using System;41{42 {43 public static void Main(string[] args)44 {45 using (var runtime = RuntimeFactory.Create())46 {47 var counterActor = runtime.CreateActor(typeof(Counter));48 runtime.SendEvent(counterActor, new Increment());49 runtime.Wait();50 }51 }52 }53 {54 }55 {56 private int count = 0;57 protected override Task OnInitializeAsync(Event initialEvent)58 {59 Console.WriteLine("Counter initialized");60 return Task.CompletedTask;61 }62 protected override Task OnEventAsync(Event e)63 {64 if (e is Increment

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful