Skip to content

Commit 9b68808

Browse files
committed
Add stub for openai clients
1 parent bd4ffd0 commit 9b68808

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

tests/unit/test_runtime.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,36 @@
2929

3030
@pytest.fixture(autouse=True)
3131
def stub_openai_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[types.ModuleType]:
32-
"""Provide a stub ``openai.AsyncOpenAI`` for modules under test."""
32+
"""Provide a stub ``openai.AsyncOpenAI`` and patch imports in guardrails.*.
33+
34+
Ensures tests don't require real OPENAI_API_KEY or networked clients.
35+
"""
3336
module = types.ModuleType("openai")
3437

35-
class AsyncOpenAI:
38+
class AsyncOpenAI: # noqa: D401 - simple stub
39+
"""Stubbed AsyncOpenAI client."""
40+
3641
pass
3742

3843
module.__dict__["AsyncOpenAI"] = AsyncOpenAI
44+
# Ensure any downstream import finds our stub module
3945
monkeypatch.setitem(sys.modules, "openai", module)
46+
# Also patch already-imported symbols on guardrails modules
47+
try:
48+
import guardrails.runtime as gr_runtime # type: ignore
49+
50+
monkeypatch.setattr(gr_runtime, "AsyncOpenAI", AsyncOpenAI, raising=False)
51+
except Exception:
52+
pass
53+
try:
54+
import guardrails.types as gr_types # type: ignore
55+
56+
monkeypatch.setattr(gr_types, "AsyncOpenAI", AsyncOpenAI, raising=False)
57+
except Exception:
58+
pass
59+
# Provide dummy API key to satisfy any code paths that inspect env
60+
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
61+
4062
yield module
4163
monkeypatch.delitem(sys.modules, "openai", raising=False)
4264

tests/unit/test_types.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,29 @@
1010

1111
@pytest.fixture(autouse=True)
1212
def stub_openai_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[types.ModuleType]:
13-
"""Provide a stub ``openai.AsyncOpenAI`` for modules under test."""
13+
"""Provide a stub ``openai.AsyncOpenAI`` and patch guardrails types symbol.
14+
15+
Ensures tests don't require real OPENAI_API_KEY or networked clients.
16+
"""
1417
module = types.ModuleType("openai")
1518

16-
class AsyncOpenAI:
19+
class AsyncOpenAI: # noqa: D401 - simple stub
20+
"""Stubbed AsyncOpenAI client."""
21+
1722
pass
1823

1924
module.__dict__["AsyncOpenAI"] = AsyncOpenAI
2025
monkeypatch.setitem(sys.modules, "openai", module)
26+
# Patch already-imported symbol in guardrails.types if present
27+
try:
28+
import guardrails.types as gr_types # type: ignore
29+
30+
monkeypatch.setattr(gr_types, "AsyncOpenAI", AsyncOpenAI, raising=False)
31+
except Exception:
32+
pass
33+
# Provide dummy API key in case any code inspects env
34+
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
35+
2136
yield module
2237
monkeypatch.delitem(sys.modules, "openai", raising=False)
2338

0 commit comments

Comments
 (0)