-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_endpoints.py
More file actions
462 lines (355 loc) · 16.8 KB
/
test_api_endpoints.py
File metadata and controls
462 lines (355 loc) · 16.8 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
"""
Test transcript API endpoints.
These tests verify that the transcript API endpoints correctly handle
requests and integrate with the TranscriptOrchestrator service.
Following TDD: Write tests first, watch them fail, then implement to pass.
"""
from unittest.mock import Mock
import pytest
from fastapi.testclient import TestClient
from fastapi import status
from youtube_transcript.services.fetcher import TranscriptResult
from youtube_transcript.api.app import app
def override_orchestrator(mock_orchestrator):
"""Helper to override the orchestrator dependency."""
from youtube_transcript.api.endpoints import get_orchestrator
app.dependency_overrides[get_orchestrator] = lambda: mock_orchestrator
def clear_overrides():
"""Clear all dependency overrides."""
app.dependency_overrides = {}
class TestTranscriptRequestModel:
"""Test TranscriptRequest Pydantic model."""
def test_transcript_request_model_exists(self):
"""Test that TranscriptRequest model is defined."""
from youtube_transcript.api.models import TranscriptRequest
assert TranscriptRequest is not None
def test_transcript_request_has_url_field(self):
"""Test that TranscriptRequest has url field."""
from youtube_transcript.api.models import TranscriptRequest
from pydantic import ValidationError
# Valid URL
request = TranscriptRequest(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
assert request.url == "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
# Missing URL should raise validation error
with pytest.raises(ValidationError):
TranscriptRequest()
def test_transcript_request_has_optional_languages_field(self):
"""Test that TranscriptRequest has optional languages field."""
from youtube_transcript.api.models import TranscriptRequest
# Without languages
request1 = TranscriptRequest(url="https://youtu.be/dQw4w9WgXcQ")
assert request1.languages is None
# With languages
request2 = TranscriptRequest(
url="https://youtu.be/dQw4w9WgXcQ",
languages=["en", "es"]
)
assert request2.languages == ["en", "es"]
def test_transcript_request_validates_url_format(self):
"""Test that TranscriptRequest validates URL format."""
from youtube_transcript.api.models import TranscriptRequest
from pydantic import ValidationError
# Invalid URLs
invalid_urls = [
"not-a-url",
"ftp://example.com",
"",
]
for invalid_url in invalid_urls:
with pytest.raises(ValidationError):
TranscriptRequest(url=invalid_url)
class TestTranscriptResponseModel:
"""Test TranscriptResponse Pydantic model."""
def test_transcript_response_model_exists(self):
"""Test that TranscriptResponse model is defined."""
from youtube_transcript.api.models import TranscriptResponse
assert TranscriptResponse is not None
def test_transcript_response_has_required_fields(self):
"""Test that TranscriptResponse has all required fields."""
from youtube_transcript.api.models import TranscriptResponse
response = TranscriptResponse(
video_id="dQw4w9WgXcQ",
transcript="Never gonna give you up",
language="en",
transcript_type="manual",
)
assert response.video_id == "dQw4w9WgXcQ"
assert response.transcript == "Never gonna give you up"
assert response.language == "en"
assert response.transcript_type == "manual"
def test_transcript_response_from_transcript_result(self):
"""Test creating TranscriptResponse from TranscriptResult."""
from youtube_transcript.api.models import TranscriptResponse
from youtube_transcript.services.fetcher import TranscriptResult
result = TranscriptResult(
video_id="j9rZxAF3C0I",
transcript="Test transcript",
language="en",
transcript_type="auto",
duration=100.0,
)
response = TranscriptResponse.from_transcript_result(result)
assert response.video_id == "j9rZxAF3C0I"
assert response.transcript == "Test transcript"
assert response.language == "en"
assert response.transcript_type == "auto"
class TestErrorModel:
"""Test error response models."""
def test_error_response_model_exists(self):
"""Test that ErrorResponse model is defined."""
from youtube_transcript.api.models import ErrorResponse
assert ErrorResponse is not None
def test_error_response_has_error_and_detail(self):
"""Test that ErrorResponse has error and detail fields."""
from youtube_transcript.api.models import ErrorResponse
error = ErrorResponse(error="Not Found", detail="Transcript not found")
assert error.error == "Not Found"
assert error.detail == "Transcript not found"
class TestPostTranscriptEndpoint:
"""Test POST /api/transcript endpoint."""
def test_post_transcript_endpoint_exists(self, test_client: TestClient):
"""Test that POST /api/transcript endpoint is registered."""
response = test_client.post("/api/transcript", json={"url": "https://youtu.be/abc"})
# Should process request (might return 404 for invalid video ID or validation error)
assert response.status_code in [status.HTTP_404_NOT_FOUND, status.HTTP_422_UNPROCESSABLE_ENTITY]
# Verify it's our endpoint responding
data = response.json()
assert "error" in data or "detail" in data
def test_post_transcript_with_valid_url(self, test_client: TestClient):
"""Test POST /api/transcript with valid YouTube URL."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='dQw4w9WgXcQ',
transcript='Never gonna give you up',
language='en',
transcript_type='manual',
duration=212.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}
)
clear_overrides()
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["video_id"] == "dQw4w9WgXcQ"
assert data["transcript"] == "Never gonna give you up"
assert data["language"] == "en"
def test_post_transcript_with_short_url(self, test_client: TestClient):
"""Test POST /api/transcript with youtu.be short URL."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='dQw4w9WgXcQ',
transcript='Rick Astley',
language='en',
transcript_type='manual',
duration=200.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={"url": "https://youtu.be/dQw4w9WgXcQ"}
)
clear_overrides()
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["video_id"] == "dQw4w9WgXcQ"
def test_post_transcript_with_languages(self, test_client: TestClient):
"""Test POST /api/transcript with language preference."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='dQw4w9WgXcQ',
transcript='Spanish transcript',
language='es',
transcript_type='manual',
duration=100.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"languages": ["es", "en"]
}
)
clear_overrides()
assert response.status_code == status.HTTP_200_OK
mock_orchestrator.get_transcript.assert_called_once_with('dQw4w9WgXcQ', languages=['es', 'en'])
def test_post_transcript_not_found(self, test_client: TestClient):
"""Test POST /api/transcript when transcript not found."""
mock_orchestrator = Mock()
mock_orchestrator.get_transcript.return_value = None
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={"url": "https://www.youtube.com/watch?v=nonexistent"}
)
clear_overrides()
assert response.status_code == status.HTTP_404_NOT_FOUND
data = response.json()
assert "error" in data or "detail" in data
def test_post_transcript_missing_url(self, test_client: TestClient):
"""Test POST /api/transcript without URL."""
response = test_client.post("/api/transcript", json={})
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
def test_post_transcript_invalid_url(self, test_client: TestClient):
"""Test POST /api/transcript with invalid URL."""
response = test_client.post(
"/api/transcript",
json={"url": "not-a-valid-url"}
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
def test_post_transcript_with_invalid_youtube_url(self, test_client: TestClient):
"""Test POST /api/transcript with invalid YouTube URL format."""
mock_orchestrator = Mock()
mock_orchestrator.get_transcript.return_value = None
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={"url": "https://example.com/watch?v=abc"}
)
clear_overrides()
# URL passes validation but transcript not found
assert response.status_code == status.HTTP_404_NOT_FOUND
class TestGetTranscriptByVideoId:
"""Test GET /api/transcript/{video_id} endpoint."""
def test_get_transcript_by_video_id_endpoint_exists(self, test_client: TestClient):
"""Test that GET /api/transcript/{video_id} endpoint is registered."""
response = test_client.get("/api/transcript/dQw4w9WgXcQ")
# Endpoint should process the request (might return 404 if transcript not found)
assert response.status_code in [status.HTTP_404_NOT_FOUND, status.HTTP_500_INTERNAL_SERVER_ERROR]
# Verify it's our endpoint responding
data = response.json()
assert "error" in data or "detail" in data
def test_get_transcript_by_video_id_success(self, test_client: TestClient):
"""Test GET /api/transcript/{video_id} with valid video ID."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='dQw4w9WgXcQ',
transcript='Never gonna give you up',
language='en',
transcript_type='manual',
duration=212.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
response = test_client.get("/api/transcript/dQw4w9WgXcQ")
clear_overrides()
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["video_id"] == "dQw4w9WgXcQ"
assert data["transcript"] == "Never gonna give you up"
mock_orchestrator.get_transcript.assert_called_once_with('dQw4w9WgXcQ', languages=None)
def test_get_transcript_by_video_id_with_languages(self, test_client: TestClient):
"""Test GET /api/transcript/{video_id} with language query parameter."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='j9rZxAF3C0I',
transcript='Spanish content',
language='es',
transcript_type='manual',
duration=100.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
response = test_client.get("/api/transcript/j9rZxAF3C0I?languages=es&languages=en")
clear_overrides()
assert response.status_code == status.HTTP_200_OK
mock_orchestrator.get_transcript.assert_called_once_with('j9rZxAF3C0I', languages=['es', 'en'])
def test_get_transcript_by_video_id_not_found(self, test_client: TestClient):
"""Test GET /api/transcript/{video_id} when not found."""
mock_orchestrator = Mock()
mock_orchestrator.get_transcript.return_value = None
override_orchestrator(mock_orchestrator)
response = test_client.get("/api/transcript/nonexistent")
clear_overrides()
assert response.status_code == status.HTTP_404_NOT_FOUND
data = response.json()
assert "error" in data or "detail" in data
def test_get_transcript_by_video_id_invalid_id(self, test_client: TestClient):
"""Test GET /api/transcript/{video_id} with invalid video ID."""
mock_orchestrator = Mock()
mock_orchestrator.get_transcript.return_value = None
override_orchestrator(mock_orchestrator)
response = test_client.get("/api/transcript/invalid-id-with-dashes")
clear_overrides()
# Should attempt to fetch but return 404
assert response.status_code == status.HTTP_404_NOT_FOUND
class TestAPIEndpointIntegration:
"""Test integration between endpoints and services."""
def test_post_and_get_return_same_transcript(self, test_client: TestClient):
"""Test that POST and GET endpoints return consistent data."""
mock_orchestrator = Mock()
mock_result = TranscriptResult(
video_id='j9rZxAF3C0I',
transcript='Consistent transcript',
language='en',
transcript_type='manual',
duration=150.0,
)
mock_orchestrator.get_transcript.return_value = mock_result
override_orchestrator(mock_orchestrator)
# POST request
post_response = test_client.post(
"/api/transcript",
json={"url": "https://www.youtube.com/watch?v=j9rZxAF3C0I"}
)
# GET request
get_response = test_client.get("/api/transcript/j9rZxAF3C0I")
clear_overrides()
assert post_response.status_code == status.HTTP_200_OK
assert get_response.status_code == status.HTTP_200_OK
post_data = post_response.json()
get_data = get_response.json()
assert post_data["video_id"] == get_data["video_id"]
assert post_data["transcript"] == get_data["transcript"]
def test_endpoints_handle_orchestrator_errors(self, test_client: TestClient):
"""Test that endpoints handle orchestrator errors gracefully."""
mock_orchestrator = Mock()
mock_orchestrator.get_transcript.side_effect = Exception("Service error")
override_orchestrator(mock_orchestrator)
response = test_client.post(
"/api/transcript",
json={"url": "https://www.youtube.com/watch?v=j9rZxAF3C0I"}
)
clear_overrides()
# Should return 500 Internal Server Error
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
class TestOpenAPIDocumentation:
"""Test OpenAPI schema generation."""
def test_transcript_endpoints_in_openapi_schema(self):
"""Test that transcript endpoints are documented in OpenAPI schema."""
from youtube_transcript.api.app import app
schema = app.openapi()
# Check paths exist
assert "/api/transcript" in schema["paths"]
assert "/api/transcript/{video_id}" in schema["paths"]
# Check POST endpoint
assert "post" in schema["paths"]["/api/transcript"]
# Check GET endpoint
assert "get" in schema["paths"]["/api/transcript/{video_id}"]
def test_transcript_request_schema_is_documented(self):
"""Test that TranscriptRequest schema is in OpenAPI."""
from youtube_transcript.api.app import app
schema = app.openapi()
# Check components exist
assert "components" in schema
assert "schemas" in schema["components"]
# TranscriptRequest schema should be referenced
post_spec = schema["paths"]["/api/transcript"]["post"]
assert "requestBody" in post_spec
def test_transcript_response_schema_is_documented(self):
"""Test that TranscriptResponse schema is in OpenAPI."""
from youtube_transcript.api.app import app
schema = app.openapi()
# Check response schemas
post_spec = schema["paths"]["/api/transcript"]["post"]
assert "responses" in post_spec
assert "200" in post_spec["responses"]
get_spec = schema["paths"]["/api/transcript/{video_id}"]["get"]
assert "responses" in get_spec
assert "200" in get_spec["responses"]