|
| 1 | +import sys |
| 2 | +from unittest.mock import MagicMock, patch |
| 3 | + |
| 4 | +# We need to import the function to test |
| 5 | +from agent_engine_cli.chat import _install_api_logging_hooks |
| 6 | + |
| 7 | +def test_install_api_logging_hooks_idempotency(): |
| 8 | + """Test that _install_api_logging_hooks does not double-patch.""" |
| 9 | + |
| 10 | + # We need to mock google.genai._api_client because it might not be installed in all environments |
| 11 | + # or we want to isolate the test. |
| 12 | + # However, since the code imports it directly, we need to mock it in sys.modules |
| 13 | + # OR we can rely on the fact that we are in an environment where it is installed. |
| 14 | + # Given the previous exploration, it is installed. |
| 15 | + |
| 16 | + from google.genai import _api_client |
| 17 | + |
| 18 | + # Save original state to restore later |
| 19 | + original_async_request = _api_client.BaseApiClient.async_request |
| 20 | + original_async_request_streamed = _api_client.BaseApiClient.async_request_streamed |
| 21 | + |
| 22 | + # Remove any existing patch markers if present (unlikely in fresh process but good for safety) |
| 23 | + if hasattr(original_async_request, "_is_logged_async_request"): |
| 24 | + delattr(original_async_request, "_is_logged_async_request") |
| 25 | + |
| 26 | + try: |
| 27 | + # First patch |
| 28 | + _install_api_logging_hooks(debug=True) |
| 29 | + patched_once = _api_client.BaseApiClient.async_request |
| 30 | + |
| 31 | + assert patched_once != original_async_request |
| 32 | + assert getattr(patched_once, "_is_logged_async_request", False) |
| 33 | + |
| 34 | + # Second patch |
| 35 | + _install_api_logging_hooks(debug=True) |
| 36 | + patched_twice = _api_client.BaseApiClient.async_request |
| 37 | + |
| 38 | + # Should be the same object |
| 39 | + assert patched_twice == patched_once |
| 40 | + |
| 41 | + finally: |
| 42 | + # Restore original state |
| 43 | + _api_client.BaseApiClient.async_request = original_async_request |
| 44 | + _api_client.BaseApiClient.async_request_streamed = original_async_request_streamed |
0 commit comments