1
from datetime import datetime
2
from pathlib import Path
3
from typing import Generator
4
from unittest.mock import Mock, patch
7
from openai.types.chat import ChatCompletion, ChatCompletionMessage
8
from openai.types.chat.chat_completion import Choice
10
from haystack import tracing
11
from haystack.testing.test_utils import set_all_seeds
12
from test.tracing.utils import SpyingTracer
20
Tokenizes the string by splitting on spaces.
23
tokenizer.encode = lambda text: text.split()
24
tokenizer.decode = lambda tokens: " ".join(tokens)
30
return Path(__file__).parent / "test_files"
34
def mock_chat_completion():
36
Mock the OpenAI API completion response and reuse it for tests
38
with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
39
completion = ChatCompletion(
42
object="chat.completion",
48
message=ChatCompletionMessage(content="Hello world!", role="assistant"),
51
created=int(datetime.now().timestamp()),
52
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
55
mock_chat_completion_create.return_value = completion
56
yield mock_chat_completion_create
59
@pytest.fixture(autouse=True)
60
def request_blocker(request: pytest.FixtureRequest, monkeypatch):
62
This fixture is applied automatically to all tests.
63
Those that are not marked as integration will have the requests module
64
monkeypatched to avoid making HTTP requests by mistake.
66
marker = request.node.get_closest_marker("integration")
67
if marker is not None:
70
def urlopen_mock(self, method, url, *args, **kwargs):
71
raise RuntimeError(f"The test was about to {method} {self.scheme}://{self.host}{url}")
73
monkeypatch.setattr("urllib3.connectionpool.HTTPConnectionPool.urlopen", urlopen_mock)
77
def spying_tracer() -> Generator[SpyingTracer, None, None]:
78
tracer = SpyingTracer()
79
tracing.enable_tracing(tracer)
84
tracing.disable_tracing()