import unittest
class Turnstile:
def __init__(self):
self.state = 'Locked'
def insert_coin(self):
if self.state == 'Locked':
self.state = 'Unlocked'
def push(self):
if self.state == 'Unlocked':
self.state = 'Locked'
class TestTurnstileStateTransitions(unittest.TestCase):
def setUp(self):
self.turnstile = Turnstile()
def test_state_transitions(self):
# Initial state
self.assertEqual(self.turnstile.state, 'Locked')
# Insert coin unlocks
self.turnstile.insert_coin()
self.assertEqual(self.turnstile.state, 'Unlocked')
# Push locks again
self.turnstile.push()
self.assertEqual(self.turnstile.state, 'Locked')
# Push again stays locked
self.turnstile.push()
self.assertEqual(self.turnstile.state, 'Locked')
# Insert coin unlocks again
self.turnstile.insert_coin()
self.assertEqual(self.turnstile.state, 'Unlocked')
if __name__ == '__main__':
unittest.main()This test uses a simple Turnstile class to model the states Locked and Unlocked.
The insert_coin method changes the state from Locked to Unlocked only.
The push method changes the state from Unlocked to Locked only.
The test case test_state_transitions checks the initial state, then simulates inserting a coin and pushing the turnstile, verifying the state changes after each action.
Assertions confirm the state is exactly as expected after each step, ensuring the state machine behaves correctly.