"""Tests for the HAPServer."""
from socket import timeout
from unittest.mock import Mock, MagicMock, patch

import pytest

from pyhap import hap_server


@patch('pyhap.hap_server.HAPServer.server_bind', new=MagicMock())
@patch('pyhap.hap_server.HAPServer.server_activate', new=MagicMock())
def test_finish_request_pops_socket():
    """Test that ``finish_request`` always clears the connection after a request."""
    amock = Mock()
    client_addr = ('192.168.1.1', 55555)
    server_addr = ('', 51826)

    # Positive case: The request is handled
    server = hap_server.HAPServer(server_addr, amock,
                                  handler_type=lambda *args: MagicMock())

    server.connections[client_addr] = amock
    server.finish_request(amock, client_addr)

    assert len(server.connections) == 0

    # Negative case: The request fails with a timeout
    def raises(*args):
        raise timeout()
    server = hap_server.HAPServer(server_addr, amock,
                                  handler_type=raises)
    server.connections[client_addr] = amock
    server.finish_request(amock, client_addr)

    assert len(server.connections) == 0

    # Negative case: The request raises some other exception
    server = hap_server.HAPServer(server_addr, amock,
                                  handler_type=lambda *args: 1 / 0)
    server.connections[client_addr] = amock

    with pytest.raises(Exception):
        server.finish_request(amock, client_addr)

    assert len(server.connections) == 0

[((14, 12, 14, 18), 'unittest.mock.Mock', 'Mock', ({}, {}), '()', False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((30, 13, 31, 54), 'pyhap.hap_server.HAPServer', 'hap_server.HAPServer', (), '', False, 'from pyhap import hap_server\n'), ((38, 13, 39, 67), 'pyhap.hap_server.HAPServer', 'hap_server.HAPServer', (), '', False, 'from pyhap import hap_server\n'), ((29, 14, 29, 23), 'socket.timeout', 'timeout', ({}, {}), '()', False, 'from socket import timeout\n'), ((42, 9, 42, 33), 'pytest.raises', 'pytest.raises', ({(42, 23, 42, 32): 'Exception'}, {}), '(Exception)', False, 'import pytest\n'), ((10, 53, 10, 64), 'unittest.mock.MagicMock', 'MagicMock', ({}, {}), '()', False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((11, 57, 11, 68), 'unittest.mock.MagicMock', 'MagicMock', ({}, {}), '()', False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((20, 61, 20, 72), 'unittest.mock.MagicMock', 'MagicMock', ({}, {}), '()', False, 'from unittest.mock import Mock, MagicMock, patch\n')]