def test_leader_removed():
    node = GateNode(nodes[0], [nodes[1], nodes[2]], visitor_repository)
    node.leader = nodes[5]

    assert list(node.process_message(NetworkMessage('leader_removed', nodes[1], nodes[0]))) == \
        [NetworkMessage('leader_removed', nodes[0], nodes[2])]
    assert node.leader is None
def test_request_mutex(visitor_repository):
    node = GateNode(nodes[0], [], visitor_repository)
    node.leader = nodes[0]

    assert list(node.process_message(NetworkMessage('mutex_requested', nodes[1], nodes[0]))) == \
        [NetworkMessage('mutex_granted', nodes[0], nodes[1])]
    assert node.mutex_holder == nodes[1]
    assert not node.mutex_queue

    assert list(node.process_message(NetworkMessage('mutex_requested', nodes[2], nodes[0]))) == []
    assert node.mutex_queue == [nodes[2]]

    assert list(node.process_message(NetworkMessage('mutex_requested', nodes[3], nodes[0]))) == []
    assert node.mutex_queue == [nodes[2], nodes[3]]

    assert list(node.process_message(NetworkMessage('mutex_released', nodes[1], nodes[0]))) == \
        [NetworkMessage('mutex_granted', nodes[0], nodes[2])]
    assert node.mutex_holder == nodes[2]
    assert node.mutex_queue == [nodes[3]]

    assert list(node.process_message(NetworkMessage('mutex_released', nodes[2], nodes[0]))) == \
        [NetworkMessage('mutex_granted', nodes[0], nodes[3])]
    assert node.mutex_holder == nodes[3]
    assert node.mutex_queue == []

    assert list(node.process_message(NetworkMessage('mutex_released', nodes[3], nodes[0]))) == []
    assert node.mutex_holder is None
    assert node.mutex_queue == []
def test_leave_request(visitor_repository):
    visitor_repository.write_state(State(capacity=1, visitors=[nodes[1].id]))

    node = GateNode(nodes[0], [], visitor_repository)
    node.leader = nodes[5]

    assert list(node.process_message(NetworkMessage('leave_request', nodes[1], nodes[0]))) == \
        [NetworkMessage('mutex_requested', nodes[0], nodes[5])]
    assert node.leave_queue == [nodes[1]]

    assert list(node.process_message(NetworkMessage('leave_request', nodes[2], nodes[0]))) == []
    assert node.leave_queue == [nodes[1], nodes[2]]

    assert list(node.process_message(NetworkMessage('mutex_granted', nodes[5], nodes[0]))) == \
        [NetworkMessage('leave_response', nodes[0], nodes[1], allowed=True),
            NetworkMessage('leave_response', nodes[0], nodes[2], allowed=False),
            NetworkMessage('mutex_released', nodes[0], nodes[5])]
    assert node.leave_queue == []

    assert list(node.process_message(NetworkMessage('leave_request', nodes[3], nodes[0]))) == \
        [NetworkMessage('mutex_requested', nodes[0], nodes[5])]
    assert node.leave_queue == [nodes[3]]