-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathtest_readme_examples.py
More file actions
265 lines (204 loc) · 10.6 KB
/
Copy pathtest_readme_examples.py
File metadata and controls
265 lines (204 loc) · 10.6 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""Exercises the code patterns shown in the README Usage and Async Usage sections."""
import json
import httpx
import pytest
from diffbot import CrawlEventType, Diffbot, DiffbotAsync, json_schema_format, resolve_token
SSE_PARIS = 'data: {"choices": [{"delta": {"content": "Paris"}}]}\n'
CAPITAL_SCHEMA = {
"type": "object",
"properties": {
"country": {"type": "string"},
"capital": {"type": "string"},
},
"required": ["country", "capital"],
}
SSE_CAPITAL_JSON = (
"data: "
+ json.dumps({"choices": [{"delta": {"content": '{"country": "France", "capital": "Paris"}'}}]})
+ "\n"
)
# ---------------------------------------------------------------------------
# Sync Usage
# ---------------------------------------------------------------------------
def test_readme_sync_extract():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["token"] == "test-token"
assert request.url.params["url"] == "https://news.ycombinator.com"
return httpx.Response(200, json={"objects": [{"title": "Hacker News"}]})
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
data = db.extract("https://news.ycombinator.com")
assert "objects" in data
def test_readme_sync_ask():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, text=SSE_PARIS)
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
chunks = list(db.ask([{"role": "user", "content": "What's the capital of France?"}]))
assert "Paris" in "".join(chunks)
def test_readme_sync_ask_json_with_schema():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["response_format"]["type"] == "json_schema"
assert body["response_format"]["json_schema"]["schema"] == CAPITAL_SCHEMA
return httpx.Response(200, text=SSE_CAPITAL_JSON)
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
answer = db.ask_json(
[{"role": "user", "content": "What's the capital of France?"}], CAPITAL_SCHEMA
)
assert answer["capital"] == "Paris"
def test_readme_sync_ask_json_without_schema():
def handler(request: httpx.Request) -> httpx.Response:
# Defaults to a permissive json_schema, never {"type": "json_object"}.
fmt = json.loads(request.content)["response_format"]
assert fmt["type"] == "json_schema"
assert fmt["json_schema"]["schema"] == {"type": "object"}
return httpx.Response(200, text=SSE_CAPITAL_JSON)
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
answer = db.ask_json([{"role": "user", "content": "What's the capital of France?"}])
assert answer["country"] == "France"
def test_readme_sync_ask_streaming_with_response_format():
def handler(request: httpx.Request) -> httpx.Response:
assert json.loads(request.content)["response_format"]["type"] == "json_schema"
return httpx.Response(200, text=SSE_CAPITAL_JSON)
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
chunks = list(
db.ask(
[{"role": "user", "content": "What's the capital of France?"}],
response_format=json_schema_format(CAPITAL_SCHEMA),
)
)
assert json.loads("".join(chunks))["capital"] == "Paris"
def test_readme_sync_crawl():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"jobs": [{"name": "test-job"}]})
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
events = list(db.crawl("https://example.com", hops=1, job_name="test-job"))
assert len(events) == 1
assert events[0].event_type == CrawlEventType.JOB_CREATED
def test_readme_sync_dql():
def handler(request: httpx.Request) -> httpx.Response:
assert "Diffbot" in request.url.params["query"]
return httpx.Response(200, json={"data": [{"entity": {"name": "Diffbot"}}]})
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
results = db.dql('type:Organization name:"Diffbot"')
assert "data" in results
# ---------------------------------------------------------------------------
# Async Usage
# ---------------------------------------------------------------------------
@pytest.mark.anyio
async def test_readme_async_extract():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"objects": [{"title": "Hacker News"}]})
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
data = await db.extract("https://news.ycombinator.com")
assert "objects" in data
@pytest.mark.anyio
async def test_readme_async_ask():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, text=SSE_PARIS)
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
chunks = [chunk async for chunk in db.ask([{"role": "user", "content": "What's the capital of France?"}])]
assert "Paris" in "".join(chunks)
@pytest.mark.anyio
async def test_readme_async_ask_json_with_schema():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["response_format"]["json_schema"]["schema"] == CAPITAL_SCHEMA
return httpx.Response(200, text=SSE_CAPITAL_JSON)
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
answer = await db.ask_json(
[{"role": "user", "content": "What's the capital of France?"}], CAPITAL_SCHEMA
)
assert answer["capital"] == "Paris"
@pytest.mark.anyio
async def test_readme_async_crawl():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"jobs": [{"name": "test-job"}]})
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
events = [event async for event in db.crawl("https://example.com", hops=1, job_name="test-job")]
assert len(events) == 1
assert events[0].event_type == CrawlEventType.JOB_CREATED
@pytest.mark.anyio
async def test_readme_async_dql():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"data": [{"entity": {"name": "Diffbot"}}]})
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
results = await db.dql('type:Organization name:"Diffbot"')
assert "data" in results
def test_readme_sync_web_search():
def handler(request: httpx.Request) -> httpx.Response:
assert request.headers["Authorization"] == "Bearer test-token"
assert request.url.params["text"] == "diffbot knowledge graph"
return httpx.Response(200, json={
"query": ["diffbot knowledge graph"],
"search_results": [{"score": 0.95, "title": "Diffbot", "pageUrl": "https://diffbot.com", "content": "AI-powered web data."}],
"timeMs": 10,
})
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
results = db.web_search("diffbot knowledge graph")
assert len(results["search_results"]) == 1
r = results["search_results"][0]
assert r["title"] == "Diffbot"
assert r["content"] == "AI-powered web data."
@pytest.mark.anyio
async def test_readme_async_web_search():
def handler(request: httpx.Request) -> httpx.Response:
assert request.headers["Authorization"] == "Bearer test-token"
assert request.url.params["text"] == "diffbot knowledge graph"
return httpx.Response(200, json={
"query": ["diffbot knowledge graph"],
"search_results": [{"score": 0.95, "title": "Diffbot", "pageUrl": "https://diffbot.com", "content": "AI-powered web data."}],
"timeMs": 10,
})
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
results = await db.web_search("diffbot knowledge graph")
assert len(results["search_results"]) == 1
r = results["search_results"][0]
assert r["title"] == "Diffbot"
assert r["content"] == "AI-powered web data."
NLP_RESPONSE = [
{
"entities": [
{"name": "Apple", "allTypes": [{"name": "organization"}], "id": "Cz9nk", "confidence": 0.98, "salience": 0.7, "sentiment": 0.0},
{"name": "Tim Cook", "allTypes": [{"name": "person"}], "id": "Cv9nk", "confidence": 0.95, "salience": 0.5, "sentiment": 0.2},
],
"sentiment": 0.3,
}
]
def test_readme_sync_entities():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "POST"
assert request.url.params["token"] == "test-token"
assert "entities" in request.url.params["fields"]
assert "sentiment" in request.url.params["fields"]
return httpx.Response(200, json=NLP_RESPONSE)
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
result = db.entities("Apple CEO Tim Cook announced record quarterly earnings.")
assert len(result["entities"]) == 2
assert result["entities"][0]["name"] == "Apple"
assert result["sentiment"] == 0.3
@pytest.mark.anyio
async def test_readme_async_entities():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "POST"
assert request.url.params["token"] == "test-token"
assert "entities" in request.url.params["fields"]
assert "sentiment" in request.url.params["fields"]
return httpx.Response(200, json=NLP_RESPONSE)
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
result = await db.entities("Apple CEO Tim Cook announced record quarterly earnings.")
assert len(result["entities"]) == 2
assert result["entities"][0]["name"] == "Apple"
assert result["sentiment"] == 0.3
# ---------------------------------------------------------------------------
# Authentication
# ---------------------------------------------------------------------------
def test_readme_authentication_resolve_token(monkeypatch, tmp_path):
# README "Authentication": Diffbot(token=resolve_token()) using the env var.
monkeypatch.setenv("DIFFBOT_API_TOKEN", "test-token")
monkeypatch.setattr("diffbot._auth.CREDENTIALS_PATH", tmp_path / "missing")
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["token"] == "test-token"
return httpx.Response(200, json={"objects": [{"title": "Example"}]})
db = Diffbot(token=resolve_token(), transport=httpx.MockTransport(handler))
data = db.extract("https://www.example.com")
assert "objects" in data