"""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

[((426, 432), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (430, 432), False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((924, 985), 'pyhap.hap_server.HAPServer', 'hap_server.HAPServer', (['server_addr', 'amock'], {'handler_type': 'raises'}), '(server_addr, amock, handler_type=raises)\n', (944, 985), False, 'from pyhap import hap_server\n'), ((1226, 1300), 'pyhap.hap_server.HAPServer', 'hap_server.HAPServer', (['server_addr', 'amock'], {'handler_type': '(lambda *args: 1 / 0)'}), '(server_addr, amock, handler_type=lambda *args: 1 / 0)\n', (1246, 1300), False, 'from pyhap import hap_server\n'), ((901, 910), 'socket.timeout', 'timeout', ([], {}), '()\n', (908, 910), False, 'from socket import timeout\n'), ((1389, 1413), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (1402, 1413), False, 'import pytest\n'), ((207, 218), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (216, 218), False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((277, 288), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (286, 288), False, 'from unittest.mock import Mock, MagicMock, patch\n'), ((664, 675), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (673, 675), False, 'from unittest.mock import Mock, MagicMock, patch\n')]