-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_routers.py
More file actions
754 lines (616 loc) · 31.2 KB
/
test_routers.py
File metadata and controls
754 lines (616 loc) · 31.2 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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
"""
Tests for api/routers/ endpoints.
Tests the modular router endpoints.
"""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from api.main import app
from api.routers.plots import (
_calculate_contextual_counts,
_calculate_global_counts,
_calculate_or_counts,
_image_matches_groups,
)
from core.database import get_db
from tests.conftest import TEST_IMAGE_URL, TEST_THUMB_URL
# Path to patch is_db_configured - it's now in api.dependencies
DB_CONFIG_PATCH = "api.dependencies.is_db_configured"
@pytest.fixture
def client() -> TestClient:
"""Create a test client for the FastAPI app."""
return TestClient(app)
@pytest.fixture
def db_client():
"""Create a test client with mocked database dependency.
This fixture overrides get_db to return a mock session and
patches is_db_configured to return True, enabling proper
testing of endpoints that use optional_db.
"""
mock_session = AsyncMock()
async def mock_get_db():
yield mock_session
app.dependency_overrides[get_db] = mock_get_db
with patch(DB_CONFIG_PATCH, return_value=True):
client = TestClient(app)
yield client, mock_session
app.dependency_overrides.clear()
@pytest.fixture
def mock_spec():
"""Create a mock spec with implementation."""
mock_impl = MagicMock()
mock_impl.library_id = "matplotlib"
mock_impl.library = MagicMock()
mock_impl.library.name = "Matplotlib"
mock_impl.preview_url = TEST_IMAGE_URL
mock_impl.preview_thumb = TEST_THUMB_URL
mock_impl.preview_html = None
mock_impl.quality_score = 92.5
mock_impl.code = "import matplotlib.pyplot as plt"
mock_impl.generated_at = None
mock_impl.generated_by = "claude"
mock_impl.python_version = "3.13"
mock_impl.library_version = "3.10.0"
# Review fields (must be proper types, not MagicMock)
mock_impl.review_image_description = "A scatter plot showing data points"
mock_impl.review_criteria_checklist = {"visual_quality": {"score": 36, "max": 40}}
mock_impl.review_verdict = "APPROVED"
mock_impl.review_strengths = ["Clean code", "Good visualization"]
mock_impl.review_weaknesses = ["Could use better labels"]
mock_spec = MagicMock()
mock_spec.id = "scatter-basic"
mock_spec.title = "Basic Scatter Plot"
mock_spec.description = "A basic scatter plot"
mock_spec.applications = ["data visualization"]
mock_spec.data = ["numeric"]
mock_spec.notes = ["Use for 2D data"]
mock_spec.tags = {
"plot_type": ["scatter"],
"domain": ["statistics"],
"data_type": ["numeric"],
"features": ["basic"],
}
mock_spec.issue = 42
mock_spec.suggested = "contributor"
mock_spec.created = None # Must be None or datetime, not MagicMock
mock_spec.updated = None # Must be None or datetime, not MagicMock
mock_spec.impls = [mock_impl]
return mock_spec
@pytest.fixture
def mock_lib():
"""Create a mock library."""
mock_lib = MagicMock()
mock_lib.id = "matplotlib"
mock_lib.name = "Matplotlib"
mock_lib.version = "3.10.0"
mock_lib.documentation_url = "https://matplotlib.org"
mock_lib.description = "Comprehensive library for visualizations"
return mock_lib
class TestStatsRouter:
"""Tests for stats router."""
def test_stats_without_db(self, client: TestClient) -> None:
"""Stats should return zeros when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/stats")
assert response.status_code == 200
data = response.json()
assert data["specs"] == 0
assert data["plots"] == 0
assert "libraries" in data
def test_stats_with_db(self, db_client, mock_spec, mock_lib) -> None:
"""Stats should return counts when DB is configured."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
mock_lib_repo = MagicMock()
mock_lib_repo.get_all = AsyncMock(return_value=[mock_lib])
with (
patch("api.routers.stats.get_cache", return_value=None),
patch("api.routers.stats.set_cache"),
patch("api.routers.stats.SpecRepository", return_value=mock_spec_repo),
patch("api.routers.stats.LibraryRepository", return_value=mock_lib_repo),
):
response = client.get("/stats")
assert response.status_code == 200
data = response.json()
assert data["specs"] == 1
assert data["plots"] == 1
assert data["libraries"] == 1
def test_stats_cached(self, db_client) -> None:
"""Stats should return cached response when available."""
client, _ = db_client
cached_response = {"specs": 5, "plots": 10, "libraries": 9}
with patch("api.routers.stats.get_cache", return_value=cached_response):
response = client.get("/stats")
assert response.status_code == 200
data = response.json()
assert data["specs"] == 5
assert data["plots"] == 10
class TestLibrariesRouter:
"""Tests for libraries router."""
def test_libraries_without_db(self, client: TestClient) -> None:
"""Libraries should return seed data when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/libraries")
assert response.status_code == 200
data = response.json()
assert "libraries" in data
assert len(data["libraries"]) > 0
def test_library_images_without_db(self, client: TestClient) -> None:
"""Library images should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/libraries/matplotlib/images")
assert response.status_code == 503
def test_library_images_invalid_library(self, client: TestClient) -> None:
"""Library images should return 404 for invalid library."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[])
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.libraries.get_cache", return_value=None),
patch("api.routers.libraries.set_cache"),
patch("api.routers.libraries.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/libraries/invalid_lib/images")
assert response.status_code == 404
def test_libraries_with_db(self, db_client, mock_lib) -> None:
"""Libraries should return data from DB when configured."""
client, _ = db_client
mock_lib_repo = MagicMock()
mock_lib_repo.get_all = AsyncMock(return_value=[mock_lib])
with (
patch("api.routers.libraries.get_cache", return_value=None),
patch("api.routers.libraries.set_cache"),
patch("api.routers.libraries.LibraryRepository", return_value=mock_lib_repo),
):
response = client.get("/libraries")
assert response.status_code == 200
data = response.json()
assert "libraries" in data
assert len(data["libraries"]) == 1
assert data["libraries"][0]["id"] == "matplotlib"
def test_libraries_cache_hit(self, db_client) -> None:
"""Libraries should return cached data when available."""
client, _ = db_client
cached_data = {"libraries": [{"id": "cached_lib", "name": "Cached"}]}
with patch("api.routers.libraries.get_cache", return_value=cached_data):
response = client.get("/libraries")
assert response.status_code == 200
data = response.json()
assert data["libraries"][0]["id"] == "cached_lib"
def test_library_images_with_db(self, db_client, mock_spec) -> None:
"""Library images should return images from DB."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
with (
patch("api.routers.libraries.get_cache", return_value=None),
patch("api.routers.libraries.set_cache"),
patch("api.routers.libraries.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/libraries/matplotlib/images")
assert response.status_code == 200
data = response.json()
assert data["library"] == "matplotlib"
assert len(data["images"]) == 1
assert data["images"][0]["spec_id"] == "scatter-basic"
def test_library_images_cache_hit(self, db_client) -> None:
"""Library images should return cached data when available."""
client, _ = db_client
cached_data = {"library": "matplotlib", "images": [{"spec_id": "cached"}]}
with patch("api.routers.libraries.get_cache", return_value=cached_data):
response = client.get("/libraries/matplotlib/images")
assert response.status_code == 200
data = response.json()
assert data["images"][0]["spec_id"] == "cached"
class TestSpecsRouter:
"""Tests for specs router."""
def test_specs_without_db(self, client: TestClient) -> None:
"""Specs should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/specs")
assert response.status_code == 503
def test_spec_detail_without_db(self, client: TestClient) -> None:
"""Spec detail should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/specs/scatter-basic")
assert response.status_code == 503
def test_spec_images_without_db(self, client: TestClient) -> None:
"""Spec images should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/specs/scatter-basic/images")
assert response.status_code == 503
def test_specs_with_db(self, client: TestClient, mock_spec) -> None:
"""Specs should return data from DB when configured."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.specs.get_cache", return_value=None),
patch("api.routers.specs.set_cache"),
patch("api.routers.specs.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/specs")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) == 1
assert data[0]["id"] == "scatter-basic"
def test_spec_detail_with_db(self, client: TestClient, mock_spec) -> None:
"""Spec detail should return spec from DB."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.specs.get_cache", return_value=None),
patch("api.routers.specs.set_cache"),
patch("api.routers.specs.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/specs/scatter-basic")
assert response.status_code == 200
data = response.json()
assert data["id"] == "scatter-basic"
def test_spec_detail_not_found(self, client: TestClient) -> None:
"""Spec detail should return 404 when not found."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=None)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.specs.get_cache", return_value=None),
patch("api.routers.specs.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/specs/nonexistent")
assert response.status_code == 404
class TestDownloadRouter:
"""Tests for download router."""
def test_download_without_db(self, client: TestClient) -> None:
"""Download should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/download/scatter-basic/matplotlib")
assert response.status_code == 503
def test_download_spec_not_found(self, client: TestClient) -> None:
"""Download should return 404 when spec not found."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=None)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.download.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/download/nonexistent/matplotlib")
assert response.status_code == 404
def test_download_impl_not_found(self, client: TestClient, mock_spec) -> None:
"""Download should return 404 when implementation not found."""
mock_spec.impls = []
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.download.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/download/scatter-basic/seaborn")
assert response.status_code == 404
def test_download_success(self, client: TestClient, mock_spec) -> None:
"""Download should return image when spec and impl found."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
# Mock httpx response
mock_response = MagicMock()
mock_response.content = b"fake image content"
mock_response.raise_for_status = MagicMock()
mock_httpx_client = AsyncMock()
mock_httpx_client.get = AsyncMock(return_value=mock_response)
mock_httpx_client.__aenter__ = AsyncMock(return_value=mock_httpx_client)
mock_httpx_client.__aexit__ = AsyncMock(return_value=None)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.download.SpecRepository", return_value=mock_spec_repo),
patch("api.routers.download.httpx.AsyncClient", return_value=mock_httpx_client),
):
response = client.get("/download/scatter-basic/matplotlib")
assert response.status_code == 200
assert response.headers["content-type"] == "image/png"
assert "attachment" in response.headers["content-disposition"]
assert response.content == b"fake image content"
def test_download_gcs_error(self, client: TestClient, mock_spec) -> None:
"""Download should return 502 when GCS fetch fails."""
import httpx
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
mock_httpx_client = AsyncMock()
mock_httpx_client.get = AsyncMock(side_effect=httpx.HTTPError("GCS error"))
mock_httpx_client.__aenter__ = AsyncMock(return_value=mock_httpx_client)
mock_httpx_client.__aexit__ = AsyncMock(return_value=None)
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.download.SpecRepository", return_value=mock_spec_repo),
patch("api.routers.download.httpx.AsyncClient", return_value=mock_httpx_client),
):
response = client.get("/download/scatter-basic/matplotlib")
assert response.status_code == 502
class TestSeoRouter:
"""Tests for SEO router."""
def test_sitemap_structure(self, client: TestClient) -> None:
"""Sitemap should return valid XML structure."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/sitemap.xml")
assert response.status_code == 200
assert response.headers["content-type"] == "application/xml"
content = response.text
assert '<?xml version="1.0"' in content
assert "<urlset" in content
# Check for homepage URL as proper XML element
assert "<loc>https://pyplots.ai/</loc>" in content
def test_sitemap_with_db(self, db_client, mock_spec) -> None:
"""Sitemap should include specs and implementations from DB."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
with (
patch("api.routers.seo.get_cache", return_value=None),
patch("api.routers.seo.set_cache"),
patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/sitemap.xml")
assert response.status_code == 200
# URL format: /, /catalog, /{spec_id}, /{spec_id}/{library_id}
assert "https://pyplots.ai/catalog" in response.text
# Overview page
assert "https://pyplots.ai/scatter-basic</loc>" in response.text
# Implementation page
assert "https://pyplots.ai/scatter-basic/matplotlib</loc>" in response.text
class TestSeoProxyRouter:
"""Tests for SEO proxy endpoints (bot-optimized pages)."""
def test_seo_home(self, client: TestClient) -> None:
"""SEO home page should return HTML with og:tags."""
response = client.get("/seo-proxy/")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
assert "og:title" in response.text
assert "pyplots.ai" in response.text
assert "og:image" in response.text
assert "twitter:card" in response.text
def test_seo_catalog(self, client: TestClient) -> None:
"""SEO catalog page should return HTML with og:tags."""
response = client.get("/seo-proxy/catalog")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
assert "Catalog" in response.text
assert "og:title" in response.text
assert "https://pyplots.ai/catalog" in response.text
def test_seo_spec_overview_without_db(self, client: TestClient) -> None:
"""SEO spec overview should return fallback HTML when DB unavailable."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/seo-proxy/scatter-basic")
assert response.status_code == 200
assert "og:title" in response.text
assert "scatter-basic" in response.text
assert "og-image.png" in response.text # Default image
def test_seo_spec_overview_with_db(self, db_client, mock_spec) -> None:
"""SEO spec overview should return HTML with spec title from DB."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
with patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo):
response = client.get("/seo-proxy/scatter-basic")
assert response.status_code == 200
assert "Basic Scatter Plot" in response.text
assert "og:title" in response.text
assert "https://pyplots.ai/scatter-basic" in response.text
def test_seo_spec_overview_not_found(self, db_client) -> None:
"""SEO spec overview should return 404 when spec not found."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=None)
with patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo):
response = client.get("/seo-proxy/nonexistent-spec")
assert response.status_code == 404
def test_seo_spec_implementation_without_db(self, client: TestClient) -> None:
"""SEO spec implementation should return fallback HTML when DB unavailable."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/seo-proxy/scatter-basic/matplotlib")
assert response.status_code == 200
assert "og:title" in response.text
assert "scatter-basic" in response.text
assert "matplotlib" in response.text
assert "og-image.png" in response.text # Default image
def test_seo_spec_implementation_with_preview_url(self, db_client, mock_spec) -> None:
"""SEO spec implementation should use preview_url from implementation."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec)
with patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo):
response = client.get("/seo-proxy/scatter-basic/matplotlib")
assert response.status_code == 200
assert "Basic Scatter Plot" in response.text
assert "matplotlib" in response.text
# Should have actual preview URL from implementation
assert TEST_IMAGE_URL in response.text or "og:image" in response.text
def test_seo_spec_implementation_not_found(self, db_client) -> None:
"""SEO spec implementation should return 404 when spec not found."""
client, _ = db_client
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=None)
with patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo):
response = client.get("/seo-proxy/nonexistent-spec/matplotlib")
assert response.status_code == 404
def test_seo_spec_implementation_fallback_image(self, db_client, mock_spec) -> None:
"""SEO spec implementation should use default image when impl has no preview."""
client, _ = db_client
# Create a spec with implementation that has no preview_url
mock_impl_no_preview = MagicMock()
mock_impl_no_preview.library_id = "seaborn"
mock_impl_no_preview.preview_url = None
mock_spec_no_preview = MagicMock()
mock_spec_no_preview.id = "scatter-basic"
mock_spec_no_preview.title = "Basic Scatter Plot"
mock_spec_no_preview.description = "A basic scatter plot"
mock_spec_no_preview.impls = [mock_impl_no_preview]
mock_spec_repo = MagicMock()
mock_spec_repo.get_by_id = AsyncMock(return_value=mock_spec_no_preview)
with patch("api.routers.seo.SpecRepository", return_value=mock_spec_repo):
response = client.get("/seo-proxy/scatter-basic/seaborn")
assert response.status_code == 200
assert "og-image.png" in response.text # Default image used
class TestPlotsRouter:
"""Tests for plots filter router."""
def test_filter_without_db(self, client: TestClient) -> None:
"""Filter should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/plots/filter")
assert response.status_code == 503
def test_filter_with_params_without_db(self, client: TestClient) -> None:
"""Filter with params should return 503 when DB not configured."""
with patch(DB_CONFIG_PATCH, return_value=False):
response = client.get("/plots/filter?lib=matplotlib")
assert response.status_code == 503
def test_filter_with_db(self, client: TestClient, mock_spec) -> None:
"""Filter should return images from DB."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.plots.get_cache", return_value=None),
patch("api.routers.plots.set_cache"),
patch("api.routers.plots.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/plots/filter")
assert response.status_code == 200
data = response.json()
assert "images" in data
assert "counts" in data
assert data["total"] == 1
def test_filter_with_lib_param(self, client: TestClient, mock_spec) -> None:
"""Filter with lib param should filter by library."""
mock_spec_repo = MagicMock()
mock_spec_repo.get_all = AsyncMock(return_value=[mock_spec])
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.plots.get_cache", return_value=None),
patch("api.routers.plots.set_cache"),
patch("api.routers.plots.SpecRepository", return_value=mock_spec_repo),
):
response = client.get("/plots/filter?lib=matplotlib")
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
def test_filter_cached(self, client: TestClient) -> None:
"""Filter should return cached response when available."""
cached_response = MagicMock()
cached_response.total = 5
cached_response.images = []
cached_response.counts = {}
cached_response.globalCounts = {}
cached_response.orCounts = []
with (
patch(DB_CONFIG_PATCH, return_value=True),
patch("api.routers.plots.get_cache", return_value=cached_response),
):
response = client.get("/plots/filter")
assert response.status_code == 200
class TestPlotsHelperFunctions:
"""Tests for plots.py helper functions."""
def test_image_matches_groups_empty(self) -> None:
"""Empty groups should match any image."""
spec_lookup = {"scatter-basic": {"tags": {"plot_type": ["scatter"]}}}
assert _image_matches_groups("scatter-basic", "matplotlib", [], spec_lookup) is True
def test_image_matches_groups_lib_match(self) -> None:
"""Library filter should match correct library."""
spec_lookup = {"scatter-basic": {"tags": {}}}
groups = [{"category": "lib", "values": ["matplotlib"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_lib_no_match(self) -> None:
"""Library filter should not match wrong library."""
spec_lookup = {"scatter-basic": {"tags": {}}}
groups = [{"category": "lib", "values": ["seaborn"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is False
def test_image_matches_groups_spec_match(self) -> None:
"""Spec filter should match correct spec."""
spec_lookup = {"scatter-basic": {"tags": {}}}
groups = [{"category": "spec", "values": ["scatter-basic"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_plot_type_match(self) -> None:
"""Plot type filter should match correct tag."""
spec_lookup = {"scatter-basic": {"tags": {"plot_type": ["scatter"]}}}
groups = [{"category": "plot", "values": ["scatter"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_data_type_match(self) -> None:
"""Data type filter should match correct tag."""
spec_lookup = {"scatter-basic": {"tags": {"data_type": ["numeric"]}}}
groups = [{"category": "data", "values": ["numeric"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_domain_match(self) -> None:
"""Domain filter should match correct tag."""
spec_lookup = {"scatter-basic": {"tags": {"domain": ["statistics"]}}}
groups = [{"category": "dom", "values": ["statistics"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_features_match(self) -> None:
"""Features filter should match correct tag."""
spec_lookup = {"scatter-basic": {"tags": {"features": ["basic"]}}}
groups = [{"category": "feat", "values": ["basic"]}]
assert _image_matches_groups("scatter-basic", "matplotlib", groups, spec_lookup) is True
def test_image_matches_groups_spec_not_in_lookup(self) -> None:
"""Spec not in lookup should not match."""
spec_lookup = {}
assert _image_matches_groups("unknown", "matplotlib", [], spec_lookup) is False
def test_calculate_global_counts(self) -> None:
"""Global counts should tally all implementations."""
mock_impl = MagicMock()
mock_impl.library_id = "matplotlib"
mock_impl.preview_url = TEST_IMAGE_URL
mock_spec = MagicMock()
mock_spec.id = "scatter-basic"
mock_spec.tags = {"plot_type": ["scatter"], "domain": ["statistics"]}
mock_spec.impls = [mock_impl]
counts = _calculate_global_counts([mock_spec])
assert counts["lib"]["matplotlib"] == 1
assert counts["spec"]["scatter-basic"] == 1
assert counts["plot"]["scatter"] == 1
assert counts["dom"]["statistics"] == 1
def test_calculate_global_counts_no_impls(self) -> None:
"""Spec without impls should not be counted."""
mock_spec = MagicMock()
mock_spec.id = "scatter-basic"
mock_spec.impls = []
counts = _calculate_global_counts([mock_spec])
assert counts["lib"] == {}
def test_calculate_global_counts_no_preview(self) -> None:
"""Impl without preview_url should not be counted."""
mock_impl = MagicMock()
mock_impl.library_id = "matplotlib"
mock_impl.preview_url = None
mock_spec = MagicMock()
mock_spec.id = "scatter-basic"
mock_spec.tags = {}
mock_spec.impls = [mock_impl]
counts = _calculate_global_counts([mock_spec])
assert counts["lib"] == {}
def test_calculate_contextual_counts(self) -> None:
"""Contextual counts should tally filtered images."""
images = [
{"spec_id": "scatter-basic", "library": "matplotlib"},
{"spec_id": "scatter-basic", "library": "seaborn"},
]
spec_tags = {"scatter-basic": {"plot_type": ["scatter"]}}
counts = _calculate_contextual_counts(images, spec_tags)
assert counts["lib"]["matplotlib"] == 1
assert counts["lib"]["seaborn"] == 1
assert counts["spec"]["scatter-basic"] == 2
assert counts["plot"]["scatter"] == 2
def test_calculate_or_counts_empty_groups(self) -> None:
"""Empty groups should return empty or_counts."""
counts = _calculate_or_counts([], [], {}, {})
assert counts == []
def test_calculate_or_counts_single_group(self) -> None:
"""Single group should count all matching images."""
groups = [{"category": "lib", "values": ["matplotlib"]}]
images = [
{"spec_id": "scatter-basic", "library": "matplotlib"},
{"spec_id": "scatter-basic", "library": "seaborn"},
]
spec_lookup = {"scatter-basic": {"tags": {}}}
spec_tags = {"scatter-basic": {}}
counts = _calculate_or_counts(groups, images, spec_tags, spec_lookup)
assert len(counts) == 1
# Each library appears once across all images
assert counts[0]["matplotlib"] == 1
assert counts[0]["seaborn"] == 1