use rsfsm::event::Event; use rsfsm::lifecycle_object::LifecycleObject; use rsfsm::state::State; use rsfsm::state_machine::StateMachine; use rsfsm::transition::Transition; struct Light { pub state_machine: StateMachine, pub color: String, } impl LifecycleObject for Light { fn get_state_machine(&mut self) -> &mut StateMachine { &mut self.state_machine } fn get_data(&self) -> &Light { self } fn get_data_mut(&mut self) -> &mut Light { self } } fn test_state_machine() -> StateMachine { let state_off: State = "Off"; let state_on: State = "On"; let event_switch_on: Event = "SwitchOn"; let event_switch_off: Event = "SwitchOff"; let transitions = vec![ Transition { from_state: state_off, on_event: event_switch_on, to_state: state_on, }, Transition { from_state: state_on, on_event: event_switch_off, to_state: state_off, }, ]; StateMachine::new(state_off, transitions) } #[test] fn successfully_apply_event() { let mut light = Light { state_machine: test_state_machine(), color: "Yellow".to_string() }; assert_eq!(light.get_current_state(), "Off"); light.apply_event("SwitchOn").expect("Failed to apply event, but it should have succeeded"); assert_eq!(light.get_current_state(), "On"); } #[test] fn unsuccessfully_apply_event() { let mut light = Light { state_machine: test_state_machine(), color: "Yellow".to_string() }; assert_eq!(light.get_current_state(), "Off"); assert_eq!(light.apply_event("SwitchOff").is_err(), true); assert_eq!(light.get_current_state(), "Off"); } #[test] fn retrieve_data() { let mut light = Light { state_machine: test_state_machine(), color: "Yellow".to_string() }; assert_eq!(light.get_data().color, "Yellow"); assert_eq!(light.get_data_mut().color, "Yellow"); } #[test] fn modify_data() { let mut light = Light { state_machine: test_state_machine(), color: "Yellow".to_string() }; assert_eq!(light.get_data().color, "Yellow"); assert_eq!(light.get_data_mut().color, "Yellow"); light.get_data_mut().color = "Red".to_string(); assert_eq!(light.get_data().color, "Red"); assert_eq!(light.get_data_mut().color, "Red"); }