|
| 1 | +"""Shared pytest fixtures for guardrails tests. |
| 2 | +
|
| 3 | +These fixtures provide deterministic test environments by stubbing the OpenAI |
| 4 | +client library, seeding environment variables, and preventing accidental live |
| 5 | +network activity during the suite. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +import sys |
| 12 | +import types |
| 13 | +from collections.abc import Iterator |
| 14 | +from dataclasses import dataclass |
| 15 | +from types import SimpleNamespace |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +import pytest |
| 19 | + |
| 20 | + |
| 21 | +class _StubOpenAIBase: |
| 22 | + """Base stub with attribute bag behaviour for OpenAI client classes.""" |
| 23 | + |
| 24 | + def __init__(self, **kwargs: Any) -> None: |
| 25 | + self._client_kwargs = kwargs |
| 26 | + self.chat = SimpleNamespace() |
| 27 | + self.responses = SimpleNamespace() |
| 28 | + self.api_key = kwargs.get("api_key", "test-key") |
| 29 | + self.base_url = kwargs.get("base_url") |
| 30 | + self.organization = kwargs.get("organization") |
| 31 | + self.timeout = kwargs.get("timeout") |
| 32 | + self.max_retries = kwargs.get("max_retries") |
| 33 | + |
| 34 | + def __getattr__(self, item: str) -> Any: |
| 35 | + """Return None for unknown attributes to emulate real client laziness.""" |
| 36 | + return None |
| 37 | + |
| 38 | + |
| 39 | +class _StubAsyncOpenAI(_StubOpenAIBase): |
| 40 | + """Stub asynchronous OpenAI client.""" |
| 41 | + |
| 42 | + |
| 43 | +class _StubSyncOpenAI(_StubOpenAIBase): |
| 44 | + """Stub synchronous OpenAI client.""" |
| 45 | + |
| 46 | + |
| 47 | +@dataclass(frozen=True, slots=True) |
| 48 | +class _DummyResponse: |
| 49 | + """Minimal response type with choices and output.""" |
| 50 | + |
| 51 | + choices: list[Any] | None = None |
| 52 | + output: list[Any] | None = None |
| 53 | + output_text: str | None = None |
| 54 | + type: str | None = None |
| 55 | + delta: str | None = None |
| 56 | + |
| 57 | + |
| 58 | +_STUB_OPENAI_MODULE = types.ModuleType("openai") |
| 59 | +_STUB_OPENAI_MODULE.AsyncOpenAI = _StubAsyncOpenAI |
| 60 | +_STUB_OPENAI_MODULE.OpenAI = _StubSyncOpenAI |
| 61 | +_STUB_OPENAI_MODULE.AsyncAzureOpenAI = _StubAsyncOpenAI |
| 62 | +_STUB_OPENAI_MODULE.AzureOpenAI = _StubSyncOpenAI |
| 63 | +_STUB_OPENAI_MODULE.NOT_GIVEN = object() |
| 64 | + |
| 65 | + |
| 66 | +class APITimeoutError(Exception): |
| 67 | + """Stub API timeout error.""" |
| 68 | + |
| 69 | + |
| 70 | +_STUB_OPENAI_MODULE.APITimeoutError = APITimeoutError |
| 71 | + |
| 72 | +_OPENAI_TYPES_MODULE = types.ModuleType("openai.types") |
| 73 | +_OPENAI_TYPES_MODULE.Completion = _DummyResponse |
| 74 | +_OPENAI_TYPES_MODULE.Response = _DummyResponse |
| 75 | + |
| 76 | +_OPENAI_CHAT_MODULE = types.ModuleType("openai.types.chat") |
| 77 | +_OPENAI_CHAT_MODULE.ChatCompletion = _DummyResponse |
| 78 | +_OPENAI_CHAT_MODULE.ChatCompletionChunk = _DummyResponse |
| 79 | + |
| 80 | +_OPENAI_RESPONSES_MODULE = types.ModuleType("openai.types.responses") |
| 81 | +_OPENAI_RESPONSES_MODULE.Response = _DummyResponse |
| 82 | +_OPENAI_RESPONSES_MODULE.ResponseInputItemParam = dict # type: ignore[attr-defined] |
| 83 | +_OPENAI_RESPONSES_MODULE.ResponseOutputItem = dict # type: ignore[attr-defined] |
| 84 | +_OPENAI_RESPONSES_MODULE.ResponseStreamEvent = dict # type: ignore[attr-defined] |
| 85 | + |
| 86 | + |
| 87 | +_OPENAI_RESPONSES_RESPONSE_MODULE = types.ModuleType("openai.types.responses.response") |
| 88 | +_OPENAI_RESPONSES_RESPONSE_MODULE.Response = _DummyResponse |
| 89 | + |
| 90 | + |
| 91 | +class _ResponseTextConfigParam(dict): |
| 92 | + """Stub config param used for response formatting.""" |
| 93 | + |
| 94 | + |
| 95 | +_OPENAI_RESPONSES_MODULE.ResponseTextConfigParam = _ResponseTextConfigParam |
| 96 | + |
| 97 | +sys.modules["openai"] = _STUB_OPENAI_MODULE |
| 98 | +sys.modules["openai.types"] = _OPENAI_TYPES_MODULE |
| 99 | +sys.modules["openai.types.chat"] = _OPENAI_CHAT_MODULE |
| 100 | +sys.modules["openai.types.responses"] = _OPENAI_RESPONSES_MODULE |
| 101 | +sys.modules["openai.types.responses.response"] = _OPENAI_RESPONSES_RESPONSE_MODULE |
| 102 | + |
| 103 | + |
| 104 | +@pytest.fixture(autouse=True) |
| 105 | +def stub_openai_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[types.ModuleType]: |
| 106 | + """Provide stub OpenAI module so tests avoid real network-bound clients.""" |
| 107 | + # Patch imported symbols in guardrails modules |
| 108 | + from guardrails import _base_client, client, types as guardrail_types # type: ignore |
| 109 | + |
| 110 | + monkeypatch.setattr(_base_client, "AsyncOpenAI", _StubAsyncOpenAI, raising=False) |
| 111 | + monkeypatch.setattr(_base_client, "OpenAI", _StubSyncOpenAI, raising=False) |
| 112 | + monkeypatch.setattr(client, "AsyncOpenAI", _StubAsyncOpenAI, raising=False) |
| 113 | + monkeypatch.setattr(client, "OpenAI", _StubSyncOpenAI, raising=False) |
| 114 | + monkeypatch.setattr(client, "AsyncAzureOpenAI", _StubAsyncOpenAI, raising=False) |
| 115 | + monkeypatch.setattr(client, "AzureOpenAI", _StubSyncOpenAI, raising=False) |
| 116 | + monkeypatch.setattr(guardrail_types, "AsyncOpenAI", _StubAsyncOpenAI, raising=False) |
| 117 | + monkeypatch.setattr(guardrail_types, "OpenAI", _StubSyncOpenAI, raising=False) |
| 118 | + monkeypatch.setattr(guardrail_types, "AsyncAzureOpenAI", _StubAsyncOpenAI, raising=False) |
| 119 | + monkeypatch.setattr(guardrail_types, "AzureOpenAI", _StubSyncOpenAI, raising=False) |
| 120 | + |
| 121 | + monkeypatch.setenv("OPENAI_API_KEY", "test-key") |
| 122 | + |
| 123 | + yield _STUB_OPENAI_MODULE |
| 124 | + |
| 125 | + |
| 126 | +@pytest.fixture(autouse=True) |
| 127 | +def configure_logging() -> None: |
| 128 | + """Ensure logging defaults to DEBUG for deterministic assertions.""" |
| 129 | + logging.basicConfig(level=logging.DEBUG) |
0 commit comments