示例#1
0
 public override void SetUp()
 {
     textDiscriminator = CreateMock<ITextDiscriminator>();
     console = CreateMock<IConsoleFacade>();
     player = CreateMock<IStateMachine>();
     informationDisplayer = CreateMock<IInformationDisplayer>();
 }
        public FollowerRoleTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();
            builder.Provide<ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide<IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve<ISettings>();
            this.settings.ApplyEntriesOnFollowers.Returns(true);
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve<IRandom>();
            this.random.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(RiggedRandomResult);

            this.coordinator = builder.Resolve<IRoleCoordinator<int>>();
            this.stateMachine = builder.Resolve<IStateMachine<int>>();

            this.timers = new MockTimers();
            builder.Provide<RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf<InMemoryLog<int>>();
            builder.Provide<IPersistentLog<int>>(this.journal);

            // After the container is configured, resolve required services.
            this.role = builder.Resolve<FollowerRole<int>>();
        }
示例#3
0
文件: Program.cs 项目: silpheed/M
        //testable main
        public static void Run(IEnumerable<string> args, ITextDiscriminator textDiscriminator, IConsoleFacade console, IStateMachine player, IInformationDisplayer informationDisplayer)
        {
            //once off construction of input from execution args
            string input = String.Empty;
            if (args != null)
                foreach (String s in args)
                    input += s + " ";

            //main loop
            bool exit = false;
            while (!exit) {
                foreach (ICommand command in textDiscriminator.Interpret(input.Trim()))
                {
                    //ignore
                    if (command.CommandType == CommandType.Ignore)
                        continue;
                    //quit
                    if ((command.CommandType == CommandType.Exit) || ((command.CommandType == CommandType.Stop) && (player.IsStopped)))
                        exit = true;
                    //everything else is fair game
                    informationDisplayer.ProcessCommand(command);
                    player.ProcessCommand(command);
                }
                if (!exit)
                    input = console.ReadLine();
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stateMachine">Interface to the state machine.</param>
        /// <exception cref="TimeoutException">Thrown if failing to connect to Remote Recoder. Service may not run.</exception>
        public RemoteRecorderSync(IStateMachine stateMachine)
        {
            // This waits for RR to start.
            this.SetUpController();

            this.stateMachine = stateMachine;

            // Get the current remote recorder version number
            // This should succeed because SetUpController has confirmed the service is up.
            Process process = Process.GetProcessesByName(RemoteRecorderSync.RemoteRecorderProcessName).FirstOrDefault();
            if (process == null)
            {
                throw new ApplicationException("Remote recoder process is not running.");
            }

            try
            {
                AssemblyName an = AssemblyName.GetAssemblyName(process.MainModule.FileName);
                this.SupportsStartNewRecording = (an.Version.CompareTo(Version.Parse("5.0")) >= 0);
            }
            catch (System.ComponentModel.Win32Exception)
            {
                // This may happen if this service runs without admin privilege.
                Trace.TraceInformation("Assembly information of Remote Recoder is not available. Assuming 5.0.0+.");
                this.SupportsStartNewRecording = true;
            }

            // Start background thread to monitor the recorder state.
            this.stateMonitorThread = new Thread(StateMonitorLoop);
            this.stateMonitorThreadToStop = new ManualResetEvent(initialState: false);
            this.stateMonitorThread.Start();
        }
示例#5
0
 public void Apply(IStateMachine stateMachine)
 {
     if (_transfer.Fade)
         PushFade(stateMachine);
     else
         PushImmediate(stateMachine);
 }
 internal TransitionNotFoundException(IState from, IEvent @event, IStateMachine stateMachine)
     : base(String.Format("Could not find a transition which we could invoke from state {0} (or any of its children) on event {1}", from.Name, @event.Name))
 {
     this.From = from;
     this.Event = @event;
     this.StateMachine = stateMachine;
 }
 public SequenceStateMachineTests()
 {
     _repository = Substitute.For<IWorkItemRepository>();
     _workItemBuilder = Substitute.For<IWorkItemBuilder>();
     _engine = Substitute.For<IEngine>();
     _stateMachine = new SequenceStateMachine(_repository, _workItemBuilder);
 }
 /// <summary>
 ///   //when showing the search panel, ensure the working panel is in the home position?
 /// </summary>
 public static void Show(LucidState state, IStateMachine<LucidState> stateMachine, dynamic args)
 {
     //       search panel search tab         home panel         root
     stateMachine.Parent.Parent.Parent.Children["WorkingPanel"].TriggerTransition(
         new WorkingPanelState.SearchMode());
     stateMachine.Parent.Parent.Parent.Children["DetailsPanels"].TriggerTransition(
         new DetailsPanelsState.SearchMode());
 }
示例#9
0
		private bool CanChangeStatus(string oldStatus, string newStatus, IStateMachine<string> stateMachine)
		{
			var retVal = string.IsNullOrEmpty(oldStatus)
			             || (oldStatus != newStatus
			                 && stateMachine.IsTransitionAvailable(oldStatus, newStatus));

			return retVal;
		}
示例#10
0
 public AppViewModel(IStateMachine<States,Events> stateMachine, CheckEngine engine, IConfigurationRepository repository)
 {
     StateMachine = stateMachine;
     this.repository = repository;
     
     SelectConfigurationCommand = new RelayCommand(SelectConfiguration, () => stateMachine.CanFire(Events.SelectConfigurationSource));
     RunChecksCommand = new RelayCommand(RunChecks, () => stateMachine.CanFire(Events.RunChecks));
 }
        public ConditionalOnAutomation WithActuator(IStateMachine actuator)
        {
            if (actuator == null) throw new ArgumentNullException(nameof(actuator));

            WithActionIfConditionsFulfilled(actuator.GetTurnOnAction());
            WithActionIfConditionsNotFulfilled(actuator.GetTurnOffAction());

            return this;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public DelcomLight(IStateMachine stateMachine)
        {
            if (stateMachine == null)
            {
                throw new ArgumentException("stateMachine cannot be null.");
            }

            this.stateMachine = stateMachine;
        }
        public static IButton ConnectToggleActionWith(this IButton button, IStateMachine actuator, ButtonPressedDuration pressedDuration = ButtonPressedDuration.Short)
        {
            if (actuator == null) throw new ArgumentNullException(nameof(actuator));
            if (button == null) throw new ArgumentNullException(nameof(button));

            ConnectToggleAction(button, actuator, pressedDuration);

            return button;
        }
示例#14
0
 private void PushImmediate(IStateMachine stateMachine)
 {
     if (_transfer.Pause)
     {
         stateMachine.PauseTopOfStack();
         stateMachine.PauseDrawingTopOfStack();
     }
     stateMachine.StartHandler(_transfer);
 }
示例#15
0
        public void Apply(IStateMachine stateMachine)
        {
            stateMachine.RemoveAllEndHandlers();

            if (_transfer.Fade)
                Engine.Instance.FadeTransition(() => EmptyStackAndStart(stateMachine));
            else
                EmptyStackAndStart(stateMachine);
        }
示例#16
0
 internal StateMachine(
     [NotNull] IJobFilterProvider filterProvider, 
     [NotNull] IStateMachine innerStateMachine)
 {
     if (filterProvider == null) throw new ArgumentNullException(nameof(filterProvider));
     if (innerStateMachine == null) throw new ArgumentNullException(nameof(innerStateMachine));
     
     _filterProvider = filterProvider;
     _innerStateMachine = innerStateMachine;
 }
示例#17
0
        public Controller(IStateMachine stateMachine, ICommandChannel commandChannel)
        {
            if (stateMachine == null) throw new ArgumentNullException("stateMachine");
            if (commandChannel == null) throw new ArgumentNullException("commandChannel");

            _stateMachine = stateMachine;
            _commandChannel = commandChannel;

            CurrentState = _stateMachine.StartingState;
        }
 internal StateMachineFaultInfo(IStateMachine stateMachine, FaultedComponent faultedComponent, Exception exception, IState from, IState to, IEvent @event, IStateGroup group = null)
 {
     this.StateMachine = stateMachine;
     this.FaultedComponent = faultedComponent;
     this.Exception = exception;
     this.From = from;
     this.To = to;
     this.Event = @event;
     this.Group = group;
 }
        public ForkStateMachineTests()
        {
            _repository = Substitute.For<IWorkItemRepository>();
            _workItemBuilder = Substitute.For<IWorkItemBuilder>();
            _workflowPathNavigator = Substitute.For<IWorkflowPathNavigator>();
            _dataStore = Substitute.For<IDataStore>();

            _stateMachine = new ForkStateMachine(_repository, _workItemBuilder, _workflowPathNavigator, _dataStore);
            _engine = Substitute.For<IEngine>();
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="StateMachineDotPrinter"/> class
 /// </summary>
 /// <param name="stateMachine">State machine to print</param>
 public StateMachineDotPrinter(IStateMachine stateMachine)
 {
     this.stateMachine = stateMachine;
     this.Colors = new List<string>()
     {
         "#0075dc", "#993f00", "#4c005c", "#191919", "#005c31", "#2bce48", "#808080", "#8f7c00", "#c20088", "#ffa405", "#ffa8bb",
         "#426600", "#ff0010", "#00998f", "#740aff", "#990000", "#ff5005", "#4d4d4d", "#5da5da", "#faa43a", "#60bd68", "#f17cb0",
         "#b2912f", "#b276b2", "#f15854"
     };
 }
 public void SetUp()
 {
     _stateMachine = StateMachineFactory.Create(TeleponeStatus.OffHook);
     _stateMachine.Permit(TeleponeStatus.OffHook, TeleponeStatus.Ringing, (t => _ringingCalled = true ))
                 .Permit(TeleponeStatus.Ringing, TeleponeStatus.OffHook)
                 .Permit(TeleponeStatus.Ringing, TeleponeStatus.Connected)
                 .Permit(TeleponeStatus.Connected, TeleponeStatus.OffHook)
                 .Permit(TeleponeStatus.Connected, TeleponeStatus.OnHold)
                 .Permit(TeleponeStatus.OnHold, TeleponeStatus.Connected)
                 .Permit(TeleponeStatus.OnHold, TeleponeStatus.OffHook);
 }
        public VhptController(IVhpt vhpt, IStateMachine<VhptStates, VhptEvents> stateMachine, JokeTelling.IJokeTeller jokeTeller)
        {
            this.vhpt = vhpt;
            this.stateMachine = stateMachine;
            this.jokeTeller = jokeTeller;

            this.vhptIdentification = new VhptIdentification(this.vhpt.Id, this.vhpt.Name);

            this.RegisterVhptEvents();
            this.InitialzeStateMachine();
        }
 public void CreateMachine()
 {
     machine = StateMachine.Create<Transitions, TransitionHandler>();
     machine.AddTransition(null, State<FirstState,Transitions>.Instance, Transitions.Start);
     machine.AddTransition(State<FirstState, Transitions>.Instance, State<SecondState, Transitions>.Instance, Transitions.Okay);
     machine.AddTransition(State<FirstState, Transitions>.Instance, State<ThirdState, Transitions>.Instance, Transitions.Error);
     machine.AddTransition(State<SecondState, Transitions>.Instance, null, Transitions.NormalExit);
     machine.AddTransition(State<ThirdState, Transitions>.Instance, State<FinalState, Transitions>.Instance, Transitions.CalculateErrorCode);
     machine.AddTransition(State<FinalState, Transitions>.Instance, null, Transitions.ExitWithErrorCode);
     
 }
        public TransitionPolicyControllerContext(IStateMachine stateMachine, IStateTransition currentTransition, ICredential credentialToApprov)
        {
            stateMachine.TestForArgumentNull();
            ControledMachine = stateMachine;

            currentTransition.TestForArgumentNull();
            _currentTransition = currentTransition;

            credentialToApprov.TestForArgumentNull();
            _credentialToApprov = credentialToApprov;
        }
示例#25
0
 public DoorSensor(
     IVhptDoor door, 
     IStateMachine<States, Events> stateMachine, 
     IAsynchronousFileLogger fileLogger,
     IVhptTravelCoordinator travelCoordinator,
     IEvaluationEngine evaluationEngine)
 {
     this.door = door;
     this.stateMachine = stateMachine;
     this.fileLogger = fileLogger;
     this.travelCoordinator = travelCoordinator;
     this.evaluationEngine = evaluationEngine;
 }
示例#26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Region"/> class.
        /// </summary>
        /// <param name="context">The <see cref="IStateMachine"/> this region belongs to.</param>
        /// <exception cref="ArgumentNullException"><paramref name="context"/> is a <see langword="null"/> reference.</exception>
        /// <exception cref="ArgumentException">Is thrown when this region is already associated.</exception>
        public Region(IStateMachine context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (stateContext != null)
            {
                throw new ArgumentException("This region is already associated to a state.", "context");
            }

            this.stateMachineContext = context;
        }
示例#27
0
        private void PopFade(IStateMachine stateMachine)
        {
            stateMachine.FinalizeTopHandler();

            Engine.Instance.FadeTransition(() =>
            {
                stateMachine.RemoveTopHandler();
                stateMachine.ResumeDrawingTopOfStack();
            },
            () =>
            {
                stateMachine.ResumeTopOfStack();
            });
        }
示例#28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PseudoState"/> class.
        /// </summary>
        /// <param name="kind">The kind or type of Pseudo state.</param>
        /// <param name="context">The associated state machine to this pseudo state.</param>
        /// <exception cref="ArgumentNullException"><paramref name="context"/> is a <see langword="null"/> reference.</exception>
        /// <exception cref="ArgumentException">Is thrown when the <paramref name="kind"/> is not of type Entry or Exit point.</exception>
        public PseudoState(PseudoStateKind kind, IStateMachine context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (kind != PseudoStateKind.EntryPoint || kind != PseudoStateKind.ExitPoint)
            {
                throw new ArgumentException("Kind of pseudo state must be of type EntryPoint or ExitPoint.");
            }

            this.kind = kind;
            this.statemachine = context;
        }
 private static void ConnectToggleAction(IButton button, IStateMachine actuator, ButtonPressedDuration pressedDuration)
 {
     if (pressedDuration == ButtonPressedDuration.Short)
     {
         button.GetPressedShortlyTrigger().Attach(actuator.GetSetNextStateAction());
     }
     else if (pressedDuration == ButtonPressedDuration.Long)
     {
         button.GetPressedLongTrigger().Attach(actuator.GetSetNextStateAction());
     }
     else
     {
         throw new NotSupportedException();
     }
 }
示例#30
0
        public void Report(
            IStateMachine<string, int> machine,
            IStateMachineReport<string, int> report)
        {
            "establish a state machine"._(() =>
                machine = new PassiveStateMachine<string, int>());

            "establish a state machine reporter"._(() =>
                report = A.Fake<IStateMachineReport<string, int>>());

            "when creating a report"._(() =>
                machine.Report(report));

            "it should call the passed reporter"._(() =>
                A.CallTo(() => report.Report(A<string>._, A<IEnumerable<IState<string, int>>>._, A<Initializable<string>>._)));
        }
示例#31
0
 internal BackgroundJobStateChanger([NotNull] IJobFilterProvider filterProvider, [NotNull] IStateMachine stateMachine)
 {
     _innerStateMachine = stateMachine ?? throw new ArgumentNullException(nameof(stateMachine));
     _stateMachine      = new StateMachine(filterProvider, stateMachine);
 }
示例#32
0
 public EndpointLoader(IStateMachine <PreloadStateTrigger> machine) : base(machine)
 {
 }
示例#33
0
 protected StatePropertyEventArgsBase(IStateMachine stateMachine)
 {
     StateMachine = stateMachine;
 }
 public void Handle(IStateMachine <string, IGameSectorLayerService> machine)
 {
     machine.SharedContext.DataLayer.ImageData = new ConcurrentBag <ImageData>(
         machine.SharedContext.DataLayer.ImageData.Except(
             machine.SharedContext.DataLayer.ImageData.Where(img => Remove.Contains(img.SelectedFrame))).ToList());
 }
示例#35
0
 public bool Enter(IStateMachine <L, V> stateMachine)
 {
     return(Begin(stateMachine));
 }
示例#36
0
 public ValueTask <DataModelValue> ExecuteStateMachineAsync(IStateMachine stateMachine, string sessionId, DataModelValue parameters = default) =>
 ExecuteStateMachineWrapper(SessionId.FromString(sessionId), new StateMachineOrigin(stateMachine), parameters);
示例#37
0
 public void OnLeaving(IStateMachine <TState, TAction> machine, StateLeavingEventArgs <TState, TAction> e)
 {
     this.Leaving?.Invoke(machine, e);
 }
示例#38
0
 public override void Init(IStateMachine stateMachine)
 {
     base.Init(stateMachine);
     positiveGameObject = views.FirstOrDefault(x => x.Id == "PositiveButton")?.GetTransform().gameObject;
 }
示例#39
0
 public void SetOwner(IStateMachine <TKey> owner)
 {
     _owner = owner;
 }
示例#40
0
            public Task <IStateMachine <GetRequest, PutRequest <T>, T> > ApplyAsync(PutRequest <T> operation)
            {
                IStateMachine <GetRequest, PutRequest <T>, T> stateMachine = this;

                return(Task.FromResult(stateMachine));
            }
 private void PopImmediate(IStateMachine stateMachine)
 {
     stateMachine.RemoveTopHandler();
     stateMachine.ResumeTopOfStack();
 }
示例#42
0
 public override void Init(IStateMachine stateMachine)
 {
     base.Init(stateMachine);
     EventBinder("BTNRetry", Restart);
 }
示例#43
0
 public BathroomFanAutomation WithActuator(IStateMachine actuator)
 {
     _actuator = actuator;
     return(this);
 }
示例#44
0
 public StatePropertyEventArgs(IStateMachine stateMachine) : base(stateMachine)
 {
 }
示例#45
0
 public ValueTask <IStateMachineController> StartStateMachineAsync(IStateMachine stateMachine,
                                                                   Uri?baseUri,
                                                                   string sessionId,
                                                                   DataModelValue parameters = default) =>
 StartStateMachineWrapper(SessionId.FromString(sessionId), new StateMachineOrigin(stateMachine, baseUri), parameters);
示例#46
0
 public AtivaFonte(IStateMachine g) : base(g)
 {
 }
示例#47
0
 public ValueTask <IStateMachineController> StartStateMachineAsync(IStateMachine stateMachine, DataModelValue parameters = default) =>
 StartStateMachineWrapper(SessionId.New(), new StateMachineOrigin(stateMachine), parameters);
示例#48
0
 protected Stateful(IStateMachine <TState, TTransitionActionStatus> stateMachine)
 {
     StateMachine = stateMachine;
 }
示例#49
0
 public ValueTask <DataModelValue> ExecuteStateMachineAsync(IStateMachine stateMachine, Uri?baseUri, DataModelValue parameters = default) =>
 ExecuteStateMachineWrapper(SessionId.New(), new StateMachineOrigin(stateMachine, baseUri), parameters);
示例#50
0
        public void Continue()
        {
            IStateMachine stateMachine = _context.Get <IStateMachine>();

            stateMachine.ChangeState <CreatePartyState>();
        }
示例#51
0
 public void OnEntered(IStateMachine <TState, TAction> machine, StateEnteredEventArgs <TState, TAction> e)
 {
     this.Entered?.Invoke(machine, e);
 }
示例#52
0
 protected Stateful(
     IStateMachine <TState> stateMachine)
 {
     StateMachine = stateMachine;
 }
示例#53
0
 public void Handle(IStateMachine <string, IGameSectorLayerService> machine)
 {
     Execute(machine.SharedContext);
 }
示例#54
0
 public StateMachineEvent(IStateMachine stateMachine, string eventName) : this(stateMachine, eventName, null)
 {
 }
示例#55
0
 /// <summary>
 /// Called when the action begins operation
 /// </summary>
 /// <param name="stateMachine">The AI agent's state machine</param>
 /// <returns>True if the action successfully began</returns>
 protected abstract bool Begin(IStateMachine <L, V> stateMachine);
示例#56
0
 public StateMachineEvent(IStateMachine parent, string eventName, object eventIdentifier) : base(parent)
 {
     EventName       = eventName;
     EventIdentifier = eventIdentifier ?? eventName;
 }
示例#57
0
 private bool IsValid(IStateMachine stateMachine, ChoiceActionItem item)
 {
     return(_stateMachineController.ChangeStateActionItemsMode == ChangeStateActionItemsMode.GroupByStateMachine? item.Data == stateMachine
         : ((ITransition)item.Data).TargetState.StateMachine == stateMachine);
 }
示例#58
0
 private ChoiceActionItem GetStateMachineChoiceActionItem(IStateMachine stateMachine)
 {
     return(_stateMachineController.ChangeStateAction.Items.GetItems <ChoiceActionItem>(item => item.Items).FirstOrDefault(
                item => IsAvailable(item) && IsValid(stateMachine, item)));
 }
示例#59
0
 public StatePropertyFilterEditorItemsEventArgs(IStateMachine stateMachine, PropertyEditor propertyEditor) : base(stateMachine)
 {
     PropertyEditor = propertyEditor;
 }
示例#60
0
 public BaseStrategy(T owner)
 {
     this.owner   = owner;
     stateMachine = owner.StateMachine;
 }