Repository navigation
Expand file tree
/
Copy pathtest_adapters.py
More file actions
170 lines (137 loc) · 5.63 KB
/
Copy pathtest_adapters.py
File metadata and controls
170 lines (137 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Offline tests for SqliteStore, OpenAILLM, and the PostgreSQL stub."""
from __future__ import annotations
import asyncio
import os
import pytest
from lang2sql.adapters.db.postgres_explorer import PostgresExplorer
from lang2sql.adapters.llm.openai_ import OpenAILLM
from lang2sql.adapters.storage.sqlite_store import SqliteStore
from lang2sql.core.identity import Identity
from lang2sql.core.ports.audit import AuditEvent
from lang2sql.core.ports.explorer import ExplorerPort, QueryTimeoutUnsupportedError
from lang2sql.core.types import Message, Role, ToolCall, ToolSpec
from lang2sql.harness.session import Session
def test_audit_record_then_query() -> None:
store = SqliteStore()
asyncio.run(
store.record(
AuditEvent(
actor="u1", action="run_sql", scope="s", detail={"q": "SELECT 1"}
)
)
)
asyncio.run(
store.record(
AuditEvent(actor="u1", action="define_metric", scope="s", detail={})
)
)
asyncio.run(store.record(AuditEvent(actor="other", action="run_sql", scope="s")))
events = asyncio.run(store.query("u1"))
assert len(events) == 2
# Newest first.
assert events[0].action == "define_metric"
assert events[1].action == "run_sql"
assert events[1].detail == {"q": "SELECT 1"}
assert events[0].ts > 0 # store fills the timestamp
def test_session_save_then_load_reconstructs_transcript() -> None:
store = SqliteStore()
identity = Identity(
user_id="u1", guild_id="g", channel_id="c", thread_id="t", is_admin=True
)
session = Session(identity=identity)
session.add(Message(role=Role.USER, content="hi"))
session.add(
Message(
role=Role.ASSISTANT,
content="",
tool_calls=[
ToolCall(id="call_1", name="run_sql", arguments={"q": "SELECT 1"})
],
)
)
session.add(
Message(role=Role.TOOL, content="ok", tool_call_id="call_1", name="run_sql")
)
key = identity.session_key()
asyncio.run(store.save(key, session))
loaded = asyncio.run(store.load(key))
assert loaded is not None
assert loaded.identity == identity
assert len(loaded.transcript) == 3
assert loaded.transcript[0].role == Role.USER
tc = loaded.transcript[1].tool_calls[0]
assert tc.id == "call_1"
assert tc.name == "run_sql"
assert tc.arguments == {"q": "SELECT 1"}
assert loaded.transcript[2].tool_call_id == "call_1"
assert loaded.transcript[2].name == "run_sql"
def test_session_load_missing_returns_none() -> None:
store = SqliteStore()
assert asyncio.run(store.load("nope")) is None
def test_kv_set_get_delete() -> None:
store = SqliteStore()
assert store.kv_get("scope", "k") is None
store.kv_set("scope", "k", "v1")
assert store.kv_get("scope", "k") == "v1"
store.kv_set("scope", "k", "v2") # upsert
assert store.kv_get("scope", "k") == "v2"
store.kv_delete("scope", "k")
assert store.kv_get("scope", "k") is None
def test_postgres_explorer_canned_data() -> None:
explorer = PostgresExplorer("postgresql://ignored")
tables = asyncio.run(explorer.list_tables())
names = {t.qualified for t in tables}
assert "public.orders" in names
assert "public.users" in names
orders = asyncio.run(explorer.describe_table("orders"))
assert {c.name for c in orders.columns} == {"id", "amount", "status", "created_at"}
rows = asyncio.run(explorer.sample_rows("public.orders", limit=1))
assert len(rows) == 1
assert "status" in rows[0]
def test_postgres_explorer_satisfies_protocol() -> None:
explorer = PostgresExplorer("postgresql://ignored")
assert isinstance(explorer, ExplorerPort)
def test_postgres_metadata_stub_refuses_unbounded_execute() -> None:
explorer = PostgresExplorer("postgresql://ignored")
with pytest.raises(QueryTimeoutUnsupportedError, match="statement cancellation"):
asyncio.run(explorer.execute("SELECT * FROM orders WHERE status='paid'"))
def test_openai_constructs_offline() -> None:
# No network, no key required to construct.
llm = OpenAILLM(model="gpt-4.1-mini", api_key=None, base_url="http://localhost:0")
assert llm.model == "gpt-4.1-mini"
def test_openai_complete_without_key_raises() -> None:
saved = os.environ.pop("OPENAI_API_KEY", None)
try:
llm = OpenAILLM(api_key=None)
raised = False
try:
asyncio.run(llm.complete([Message(role=Role.USER, content="hi")]))
except RuntimeError as exc:
raised = True
assert "OPENAI_API_KEY not set" in str(exc)
assert raised
finally:
if saved is not None:
os.environ["OPENAI_API_KEY"] = saved
def test_openai_requires_a_tool_on_one_request(monkeypatch) -> None:
requests = []
def post(payload):
requests.append(payload)
return {"choices": [{"message": {"content": "ok"}}]}
llm = OpenAILLM(api_key="test")
monkeypatch.setattr(llm, "_post", post)
messages = [Message(role=Role.USER, content="Show order amounts")]
tools = [ToolSpec(name="explore_schema", description="Show table columns")]
async def complete():
await llm.complete(messages, tools)
await llm.complete_with_required_tool(messages, tools, "explore_schema")
await llm.complete(messages)
asyncio.run(complete())
ordinary, forced, auxiliary = requests
assert "tool_choice" not in ordinary
assert ordinary["tools"] == forced["tools"]
assert forced["tool_choice"] == {
"type": "function",
"function": {"name": "explore_schema"},
}
assert "tool_choice" not in auxiliary and "tools" not in auxiliary