-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sdk_fixtures.py
More file actions
712 lines (573 loc) · 30.6 KB
/
Copy pathtest_sdk_fixtures.py
File metadata and controls
712 lines (573 loc) · 30.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
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
"""Test SDK behavior against real API responses (fixture-based tests).
This module uses cached API responses to validate that the SDK:
1. Builds correct URLs for diverse query patterns
2. Parses responses correctly
3. Handles all field types and operators
4. Respects pagination and sorting
5. Transforms data correctly (tidy format, etc.)
Fixtures are discovered from live GoaT API via discover_fixtures.py.
Usage:
# Step 1: Cache fixtures from live API (one-time)
python tests/python/discover_fixtures.py --update
# Step 2a: Run pytest directly on cached fixtures
pytest tests/python/test_sdk_fixtures.py -v
# Step 2b: Or use the convenience script to test a generated SDK
bash scripts/test_sdk_fixtures.sh --site goat --python
To update cached fixtures:
python tests/python/discover_fixtures.py --update
See:
- docs/test-fixtures-quick-reference.md — Quick reference
- docs/test-fixtures-usage.md — Complete guide
- docs/testing-generated-sdks.md — Testing generated SDKs
"""
import json
from pathlib import Path
from typing import Any
import pytest
from cli_generator import QueryBuilder, ReportBuilder, parse_response_status
PROJECT_ROOT = Path(__file__).parent.parent.parent
def _find_fixtures_dir() -> Path:
"""Find the appropriate fixtures directory (site-specific or generator).
Searches for fixtures in this order:
1. Site-specific caches: tests/python/fixtures-{site}/
2. Generator cache: tests/python/fixtures/
Returns:
Path to the fixtures directory to use.
"""
fixtures_base = PROJECT_ROOT / "tests/python"
return next(
(
site_dir
for site_dir in sorted(fixtures_base.glob("fixtures-*"))
if site_dir.is_dir() and list(site_dir.glob("*.json"))
),
fixtures_base / "fixtures",
)
FIXTURES_CACHE_DIR = _find_fixtures_dir()
# ── Load fixture metadata ────────────────────────────────────────────────────
def load_all_fixtures() -> dict[str, dict[str, Any]]:
"""Load all cached fixture responses from disk.
Returns:
Dict mapping fixture names to cached API responses.
"""
fixtures = {}
if not FIXTURES_CACHE_DIR.exists():
pytest.skip("Fixtures not cached. Run: python tests/python/discover_fixtures.py --update")
for cache_file in FIXTURES_CACHE_DIR.glob("*.json"):
name = cache_file.stem
with open(cache_file) as f:
fixtures[name] = json.load(f)
return fixtures
# ── Fixture mapping to QueryBuilder patterns ─────────────────────────────────
FIXTURE_TO_BUILDER = {
"basic_taxon_search": lambda: QueryBuilder("taxon"),
"numeric_field_integer_filter": lambda: QueryBuilder("taxon").add_attribute("chromosome_count", "gt", "10"),
"numeric_field_range": lambda: QueryBuilder("taxon")
.add_attribute("genome_size", "ge", "1G")
.add_attribute("genome_size", "le", "3G"),
"enum_field_filter": lambda: QueryBuilder("taxon").add_attribute("assembly_level", "eq", "complete genome"),
"taxa_filter_tree": lambda: QueryBuilder("taxon").set_taxa(["Mammalia"], filter_type="tree").set_rank("species"),
"taxa_with_negative_filter": lambda: QueryBuilder("taxon")
.set_taxa(["Mammalia", "!Rodentia"], filter_type="tree")
.set_rank("species"),
"multiple_fields_single_filter": lambda: QueryBuilder("taxon")
.add_attribute("genome_size", "exists")
.add_field("genome_size")
.add_field("chromosome_count")
.add_field("assembly_level"),
"fields_with_modifiers": lambda: QueryBuilder("taxon")
.add_field("genome_size", modifiers=["min", "max"])
.add_field("chromosome_count", modifiers=["median"]),
"pagination_size_variation": lambda: QueryBuilder("taxon").set_rank("species").set_size(50),
"pagination_second_page": lambda: QueryBuilder("taxon").set_rank("species").set_page(2),
"complex_multi_constraint": lambda: QueryBuilder("taxon")
.set_taxa(["Primates"], filter_type="tree")
.set_rank("species")
.add_attribute("assembly_span", "ge", "1000000000")
.add_field("genome_size")
.add_field("chromosome_count", modifiers=["min", "max"])
.add_field("assembly_level"),
"complex_multi_filter_same_field": lambda: QueryBuilder("taxon")
.add_attribute("c_value", "ge", "0.5")
.add_attribute("c_value", "le", "5.0")
.add_attribute("genome_size", "exists")
.add_field("c_value")
.add_field("genome_size"),
"assembly_index_basic": lambda: QueryBuilder("assembly"),
"sample_index_basic": lambda: QueryBuilder("sample"),
"exclude_ancestral_single": lambda: QueryBuilder("taxon")
.add_field("genome_size")
.set_exclude_ancestral(["genome_size"]),
"exclude_descendant_single": lambda: QueryBuilder("taxon").add_field("c_value").set_exclude_descendant(["c_value"]),
"exclude_direct_single": lambda: QueryBuilder("taxon")
.add_field("assembly_level")
.set_exclude_direct(["assembly_level"]),
"exclude_missing_single": lambda: QueryBuilder("taxon")
.add_field("chromosome_count")
.set_exclude_missing(["chromosome_count"]),
"exclude_multiple_types_combined": lambda: QueryBuilder("taxon")
.add_field("genome_size")
.add_field("chromosome_count")
.add_field("assembly_level")
.set_exclude_ancestral(["genome_size"])
.set_exclude_missing(["chromosome_count"])
.set_exclude_direct(["assembly_level"]),
"exclude_with_taxa_filter": lambda: QueryBuilder("taxon")
.set_taxa(["Mammalia"], filter_type="tree")
.add_field("genome_size")
.set_exclude_ancestral(["genome_size"]),
"sorting_by_chromosome_count": lambda: QueryBuilder("taxon")
.add_attribute("chromosome_count", "gt", "10")
.add_field("chromosome_count")
.set_sort("chromosome_count", "asc"),
"sorting_descending_order": lambda: QueryBuilder("taxon")
.add_attribute("c_value", "ge", "0.5")
.add_field("c_value")
.set_sort("c_value", "desc"),
"with_taxonomy_param": lambda: QueryBuilder("taxon")
.add_attribute("assembly_level", "eq", "complete genome")
.add_field("assembly_level")
.set_taxonomy("ncbi"),
"with_names_param": lambda: QueryBuilder("taxon")
.add_attribute("chromosome_count", "gt", "10")
.add_field("chromosome_count")
.set_names(["scientific_name"]),
"with_ranks_param": lambda: QueryBuilder("taxon")
.add_attribute("c_value", "ge", "0.5")
.add_field("c_value")
.set_ranks(["genus", "family", "order"]),
"assembly_index_with_filter": lambda: QueryBuilder("assembly")
.add_attribute("assembly_level", "eq", "complete genome")
.add_field("assembly_span")
.add_field("assembly_level"),
"chain_query_cross_index": lambda: QueryBuilder("taxon")
.chain_query("queryA", "assembly--assembly_span>1000000000")
.add_attribute("taxon_id", "eq", "queryA.taxon_id"),
"chain_query_same_index_limit": lambda: QueryBuilder("taxon")
.chain_query("queryA", "genome_size>1000000000", limit=200)
.add_attribute("taxon_id", "eq", "queryA.taxon_id"),
}
# Fixtures that have no pre-recorded API response JSON (builder-only tests).
# Fixture-response tests are skipped for these names.
BUILDER_ONLY_FIXTURES: frozenset[str] = frozenset(
{
"chain_query_cross_index",
"chain_query_same_index_limit",
}
)
# ── Expected URL substrings per fixture ──────────────────────────────────────
# Each entry maps a fixture name to substrings that MUST appear in the built URL.
# Uses raw (percent-encoded) URL strings so assertions pass without decoding.
# This catches builder methods that silently ignore their arguments.
FIXTURE_EXPECTED_URL_PARTS: dict[str, list[str]] = {
"basic_taxon_search": ["result=taxon"],
"numeric_field_integer_filter": ["result=taxon", "chromosome_count"],
"numeric_field_range": ["result=taxon", "genome_size"],
"enum_field_filter": ["result=taxon", "assembly_level"],
"taxa_filter_tree": ["result=taxon", "tax_tree", "Mammalia", "tax_rank", "species"],
"taxa_with_negative_filter": ["result=taxon", "Mammalia", "Rodentia"],
"multiple_fields_single_filter": ["result=taxon", "genome_size", "chromosome_count", "assembly_level"],
"fields_with_modifiers": ["result=taxon", "genome_size%3Amin", "chromosome_count%3Amedian"],
"pagination_size_variation": ["result=taxon", "size=50"],
"pagination_second_page": ["result=taxon", "offset=10"],
"complex_multi_constraint": ["result=taxon", "tax_tree", "Primates", "assembly_span"],
"complex_multi_filter_same_field": ["result=taxon", "c_value", "genome_size"],
"assembly_index_basic": ["result=assembly"],
"sample_index_basic": ["result=sample"],
"exclude_ancestral_single": ["result=taxon", "genome_size", "excludeAncestral"],
"exclude_descendant_single": ["result=taxon", "c_value", "excludeDescendant"],
"exclude_direct_single": ["result=taxon", "assembly_level", "excludeDirect"],
"exclude_missing_single": ["result=taxon", "chromosome_count", "excludeMissing"],
"exclude_multiple_types_combined": ["result=taxon", "excludeAncestral", "excludeMissing", "excludeDirect"],
"exclude_with_taxa_filter": ["result=taxon", "tax_tree", "Mammalia", "excludeAncestral"],
"sorting_by_chromosome_count": ["result=taxon", "sortBy=chromosome_count", "sortOrder=asc"],
"sorting_descending_order": ["result=taxon", "sortBy=c_value", "sortOrder=desc"],
"with_taxonomy_param": ["result=taxon", "taxonomy=ncbi", "assembly_level"],
"with_names_param": ["result=taxon", "names=scientific_name"],
"with_ranks_param": ["result=taxon", "ranks=", "genus"],
"assembly_index_with_filter": ["result=assembly", "assembly_level", "assembly_span"],
# chain_query fixtures: named_queries don't appear in v2 URLs; assert the
# attribute filter value (chain reference) appears in the query string.
"chain_query_cross_index": ["result=taxon", "taxon_id"],
"chain_query_same_index_limit": ["result=taxon", "taxon_id"],
}
# ── Tests ────────────────────────────────────────────────────────────────────
class TestFixtureValidation:
"""Validate SDK behavior against cached API fixtures."""
@pytest.fixture(autouse=True)
def setup(self):
"""Load fixtures once per test class."""
self.fixtures = load_all_fixtures()
self.fixture_names = list(self.fixtures.keys())
def get_builder(self, fixture_name: str) -> QueryBuilder:
"""Get the QueryBuilder for a fixture.
Args:
fixture_name: Name of the fixture.
Returns:
QueryBuilder instance matching the fixture pattern.
Raises:
KeyError: If fixture is not mapped to a builder.
"""
if fixture_name not in FIXTURE_TO_BUILDER:
pytest.skip(f"Fixture {fixture_name} not yet mapped to QueryBuilder")
return FIXTURE_TO_BUILDER[fixture_name]()
def get_response(self, fixture_name: str) -> dict[str, Any]:
"""Get the cached API response for a fixture.
Args:
fixture_name: Name of the fixture.
Returns:
Parsed API response dict.
"""
if fixture_name in BUILDER_ONLY_FIXTURES:
pytest.skip(f"Fixture {fixture_name} is builder-only (no pre-recorded API response)")
return self.fixtures[fixture_name]
# ── Parametrized tests covering all fixtures ──────────────────────────────
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_no_api_error(self, fixture_name: str):
"""Verify cached fixture response has no error."""
response = self.get_response(fixture_name)
assert "error" not in response, f"Fixture {fixture_name} returned an error"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_has_results_or_hits(self, fixture_name: str):
"""Verify cached fixture response has results or hits info."""
response = self.get_response(fixture_name)
# Most queries should have hits info
assert (
"hits" in response or "results" in response
), f"Fixture {fixture_name} has neither 'hits' nor 'results' key"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_builder_creates_valid_url(self, fixture_name: str):
"""Verify builder creates a valid URL for each fixture."""
qb = self.get_builder(fixture_name)
url = qb.to_v2_url(
api_base="https://goat.genomehubs.org/api",
api_version="v2",
)
assert url.startswith("https://goat.genomehubs.org/api"), f"URL for {fixture_name} doesn't start with API base"
assert "search" in url or "count" in url, f"URL for {fixture_name} doesn't contain endpoint"
@pytest.mark.parametrize("fixture_name", FIXTURE_EXPECTED_URL_PARTS.keys())
def test_builder_url_encodes_state(self, fixture_name: str):
"""Verify builder state is encoded in the built URL for each fixture.
Catches methods that silently ignore their arguments by asserting specific
substrings from FIXTURE_EXPECTED_URL_PARTS appear in the generated URL.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
url = qb.to_v2_url(
api_base="https://goat.genomehubs.org/api",
api_version="v2",
)
for expected in FIXTURE_EXPECTED_URL_PARTS[fixture_name]:
assert expected in url, f"Fixture {fixture_name}: expected '{expected}' in URL — got: {url}"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_builder_creates_valid_ui_url(self, fixture_name: str):
"""Verify builder creates a valid UI URL for each fixture."""
qb = self.get_builder(fixture_name)
ui_url = qb.to_ui_url(ui_base="https://goat.genomehubs.org")
assert ui_url.startswith(
"https://goat.genomehubs.org/"
), f"UI URL for {fixture_name} doesn't start with UI base"
assert "/api/" not in ui_url, f"UI URL for {fixture_name} contains /api/ — should be UI-only path"
assert "result=" in ui_url, f"UI URL for {fixture_name} missing result= parameter"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_counts_are_reasonable(self, fixture_name: str):
"""Verify fixture result counts are sensible.
Checks that:
- `results` array size <= `size` parameter
- ``hits`` count is non-negative
- Complex queries return fewer results than simple ones
"""
response = self.get_response(fixture_name)
results = response.get("results", [])
status = json.loads(parse_response_status(json.dumps(response)))
total_hits = status.get("hits", 0)
# Results should not exceed requested size
response_size = results.__len__()
if response_size > 0:
# Some fixtures don't have size info in response
assert response_size <= 100, f"Fixture {fixture_name} returned {response_size} results, " f"seems excessive"
# Total hits should be non-negative
assert total_hits >= 0, f"Fixture {fixture_name} has negative hit count"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_builder_to_yaml(self, fixture_name: str):
"""Verify builder serialization to YAML is valid.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
query_yaml = qb.to_query_yaml()
params_yaml = qb.to_params_yaml()
# Should be valid YAML (not empty, contains key-value pairs)
assert len(query_yaml) > 1, f"Fixture {fixture_name}: query_yaml is empty"
assert len(params_yaml) > 1, f"Fixture {fixture_name}: params_yaml is empty"
# Should contain expected keys
assert "index" in query_yaml, f"query_yaml missing 'index' for {fixture_name}"
assert "size" in params_yaml, f"params_yaml missing 'size' for {fixture_name}"
# ── Tests with real response data ─────────────────────────────────────────
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_can_describe(self, fixture_name: str):
"""Verify builder can generate English description.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
description = qb.describe()
assert isinstance(description, str), f"Fixture {fixture_name}: describe() returned non-string"
assert len(description) > 0, f"Fixture {fixture_name}: describe() returned empty string"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_can_generate_snippet(self, fixture_name: str):
"""Verify builder can generate code snippets.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
snippets = qb.snippet(
languages=["python"],
site_name="goat",
sdk_name="goat_sdk",
)
assert "python" in snippets, f"Fixture {fixture_name}: missing 'python' snippet"
assert len(snippets["python"]) > 0, f"Fixture {fixture_name}: Python snippet is empty"
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_can_tidy_records(self, fixture_name: str):
"""Verify builder can tidy records from response.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
response = self.get_response(fixture_name)
results = response.get("results", [])
if not results:
pytest.skip(f"Fixture {fixture_name} has no results to tidy")
tidy = qb.to_tidy_records(results)
assert isinstance(tidy, list), f"Fixture {fixture_name}: to_tidy_records() returned non-list"
assert len(tidy) > 0, f"Fixture {fixture_name}: to_tidy_records() returned empty list"
# Check for expected tidy columns
if tidy:
first = tidy[0]
expected_keys = {"field", "value"}
missing = expected_keys - set(first.keys())
assert not missing, f"Fixture {fixture_name}: tidy record missing keys {missing}"
# ── Test fixture-specific patterns ───────────────────────────────────────
def test_complex_multi_constraint_has_results(self):
"""Complex query should return results for Primates."""
fixture_name = "complex_multi_constraint"
response = self.get_response(fixture_name)
results = response.get("results", [])
# Primates with assembly_span > 1G should exist
assert len(results) > 0, f"{fixture_name} should return Primates with large assemblies"
def test_pagination_size_respected(self):
"""Pagination with size=50 should not exceed 50 results."""
fixture_name = "pagination_size_variation"
response = self.get_response(fixture_name)
results = response.get("results", [])
assert len(results) <= 50, f"{fixture_name} returned more than 50 results"
def test_numeric_filters_effective(self):
"""Numeric filters should reduce result count vs unfiltered."""
fixture_name = "numeric_field_integer_filter"
response = self.get_response(fixture_name)
# Get unfiltered baseline
baseline_response = self.get_response("basic_taxon_search")
filtered_status = json.loads(parse_response_status(json.dumps(response)))
baseline_status = json.loads(parse_response_status(json.dumps(baseline_response)))
filtered_hits = filtered_status.get("hits", 0)
baseline_hits = baseline_status.get("hits", 0)
# Filtered query should have fewer or equal results
assert filtered_hits <= baseline_hits, f"Filtered {fixture_name} returned more results than baseline"
def test_taxa_tree_filter_returns_results(self):
"""Taxa tree filter for Mammalia should return many results."""
fixture_name = "taxa_filter_tree"
response = self.get_response(fixture_name)
total_hits = response.get("status", {}).get("hits", 0)
# Mammalia is a large clade with many species
assert total_hits > 100, f"{fixture_name} returned too few hits for Mammalia subtree"
# ── Validate method tests ─────────────────────────────────────────────────
@pytest.mark.parametrize("fixture_name", FIXTURE_TO_BUILDER.keys())
def test_fixture_can_validate(self, fixture_name: str):
"""Verify builder can validate a query and that known-good fixtures have no errors.
Args:
fixture_name: Name of the fixture.
"""
qb = self.get_builder(fixture_name)
errors = qb.validate()
# validate() should always return a list
assert isinstance(errors, list), f"Fixture {fixture_name}: validate() returned non-list"
assert all(isinstance(e, str) for e in errors), f"Fixture {fixture_name}: validate() returned non-string errors"
# Known-good fixture queries should produce zero validation errors
assert errors == [], f"Fixture {fixture_name}: validate() returned unexpected errors: {errors}"
class TestFixtureRegressionCatches:
"""Ensure fixture test updates catch real SDK regressions."""
def test_fixture_mapping_completeness(self):
"""Ensure all fixtures have mappings to QueryBuilder."""
fixtures = load_all_fixtures()
unmapped = set(fixtures.keys()) - set(FIXTURE_TO_BUILDER.keys())
assert not unmapped, f"Unmapped fixtures (add to FIXTURE_TO_BUILDER): {unmapped}"
def test_builders_match_fixture_patterns(self):
"""Spot-check a few builders match their fixture patterns."""
# These are sanity checks to catch obvious builder/fixture mismatches
# basic_taxon_search should be taxon index
qb = FIXTURE_TO_BUILDER["basic_taxon_search"]()
assert qb._index == "taxon"
# assembly_index_basic should be assembly index
qb = FIXTURE_TO_BUILDER["assembly_index_basic"]()
assert qb._index == "assembly"
# sample_index_basic should be sample index
qb = FIXTURE_TO_BUILDER["sample_index_basic"]()
assert qb._index == "sample"
# taxa_filter_tree should have taxa set
qb = FIXTURE_TO_BUILDER["taxa_filter_tree"]()
assert len(qb._taxa) > 0
# ── YAML-based fixture builders (no cached JSON required) ────────────────────
# Maps a logical fixture name to (query_builder_factory, report_builder_factory).
# These test that to_query_yaml() / to_report_yaml() encode state correctly
# without requiring a live API or a cached fixture file.
YAML_FIXTURE_BUILDERS: dict[str, tuple[Any, Any]] = {
"report_histogram_primates": (
lambda: QueryBuilder("taxon").set_taxa(["Primates"], filter_type="ancestor").set_rank("species"),
lambda: ReportBuilder("histogram").set_x("genome_size").set_rank("species"),
),
"histogram_numeric_boundaries": (
lambda: QueryBuilder("taxon").set_taxa(["Mammalia"]).set_rank("species"),
lambda: ReportBuilder("histogram")
.set_x("genome_size")
.set_rank("species")
.set_axis_boundaries("x", [1e6, 10e6, 100e6, 1e9]),
),
"histogram_date_intervals": (
lambda: QueryBuilder("assembly"),
lambda: ReportBuilder("histogram")
.set_x("release_date")
.set_rank("species")
.set_axis_date_intervals("x", ["week", "month", "quarter"]),
),
"histogram_boundaries_custom_labels": (
lambda: QueryBuilder("taxon").set_rank("species"),
lambda: ReportBuilder("histogram")
.set_x("genome_size")
.set_rank("species")
.set_axis_boundaries("x", [1e6, 10e6, 100e6, 1e9], labels=[">1M-10M", ">10M-100M", ">100M-1B", ">1B+"]),
),
}
# ── Expected YAML substrings per YAML fixture ─────────────────────────────────
# Each entry maps a fixture name to expected substrings in the YAML outputs.
# This validates v3 transport correctness (POST body content) without a live API.
FIXTURE_EXPECTED_YAML_PARTS: dict[str, dict[str, list[str]]] = {
"report_histogram_primates": {
"query_yaml": ["taxa:", "Primates"],
"report_yaml": ["report: histogram", "x: genome_size"],
},
"histogram_numeric_boundaries": {
"query_yaml": ["taxa:", "Mammalia"],
"report_yaml": ["report: histogram", "x: genome_size", "boundaries:", "1000000"],
},
"histogram_date_intervals": {
"query_yaml": ["index: assembly"],
"report_yaml": ["report: histogram", "x: release_date", "intervals:", "week"],
},
"histogram_boundaries_custom_labels": {
"query_yaml": ["index: taxon", "rank: species"],
"report_yaml": ["report: histogram", "boundaries:", "labels:", ">1M-10M"],
},
}
class TestYamlFixtures:
"""Validate YAML output for report and query builders (no network required)."""
@pytest.mark.parametrize("fixture_name", YAML_FIXTURE_BUILDERS.keys())
def test_yaml_fixture_query_yaml_content(self, fixture_name: str):
"""Verify to_query_yaml() contains expected substrings."""
query_factory, _ = YAML_FIXTURE_BUILDERS[fixture_name]
qb = query_factory()
query_yaml = qb.to_query_yaml()
expected = FIXTURE_EXPECTED_YAML_PARTS.get(fixture_name, {}).get("query_yaml", [])
for part in expected:
assert part in query_yaml, f"{fixture_name}: expected '{part}' in query_yaml — got: {query_yaml}"
@pytest.mark.parametrize("fixture_name", YAML_FIXTURE_BUILDERS.keys())
def test_yaml_fixture_report_yaml_content(self, fixture_name: str):
"""Verify to_report_yaml() contains expected substrings."""
_, report_factory = YAML_FIXTURE_BUILDERS[fixture_name]
rb = report_factory()
report_yaml = rb.to_report_yaml()
expected = FIXTURE_EXPECTED_YAML_PARTS.get(fixture_name, {}).get("report_yaml", [])
for part in expected:
assert part in report_yaml, f"{fixture_name}: expected '{part}' in report_yaml — got: {report_yaml}"
class TestReportBuilderBoundaries:
"""Test set_axis_boundaries and set_axis_date_intervals methods."""
def test_set_axis_boundaries_numeric(self):
"""Verify set_axis_boundaries() correctly sets numeric boundaries."""
rb = ReportBuilder("histogram").set_x("genome_size").set_axis_boundaries("x", [1e6, 10e6, 100e6])
yaml = rb.to_report_yaml()
assert "boundaries:" in yaml
assert "1000000" in yaml or "1e6" in yaml or "1000000.0" in yaml
def test_set_axis_boundaries_with_labels(self):
"""Verify set_axis_boundaries() correctly sets custom labels."""
labels = ["Small", "Medium", "Large"]
rb = ReportBuilder("histogram").set_x("genome_size").set_axis_boundaries("x", [1e6, 10e6, 100e6], labels=labels)
yaml = rb.to_report_yaml()
assert "boundaries:" in yaml
assert "labels:" in yaml
for label in labels:
assert label in yaml
def test_set_axis_date_intervals(self):
"""Verify set_axis_date_intervals() correctly sets date intervals."""
intervals = ["week", "month", "quarter"]
rb = ReportBuilder("histogram").set_x("release_date").set_axis_date_intervals("x", intervals)
yaml = rb.to_report_yaml()
assert "boundaries:" in yaml
assert "intervals:" in yaml
for interval in intervals:
assert interval in yaml
def test_set_axis_boundaries_multiple_axes(self):
"""Verify boundaries can be set on different axes."""
rb = (
ReportBuilder("scatter")
.set_x("genome_size")
.set_y("chromosome_count")
.set_axis_boundaries("x", [1e6, 10e6, 100e6])
.set_axis_boundaries("y", [10, 50, 100])
)
yaml = rb.to_report_yaml()
assert "x_opts:" in yaml
assert "y_opts:" in yaml
assert "boundaries:" in yaml
def test_set_axis_boundaries_cat_axis(self):
"""Verify boundaries can be set on category axis."""
rb = ReportBuilder("histogram").set_cat("assembly_level").set_axis_boundaries("cat", ["value1", "value2"])
yaml = rb.to_report_yaml()
assert "cat_opts:" in yaml
assert "boundaries:" in yaml
def test_set_axis_boundaries_chaining(self):
"""Verify set_axis_boundaries() returns self for method chaining."""
rb = ReportBuilder("histogram")
result = rb.set_x("genome_size").set_axis_boundaries("x", [1e6, 10e6, 100e6])
assert result is rb
yaml = rb.to_report_yaml()
assert "boundaries:" in yaml
def test_set_axis_date_intervals_chaining(self):
"""Verify set_axis_date_intervals() returns self for method chaining."""
rb = ReportBuilder("histogram")
result = rb.set_x("release_date").set_axis_date_intervals("x", ["week", "month"])
assert result is rb
yaml = rb.to_report_yaml()
assert "intervals:" in yaml
def test_set_axis_boundaries_replaces_previous(self):
"""Verify setting boundaries twice replaces the previous value."""
rb = ReportBuilder("histogram")
rb.set_x("genome_size")
rb.set_axis_boundaries("x", [1e6, 10e6])
rb.set_axis_boundaries("x", [1e3, 1e6, 1e9])
yaml = rb.to_report_yaml()
# Should contain the newer values
assert "1000000" in yaml or "1e6" in yaml
# Count occurrences of "boundaries:" to ensure there's only one
assert yaml.count("boundaries:") == 1
def test_set_axis_date_intervals_replaces_numeric_boundaries(self):
"""Verify date intervals replaces previously set numeric boundaries."""
rb = ReportBuilder("histogram").set_x("release_date")
rb.set_axis_boundaries("x", [1e6, 10e6])
rb.set_axis_date_intervals("x", ["week", "month"])
yaml = rb.to_report_yaml()
assert "intervals:" in yaml
# boundaries should still be there but now contain intervals
assert "boundaries:" in yaml
if __name__ == "__main__":
pytest.main([__file__, "-v"])