Test the find_available_port utility function.
| 304 | |
| 305 | |
| 306 | class TestFindAvailablePort: |
| 307 | """Test the find_available_port utility function.""" |
| 308 | |
| 309 | def test_find_available_port_success(self): |
| 310 | """Test finding an available port.""" |
| 311 | # This should succeed as it tests real socket binding |
| 312 | port = find_available_port(8080, max_attempts=5) |
| 313 | assert isinstance(port, int) |
| 314 | assert 8080 <= port < 8085 |
| 315 | |
| 316 | @patch('socket.socket') |
| 317 | def test_find_available_port_all_busy(self, mock_socket_class): |
| 318 | """Test when all ports in range are busy.""" |
| 319 | mock_socket = Mock() |
| 320 | mock_socket_class.return_value.__enter__.return_value = mock_socket |
| 321 | mock_socket.bind.side_effect = OSError("Port in use") |
| 322 | |
| 323 | # Should return the start port as fallback |
| 324 | port = find_available_port(8080, max_attempts=3) |
| 325 | assert port == 8080 |
| 326 | |
| 327 | @patch('socket.socket') |
| 328 | def test_find_available_port_second_attempt(self, mock_socket_class): |
| 329 | """Test finding port on second attempt.""" |
| 330 | mock_socket = Mock() |
| 331 | mock_socket_class.return_value.__enter__.return_value = mock_socket |
| 332 | |
| 333 | # First call fails, second succeeds |
| 334 | mock_socket.bind.side_effect = [OSError("Port in use"), None] |
| 335 | |
| 336 | port = find_available_port(8080, max_attempts=3) |
| 337 | assert port == 8081 |
| 338 | |
| 339 | |
| 340 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected