nullcount / rain

Evaporate stagnant liquidity from source nodes and condensate to sinks. Make it rain.
MIT License
2 stars 5 forks source link

Channel Manager State Machine with Tests #59

Closed nullcount closed 1 year ago

nullcount commented 1 year ago

example:

import unittest

class StateMachine:
    def __init__(self, initial_state):
        self.state = initial_state

    def transition(self, event):
        self.state = self.state.transition(event)

class State:
    def transition(self, event):
        raise NotImplementedError

class InitialState(State):
    def transition(self, event):
        if event == "start":
            return StartedState()
        return self

class StartedState(State):
    def transition(self, event):
        if event == "stop":
            return StoppedState()
        return self

class StoppedState(State):
    def transition(self, event):
        if event == "start":
            return StartedState()
        return self

class TestStateMachine(unittest.TestCase):
    def test_state_machine(self):
        machine = StateMachine(InitialState())

        # Test initial state
        self.assertEqual(machine.state.__class__, InitialState)

        # Test transition to StartedState
        machine.transition("start")
        self.assertEqual(machine.state.__class__, StartedState)

        # Test transition to StoppedState
        machine.transition("stop")
        self.assertEqual(machine.state.__class__, StoppedState)

        # Test transition back to StartedState
        machine.transition("start")
        self.assertEqual(machine.state.__class__, StartedState)

if __name__ == "__main__":
    unittest.main()