|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import asyncio |
| 8 | +from unittest.mock import MagicMock, patch |
| 9 | + |
| 10 | +import pytest |
| 11 | + |
| 12 | +import matrix |
| 13 | +from matrix.app_server.llm import query_llm |
| 14 | + |
| 15 | + |
| 16 | +def test_batch_requests_from_async_run(): |
| 17 | + """Test batch_requests called from within an asyncio.run context.""" |
| 18 | + mock_response = "mocked_response" |
| 19 | + |
| 20 | + async def mock_make_request_async(_url, _model, request): |
| 21 | + return f"{mock_response}_{request}" |
| 22 | + |
| 23 | + async def async_wrapper(): |
| 24 | + with patch( |
| 25 | + "matrix.app_server.llm.query_llm.make_request", |
| 26 | + side_effect=mock_make_request_async, |
| 27 | + ): |
| 28 | + requests = [1, 2, 3] |
| 29 | + # batch_requests should handle the async context internally |
| 30 | + # and return a list directly, not a task |
| 31 | + result = query_llm.batch_requests("", "", requests) |
| 32 | + |
| 33 | + # Verify it returned a list, not a task |
| 34 | + assert isinstance(result, list) |
| 35 | + assert len(result) == 3 |
| 36 | + assert result == [ |
| 37 | + f"{mock_response}_1", |
| 38 | + f"{mock_response}_2", |
| 39 | + f"{mock_response}_3", |
| 40 | + ] |
| 41 | + |
| 42 | + # Use asyncio.run to execute the async wrapper |
| 43 | + asyncio.run(async_wrapper()) |
| 44 | + |
| 45 | + |
| 46 | +def test_batch_requests_in_sync_context(): |
| 47 | + """Test batch_requests when called from a synchronous context.""" |
| 48 | + # Create a mock for make_request_async |
| 49 | + mock_response = "mocked_response" |
| 50 | + |
| 51 | + async def mock_make_request_async(_url, _model, request): |
| 52 | + return f"{mock_response}_{request}" |
| 53 | + |
| 54 | + with patch( |
| 55 | + "matrix.app_server.llm.query_llm.make_request", |
| 56 | + side_effect=mock_make_request_async, |
| 57 | + ): |
| 58 | + # Test with a list of requests |
| 59 | + requests = [1, 2, 3] |
| 60 | + result = query_llm.batch_requests("", "", requests) |
| 61 | + |
| 62 | + # Verify results |
| 63 | + assert len(result) == 3 |
| 64 | + assert result == [ |
| 65 | + f"{mock_response}_1", |
| 66 | + f"{mock_response}_2", |
| 67 | + f"{mock_response}_3", |
| 68 | + ] |
| 69 | + |
| 70 | + |
| 71 | +def test_batch_requests_empty_list(): |
| 72 | + """Test batch_requests with an empty list.""" |
| 73 | + with patch("matrix.app_server.llm.query_llm.make_request") as mock_request: |
| 74 | + result = query_llm.batch_requests("", "", []) |
| 75 | + # make_request_async should not be called |
| 76 | + mock_request.assert_not_called() |
| 77 | + # Result should be an empty list |
| 78 | + assert result == [] |
0 commit comments