-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_extraction.py
More file actions
713 lines (604 loc) · 25.1 KB
/
Copy pathtest_extraction.py
File metadata and controls
713 lines (604 loc) · 25.1 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
"""
Tests for the Extraction module
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from stack0.extraction import AsyncExtraction, Extraction
from stack0.extraction.types import (
CreateBatchExtractionsRequest,
CreateExtractionRequest,
CreateExtractionScheduleRequest,
GetBatchJobRequest,
GetExtractionRequest,
GetScheduleRequest,
GetUsageRequest,
ListBatchJobsRequest,
ListExtractionsRequest,
ListSchedulesRequest,
UpdateExtractionScheduleRequest,
)
from tests.conftest import MockAsyncHTTPClient, MockHTTPClient
class TestExtraction:
"""Tests for synchronous Extraction client"""
def test_extract(self) -> None:
"""Test extracting content from a URL"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/extractions": {
"id": "ext_123",
"status": "pending",
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.extract(CreateExtractionRequest(
url="https://example.com/article",
mode="markdown",
))
assert response.id == "ext_123"
assert response.status == "pending"
body = mock_http.requests[0]["body"]
assert body["url"] == "https://example.com/article"
assert body["mode"] == "markdown"
def test_get_extraction(self) -> None:
"""Test getting an extraction by ID"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/extractions/ext_123": {
"id": "ext_123",
"organizationId": "org_1",
"projectId": None,
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "completed",
"extractedData": None,
"markdown": "# Hello World\n\nThis is the content.",
"rawHtml": None,
"pageMetadata": {
"title": "Hello World",
"description": "A test article",
"ogImage": "https://example.com/og.png",
},
"error": None,
"processingTimeMs": 2500,
"tokensUsed": 150,
"metadata": None,
"createdAt": "2024-01-15T10:00:00Z",
"completedAt": "2024-01-15T10:00:03Z",
}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.get(GetExtractionRequest(id="ext_123"))
assert result.id == "ext_123"
assert result.status == "completed"
assert result.markdown == "# Hello World\n\nThis is the content."
assert result.page_metadata is not None
assert result.page_metadata.title == "Hello World"
def test_get_extraction_with_environment(self) -> None:
"""Test getting an extraction with environment filter"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/extractions/ext_123?environment=production": {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.get(GetExtractionRequest(
id="ext_123",
environment="production",
))
assert result.id == "ext_123"
assert result.environment == "production"
def test_list_extractions(self) -> None:
"""Test listing extractions"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/extractions?environment=production&limit=10": {
"items": [
{
"id": "ext_1",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/page1",
"mode": "markdown",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
},
{
"id": "ext_2",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/page2",
"mode": "schema",
"status": "completed",
"createdAt": "2024-01-15T11:00:00Z",
},
],
"nextCursor": None,
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.list(ListExtractionsRequest(
environment="production",
limit=10,
))
assert len(response.items) == 2
assert response.items[0].id == "ext_1"
def test_delete_extraction(self) -> None:
"""Test deleting an extraction"""
mock_http = MockHTTPClient(responses={
"DELETE:/webdata/extractions/ext_123": {"success": True}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.delete(GetExtractionRequest(id="ext_123"))
assert result["success"] is True
def test_extract_with_schema(self) -> None:
"""Test extracting with a schema"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/extractions": {
"id": "ext_456",
"status": "pending",
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.extract(CreateExtractionRequest(
url="https://example.com/product",
mode="schema",
schema_={
"type": "object",
"properties": {
"title": {"type": "string"},
"price": {"type": "number"},
"description": {"type": "string"},
},
},
prompt="Extract the product information",
))
assert response.id == "ext_456"
body = mock_http.requests[0]["body"]
assert body["mode"] == "schema"
assert body["schema"]["properties"]["title"]["type"] == "string"
assert body["prompt"] == "Extract the product information"
class TestExtractionExtractAndWait:
"""Tests for extract_and_wait polling functionality"""
def test_extract_and_wait_immediate_completion(self) -> None:
"""Test extract_and_wait when extraction completes immediately"""
call_count = [0]
def mock_get_response(method: str, path: str) -> dict:
if method == "POST" and "/webdata/extractions" in path:
return {"id": "ext_123", "status": "pending"}
if method == "GET" and "/webdata/extractions/ext_123" in path:
call_count[0] += 1
return {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "completed",
"markdown": "# Extracted Content",
"createdAt": "2024-01-15T10:00:00Z",
}
return {"success": True}
mock_http = MockHTTPClient()
mock_http._get_response = mock_get_response # type: ignore
extraction = Extraction(mock_http) # type: ignore
result = extraction.extract_and_wait(
CreateExtractionRequest(url="https://example.com/article", mode="markdown"),
poll_interval=0.01,
timeout=1.0,
)
assert result.status == "completed"
assert call_count[0] == 1
def test_extract_and_wait_delayed_completion(self) -> None:
"""Test extract_and_wait with multiple polls"""
call_count = [0]
def mock_get_response(method: str, path: str) -> dict:
if method == "POST" and "/webdata/extractions" in path:
return {"id": "ext_123", "status": "pending"}
if method == "GET" and "/webdata/extractions/ext_123" in path:
call_count[0] += 1
status = "completed" if call_count[0] >= 3 else "processing"
return {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": status,
"markdown": "# Extracted Content" if status == "completed" else None,
"createdAt": "2024-01-15T10:00:00Z",
}
return {"success": True}
mock_http = MockHTTPClient()
mock_http._get_response = mock_get_response # type: ignore
extraction = Extraction(mock_http) # type: ignore
with patch("time.sleep"): # Skip actual sleep
result = extraction.extract_and_wait(
CreateExtractionRequest(url="https://example.com/article", mode="markdown"),
poll_interval=0.01,
timeout=10.0,
)
assert result.status == "completed"
assert call_count[0] == 3
def test_extract_and_wait_failure(self) -> None:
"""Test extract_and_wait when extraction fails"""
def mock_get_response(method: str, path: str) -> dict:
if method == "POST" and "/webdata/extractions" in path:
return {"id": "ext_123", "status": "pending"}
if method == "GET" and "/webdata/extractions/ext_123" in path:
return {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "failed",
"error": "Page could not be loaded",
"createdAt": "2024-01-15T10:00:00Z",
}
return {"success": True}
mock_http = MockHTTPClient()
mock_http._get_response = mock_get_response # type: ignore
extraction = Extraction(mock_http) # type: ignore
with pytest.raises(Exception, match="Page could not be loaded"):
extraction.extract_and_wait(
CreateExtractionRequest(url="https://example.com/article", mode="markdown"),
poll_interval=0.01,
timeout=1.0,
)
def test_extract_and_wait_timeout(self) -> None:
"""Test extract_and_wait timeout"""
def mock_get_response(method: str, path: str) -> dict:
if method == "POST" and "/webdata/extractions" in path:
return {"id": "ext_123", "status": "pending"}
if method == "GET" and "/webdata/extractions/ext_123" in path:
return {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "processing", # Never completes
"createdAt": "2024-01-15T10:00:00Z",
}
return {"success": True}
mock_http = MockHTTPClient()
mock_http._get_response = mock_get_response # type: ignore
extraction = Extraction(mock_http) # type: ignore
with pytest.raises(Exception, match="timed out"):
extraction.extract_and_wait(
CreateExtractionRequest(url="https://example.com/article", mode="markdown"),
poll_interval=0.01,
timeout=0.05, # Very short timeout
)
class TestBatchExtraction:
"""Tests for batch extraction operations"""
def test_create_batch(self) -> None:
"""Test creating a batch job"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/batch/extractions": {
"id": "batch_123",
"status": "pending",
"totalUrls": 5,
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.batch(CreateBatchExtractionsRequest(
urls=["https://example.com/page1", "https://example.com/page2"],
mode="markdown",
))
assert response.id == "batch_123"
assert response.status == "pending"
def test_get_batch_job(self) -> None:
"""Test getting a batch job"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/batch/batch_123": {
"id": "batch_123",
"organizationId": "org_1",
"environment": "production",
"status": "completed",
"type": "extraction",
"totalUrls": 2,
"processedUrls": 2,
"failedUrls": 0,
"config": {"mode": "markdown"},
"createdAt": "2024-01-15T10:00:00Z",
"completedAt": "2024-01-15T10:01:00Z",
}
})
extraction = Extraction(mock_http) # type: ignore
job = extraction.get_batch_job(GetBatchJobRequest(id="batch_123"))
assert job.id == "batch_123"
assert job.status == "completed"
assert job.processed_urls == 2
def test_list_batch_jobs(self) -> None:
"""Test listing batch jobs"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/batch?type=extraction": {
"items": [
{
"id": "batch_1",
"organizationId": "org_1",
"environment": "production",
"status": "completed",
"type": "extraction",
"totalUrls": 5,
"processedUrls": 5,
"failedUrls": 0,
"config": {},
"createdAt": "2024-01-15T10:00:00Z",
},
],
"nextCursor": None,
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.list_batch_jobs()
assert len(response.items) == 1
assert response.items[0].status == "completed"
def test_cancel_batch_job(self) -> None:
"""Test cancelling a batch job"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/batch/batch_123/cancel": {"success": True}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.cancel_batch_job(GetBatchJobRequest(id="batch_123"))
assert result["success"] is True
class TestExtractionSchedules:
"""Tests for extraction schedule operations"""
def test_create_schedule(self) -> None:
"""Test creating a schedule"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/schedules": {
"id": "schedule_123",
"status": "active",
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.create_schedule(CreateExtractionScheduleRequest(
url="https://example.com/page",
frequency="daily",
mode="markdown",
))
assert response.id == "schedule_123"
def test_get_schedule(self) -> None:
"""Test getting a schedule"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/schedules/schedule_123": {
"id": "schedule_123",
"organizationId": "org_1",
"environment": "production",
"type": "extraction",
"isActive": True,
"frequency": "daily",
"config": {
"url": "https://example.com/page",
"mode": "markdown",
},
"lastRunAt": None,
"nextRunAt": "2024-01-16T10:00:00Z",
"createdAt": "2024-01-15T10:00:00Z",
}
})
extraction = Extraction(mock_http) # type: ignore
schedule = extraction.get_schedule(GetScheduleRequest(id="schedule_123"))
assert schedule.id == "schedule_123"
assert schedule.is_active is True
def test_list_schedules(self) -> None:
"""Test listing schedules"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/schedules?type=extraction&isActive=true": {
"items": [
{
"id": "schedule_1",
"organizationId": "org_1",
"environment": "production",
"type": "extraction",
"isActive": True,
"frequency": "daily",
"config": {},
"createdAt": "2024-01-15T10:00:00Z",
},
],
"nextCursor": None,
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.list_schedules(ListSchedulesRequest(is_active=True))
assert len(response.items) == 1
def test_update_schedule(self) -> None:
"""Test updating a schedule"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/schedules/schedule_123": {"success": True}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.update_schedule(UpdateExtractionScheduleRequest(
id="schedule_123",
frequency="weekly",
))
assert result["success"] is True
def test_delete_schedule(self) -> None:
"""Test deleting a schedule"""
mock_http = MockHTTPClient(responses={
"DELETE:/webdata/schedules/schedule_123": {"success": True}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.delete_schedule(GetScheduleRequest(id="schedule_123"))
assert result["success"] is True
def test_toggle_schedule(self) -> None:
"""Test toggling a schedule"""
mock_http = MockHTTPClient(responses={
"POST:/webdata/schedules/schedule_123/toggle": {"success": True}
})
extraction = Extraction(mock_http) # type: ignore
result = extraction.toggle_schedule(GetScheduleRequest(id="schedule_123"))
assert result["success"] is True
class TestExtractionUsage:
"""Tests for extraction usage operations"""
def test_get_usage(self) -> None:
"""Test getting usage stats"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/usage": {
"totalExtractions": 100,
"successfulExtractions": 95,
"failedExtractions": 5,
"totalTokens": 50000,
"estimatedCost": 0.50,
}
})
extraction = Extraction(mock_http) # type: ignore
usage = extraction.get_usage()
assert usage.total_extractions == 100
assert usage.successful_extractions == 95
def test_get_usage_with_filters(self) -> None:
"""Test getting usage with date filters"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/usage?environment=production&periodStart=2024-01-01&periodEnd=2024-01-31": {
"totalExtractions": 50,
"successfulExtractions": 48,
"failedExtractions": 2,
"totalTokens": 25000,
"estimatedCost": 0.25,
}
})
extraction = Extraction(mock_http) # type: ignore
usage = extraction.get_usage(GetUsageRequest(
environment="production",
period_start="2024-01-01",
period_end="2024-01-31",
))
assert usage.total_extractions == 50
def test_get_usage_daily(self) -> None:
"""Test getting daily usage breakdown"""
mock_http = MockHTTPClient(responses={
"GET:/webdata/usage/daily": {
"items": [
{
"date": "2024-01-15",
"extractions": 10,
"tokens": 5000,
},
{
"date": "2024-01-16",
"extractions": 15,
"tokens": 7500,
},
],
}
})
extraction = Extraction(mock_http) # type: ignore
response = extraction.get_usage_daily()
assert len(response.items) == 2
class TestAsyncExtraction:
"""Tests for async Extraction client"""
@pytest.mark.asyncio
async def test_extract(self) -> None:
"""Test extracting content asynchronously"""
mock_http = MockAsyncHTTPClient(responses={
"POST:/webdata/extractions": {
"id": "ext_async_123",
"status": "pending",
}
})
extraction = AsyncExtraction(mock_http) # type: ignore
response = await extraction.extract(CreateExtractionRequest(
url="https://example.com/article",
mode="auto",
))
assert response.id == "ext_async_123"
assert response.status == "pending"
@pytest.mark.asyncio
async def test_get_extraction(self) -> None:
"""Test getting an extraction asynchronously"""
mock_http = MockAsyncHTTPClient(responses={
"GET:/webdata/extractions/ext_async_123": {
"id": "ext_async_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "completed",
"markdown": "# Test Content",
"createdAt": "2024-01-15T10:00:00Z",
}
})
extraction = AsyncExtraction(mock_http) # type: ignore
result = await extraction.get(GetExtractionRequest(id="ext_async_123"))
assert result.id == "ext_async_123"
assert result.status == "completed"
assert result.markdown == "# Test Content"
@pytest.mark.asyncio
async def test_list_extractions(self) -> None:
"""Test listing extractions asynchronously"""
mock_http = MockAsyncHTTPClient(responses={
"GET:/webdata/extractions": {
"items": [
{
"id": "ext_1",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/page",
"mode": "markdown",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
},
],
"nextCursor": None,
}
})
extraction = AsyncExtraction(mock_http) # type: ignore
response = await extraction.list()
assert len(response.items) == 1
@pytest.mark.asyncio
async def test_batch(self) -> None:
"""Test creating a batch job asynchronously"""
mock_http = MockAsyncHTTPClient(responses={
"POST:/webdata/batch/extractions": {
"id": "batch_async_123",
"status": "pending",
"totalUrls": 3,
}
})
extraction = AsyncExtraction(mock_http) # type: ignore
response = await extraction.batch(CreateBatchExtractionsRequest(
urls=["https://example.com/p1", "https://example.com/p2"],
mode="markdown",
))
assert response.id == "batch_async_123"
@pytest.mark.asyncio
async def test_extract_and_wait(self) -> None:
"""Test async extract_and_wait"""
call_count = [0]
async def mock_get(path: str):
if "/webdata/extractions/ext_123" in path:
call_count[0] += 1
return {
"id": "ext_123",
"organizationId": "org_1",
"environment": "production",
"url": "https://example.com/article",
"mode": "markdown",
"status": "completed",
"markdown": "# Extracted",
"createdAt": "2024-01-15T10:00:00Z",
}
return {"success": True}
async def mock_post(path: str, body=None):
if "/webdata/extractions" in path:
return {"id": "ext_123", "status": "pending"}
return {"success": True}
mock_http = MockAsyncHTTPClient()
mock_http.get = mock_get # type: ignore
mock_http.post = mock_post # type: ignore
extraction = AsyncExtraction(mock_http) # type: ignore
result = await extraction.extract_and_wait(
CreateExtractionRequest(url="https://example.com/article", mode="markdown"),
poll_interval=0.01,
timeout=1.0,
)
assert result.status == "completed"
assert call_count[0] >= 1