|
15 | 15 | # specific language governing permissions and limitations |
16 | 16 | # under the License. |
17 | 17 |
|
| 18 | +import asyncio |
18 | 19 | import os |
19 | 20 | import unittest |
| 21 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 22 | + |
| 23 | +import httpx |
| 24 | +import ollama |
| 25 | +import pytest |
| 26 | +from tenacity import RetryError, wait_none |
20 | 27 |
|
21 | 28 | from hugegraph_llm.models.llms.ollama import OllamaClient |
22 | 29 |
|
| 30 | +pytestmark = pytest.mark.contract |
| 31 | + |
| 32 | +# Minimal dict response matching the structure ollama.Client.chat() returns |
| 33 | +_MOCK_RESPONSE = { |
| 34 | + "prompt_eval_count": 10, |
| 35 | + "eval_count": 5, |
| 36 | + "message": {"content": "Paris"}, |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +class TestOllamaClientRetryPolicy(unittest.TestCase): |
| 41 | + """Mock-based contract tests for the Tenacity retry policy in OllamaClient. |
| 42 | +
|
| 43 | + These tests do not require a running Ollama service. They verify: |
| 44 | + - retryable exceptions (ollama.ResponseError, httpx.ConnectError, |
| 45 | + httpx.TimeoutException) trigger the configured number of attempts; |
| 46 | + - non-retryable exceptions (e.g. ValueError) are NOT retried; |
| 47 | + - a transient failure followed by success resolves correctly. |
| 48 | + """ |
| 49 | + |
| 50 | + def setUp(self): |
| 51 | + # Zero out exponential wait so retry tests complete in milliseconds. |
| 52 | + # Tenacity exposes the Retrying object on the decorated function via |
| 53 | + # the .retry attribute; its .wait field is mutable. |
| 54 | + self._orig_generate_wait = OllamaClient.generate.retry.wait |
| 55 | + self._orig_agenerate_wait = OllamaClient.agenerate.retry.wait |
| 56 | + OllamaClient.generate.retry.wait = wait_none() |
| 57 | + OllamaClient.agenerate.retry.wait = wait_none() |
| 58 | + |
| 59 | + def tearDown(self): |
| 60 | + OllamaClient.generate.retry.wait = self._orig_generate_wait |
| 61 | + OllamaClient.agenerate.retry.wait = self._orig_agenerate_wait |
| 62 | + |
| 63 | + # ------------------------------------------------------------------ # |
| 64 | + # generate() # |
| 65 | + # ------------------------------------------------------------------ # |
| 66 | + |
| 67 | + @patch("hugegraph_llm.models.llms.ollama.ollama.Client") |
| 68 | + def test_generate_returns_content_on_success(self, mock_client_class): |
| 69 | + """Happy path: generate() returns the message content string.""" |
| 70 | + mock_client = MagicMock() |
| 71 | + mock_client.chat.return_value = _MOCK_RESPONSE |
| 72 | + mock_client_class.return_value = mock_client |
| 73 | + |
| 74 | + result = OllamaClient(model="llama3").generate(prompt="hello") |
| 75 | + |
| 76 | + self.assertEqual(result, "Paris") |
| 77 | + mock_client.chat.assert_called_once() |
| 78 | + |
| 79 | + @patch("hugegraph_llm.models.llms.ollama.ollama.Client") |
| 80 | + def test_generate_retries_response_error_exhausts_all_attempts(self, mock_client_class): |
| 81 | + """ollama.ResponseError is retryable; all 3 attempts are made.""" |
| 82 | + mock_client = MagicMock() |
| 83 | + mock_client.chat.side_effect = ollama.ResponseError("model not found") |
| 84 | + mock_client_class.return_value = mock_client |
| 85 | + |
| 86 | + with self.assertRaises(RetryError): |
| 87 | + OllamaClient(model="llama3").generate(prompt="hello") |
| 88 | + |
| 89 | + self.assertEqual(mock_client.chat.call_count, 3) |
| 90 | + |
| 91 | + @patch("hugegraph_llm.models.llms.ollama.ollama.Client") |
| 92 | + def test_generate_retries_connect_error_exhausts_all_attempts(self, mock_client_class): |
| 93 | + """httpx.ConnectError is retryable; all 3 attempts are made.""" |
| 94 | + mock_client = MagicMock() |
| 95 | + mock_client.chat.side_effect = httpx.ConnectError("connection refused") |
| 96 | + mock_client_class.return_value = mock_client |
| 97 | + |
| 98 | + with self.assertRaises(RetryError): |
| 99 | + OllamaClient(model="llama3").generate(prompt="hello") |
| 100 | + |
| 101 | + self.assertEqual(mock_client.chat.call_count, 3) |
| 102 | + |
| 103 | + @patch("hugegraph_llm.models.llms.ollama.ollama.Client") |
| 104 | + def test_generate_does_not_retry_non_retriable_error(self, mock_client_class): |
| 105 | + """ValueError is not in the retry predicate; only 1 attempt is made.""" |
| 106 | + mock_client = MagicMock() |
| 107 | + mock_client.chat.side_effect = ValueError("unexpected") |
| 108 | + mock_client_class.return_value = mock_client |
| 109 | + |
| 110 | + with self.assertRaises(ValueError): |
| 111 | + OllamaClient(model="llama3").generate(prompt="hello") |
| 112 | + |
| 113 | + mock_client.chat.assert_called_once() |
| 114 | + |
| 115 | + @patch("hugegraph_llm.models.llms.ollama.ollama.Client") |
| 116 | + def test_generate_succeeds_on_second_attempt(self, mock_client_class): |
| 117 | + """Transient ResponseError on attempt 1, success on attempt 2.""" |
| 118 | + mock_client = MagicMock() |
| 119 | + mock_client.chat.side_effect = [ |
| 120 | + ollama.ResponseError("transient"), |
| 121 | + _MOCK_RESPONSE, |
| 122 | + ] |
| 123 | + mock_client_class.return_value = mock_client |
| 124 | + |
| 125 | + result = OllamaClient(model="llama3").generate(prompt="hello") |
| 126 | + |
| 127 | + self.assertEqual(result, "Paris") |
| 128 | + self.assertEqual(mock_client.chat.call_count, 2) |
| 129 | + |
| 130 | + # ------------------------------------------------------------------ # |
| 131 | + # agenerate() # |
| 132 | + # ------------------------------------------------------------------ # |
| 133 | + |
| 134 | + @patch("hugegraph_llm.models.llms.ollama.ollama.AsyncClient") |
| 135 | + def test_agenerate_retries_connect_error_exhausts_all_attempts(self, mock_async_client_class): |
| 136 | + """httpx.ConnectError is retryable in agenerate(); all 3 attempts made.""" |
| 137 | + mock_async_client = MagicMock() |
| 138 | + mock_async_client.chat = AsyncMock(side_effect=httpx.ConnectError("connection refused")) |
| 139 | + mock_async_client_class.return_value = mock_async_client |
| 140 | + |
| 141 | + async def run(): |
| 142 | + with self.assertRaises(RetryError): |
| 143 | + await OllamaClient(model="llama3").agenerate(prompt="hello") |
| 144 | + self.assertEqual(mock_async_client.chat.call_count, 3) |
| 145 | + |
| 146 | + asyncio.run(run()) |
| 147 | + |
| 148 | + @patch("hugegraph_llm.models.llms.ollama.ollama.AsyncClient") |
| 149 | + def test_agenerate_retries_timeout_exception_exhausts_all_attempts(self, mock_async_client_class): |
| 150 | + """httpx.TimeoutException is retryable in agenerate(); all 3 attempts made.""" |
| 151 | + mock_async_client = MagicMock() |
| 152 | + mock_async_client.chat = AsyncMock(side_effect=httpx.TimeoutException("timed out")) |
| 153 | + mock_async_client_class.return_value = mock_async_client |
| 154 | + |
| 155 | + async def run(): |
| 156 | + with self.assertRaises(RetryError): |
| 157 | + await OllamaClient(model="llama3").agenerate(prompt="hello") |
| 158 | + self.assertEqual(mock_async_client.chat.call_count, 3) |
| 159 | + |
| 160 | + asyncio.run(run()) |
| 161 | + |
| 162 | + @patch("hugegraph_llm.models.llms.ollama.ollama.AsyncClient") |
| 163 | + def test_agenerate_does_not_retry_non_retriable_error(self, mock_async_client_class): |
| 164 | + """ValueError is not retryable in agenerate(); only 1 attempt is made.""" |
| 165 | + mock_async_client = MagicMock() |
| 166 | + mock_async_client.chat = AsyncMock(side_effect=ValueError("unexpected")) |
| 167 | + mock_async_client_class.return_value = mock_async_client |
| 168 | + |
| 169 | + async def run(): |
| 170 | + with self.assertRaises(ValueError): |
| 171 | + await OllamaClient(model="llama3").agenerate(prompt="hello") |
| 172 | + mock_async_client.chat.assert_called_once() |
| 173 | + |
| 174 | + asyncio.run(run()) |
| 175 | + |
| 176 | + @patch("hugegraph_llm.models.llms.ollama.ollama.AsyncClient") |
| 177 | + def test_agenerate_succeeds_on_second_attempt(self, mock_async_client_class): |
| 178 | + """Transient ResponseError on attempt 1, success on attempt 2.""" |
| 179 | + mock_async_client = MagicMock() |
| 180 | + mock_async_client.chat = AsyncMock(side_effect=[ollama.ResponseError("transient"), _MOCK_RESPONSE]) |
| 181 | + mock_async_client_class.return_value = mock_async_client |
| 182 | + |
| 183 | + async def run(): |
| 184 | + result = await OllamaClient(model="llama3").agenerate(prompt="hello") |
| 185 | + self.assertEqual(result, "Paris") |
| 186 | + self.assertEqual(mock_async_client.chat.call_count, 2) |
| 187 | + |
| 188 | + asyncio.run(run()) |
| 189 | + |
| 190 | + |
| 191 | +class TestOllamaClientExternalService(unittest.TestCase): |
| 192 | + """Integration tests that require a live Ollama service. |
| 193 | +
|
| 194 | + Skipped in CI via SKIP_EXTERNAL_SERVICES=true (set in conftest.py). |
| 195 | + """ |
23 | 196 |
|
24 | | -class TestOllamaClient(unittest.TestCase): |
25 | 197 | def setUp(self): |
26 | 198 | self.skip_external = os.getenv("SKIP_EXTERNAL_SERVICES", "false").lower() == "true" |
27 | 199 |
|
28 | | - @unittest.skipIf(os.getenv("SKIP_EXTERNAL_SERVICES", "false").lower() == "true", "Skipping external service tests") |
| 200 | + @unittest.skipIf( |
| 201 | + os.getenv("SKIP_EXTERNAL_SERVICES", "false").lower() == "true", |
| 202 | + "Skipping external service tests", |
| 203 | + ) |
29 | 204 | def test_generate(self): |
30 | 205 | ollama_client = OllamaClient(model="llama3:8b-instruct-fp16") |
31 | 206 | response = ollama_client.generate(prompt="What is the capital of France?") |
32 | 207 | print(response) |
33 | 208 |
|
34 | | - @unittest.skipIf(os.getenv("SKIP_EXTERNAL_SERVICES", "false").lower() == "true", "Skipping external service tests") |
| 209 | + @unittest.skipIf( |
| 210 | + os.getenv("SKIP_EXTERNAL_SERVICES", "false").lower() == "true", |
| 211 | + "Skipping external service tests", |
| 212 | + ) |
35 | 213 | def test_stream_generate(self): |
36 | 214 | ollama_client = OllamaClient(model="llama3:8b-instruct-fp16") |
37 | 215 |
|
38 | 216 | def on_token_callback(chunk): |
39 | 217 | print(chunk, end="", flush=True) |
40 | 218 |
|
41 | | - ollama_client.generate_streaming(prompt="What is the capital of France?", on_token_callback=on_token_callback) |
| 219 | + ollama_client.generate_streaming( |
| 220 | + prompt="What is the capital of France?", |
| 221 | + on_token_callback=on_token_callback, |
| 222 | + ) |
| 223 | + |
| 224 | + |
| 225 | +if __name__ == "__main__": |
| 226 | + unittest.main() |
0 commit comments