File size: 23,128 Bytes
6d1bbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests for drug name resolution cascade."""

import json
import sqlite3
from pathlib import Path

import pandas as pd
import pytest

from negbiodb_ct.ct_db import create_ct_database, get_connection
from negbiodb_ct.drug_resolver import (
    _map_mol_type,
    _pug_download_results,
    _pubchem_batch_cid_to_properties,
    _pubchem_name_lookup,
    _xml_escape,
    build_chembl_synonym_index,
    clean_drug_name,
    crossref_inchikey_to_chembl,
    insert_intervention_targets,
    is_non_drug_name,
    load_overrides,
    resolve_step1_chembl,
    resolve_step2_pubchem,
    resolve_step3_fuzzy,
    resolve_step4_overrides,
    update_interventions,
)

MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations_ct"


@pytest.fixture
def ct_db(tmp_path):
    """Create a fresh CT database with all migrations applied."""
    db_path = tmp_path / "test_ct.db"
    create_ct_database(db_path, MIGRATIONS_DIR)
    return db_path


# ============================================================
# CLEAN DRUG NAME TESTS
# ============================================================


class TestCleanDrugName:
    def test_lowercase(self):
        assert clean_drug_name("Imatinib") == "imatinib"

    def test_strip_dosage_mg(self):
        assert clean_drug_name("Imatinib (400mg)") == "imatinib"

    def test_strip_dosage_ug(self):
        assert clean_drug_name("DrugX (50ug daily)") == "drugx"

    def test_strip_salt(self):
        assert clean_drug_name("Imatinib mesylate") == "imatinib"

    def test_strip_hydrochloride(self):
        assert clean_drug_name("Tamsulosin Hydrochloride") == "tamsulosin"

    def test_strip_trailing_paren(self):
        assert clean_drug_name("DrugA (formerly B123)") == "druga"

    def test_empty(self):
        assert clean_drug_name("") == ""

    def test_combined(self):
        assert clean_drug_name("Aspirin Sodium (500mg tablets)") == "aspirin"


# ============================================================
# STEP 1: CHEMBL SYNONYM INDEX TESTS
# ============================================================


class TestBuildChemblSynonymIndex:
    def test_missing_db(self, tmp_path):
        result = build_chembl_synonym_index(tmp_path / "nonexistent.db")
        assert result == {}


class TestResolveStep1:
    def test_exact_match(self):
        index = {"imatinib": "CHEMBL941", "aspirin": "CHEMBL25"}
        resolved = resolve_step1_chembl(["Imatinib", "Unknown Drug"], index)
        assert resolved == {"Imatinib": "CHEMBL941"}

    def test_no_match(self):
        index = {"imatinib": "CHEMBL941"}
        resolved = resolve_step1_chembl(["SomeNewDrug"], index)
        assert resolved == {}

    def test_salt_stripped(self):
        index = {"imatinib": "CHEMBL941"}
        resolved = resolve_step1_chembl(["Imatinib mesylate"], index)
        assert resolved == {"Imatinib mesylate": "CHEMBL941"}


# ============================================================
# STEP 3: FUZZY MATCH TESTS
# ============================================================


class TestResolveStep3Fuzzy:
    def test_close_match(self):
        index = {"imatinib": "CHEMBL941", "aspirin": "CHEMBL25"}
        # "imatinb" is close to "imatinib"
        resolved = resolve_step3_fuzzy(["Imatinb"], index, threshold=0.85)
        assert "Imatinb" in resolved
        assert resolved["Imatinb"] == "CHEMBL941"

    def test_no_close_match(self):
        index = {"imatinib": "CHEMBL941"}
        resolved = resolve_step3_fuzzy(["CompletelyDifferent"], index, threshold=0.90)
        assert resolved == {}

    def test_high_threshold(self):
        index = {"imatinib": "CHEMBL941"}
        # Very high threshold should reject approximate matches
        resolved = resolve_step3_fuzzy(["imatinb"], index, threshold=0.99)
        assert resolved == {}


# ============================================================
# STEP 4: OVERRIDES TESTS
# ============================================================


class TestLoadOverrides:
    def test_basic_load(self, tmp_path):
        csv = tmp_path / "overrides.csv"
        csv.write_text(
            "intervention_name,chembl_id,canonical_smiles,molecular_type\n"
            "trastuzumab,CHEMBL1201585,,monoclonal_antibody\n"
        )
        overrides = load_overrides(csv)
        assert "trastuzumab" in overrides
        assert overrides["trastuzumab"]["chembl_id"] == "CHEMBL1201585"

    def test_missing_file(self, tmp_path):
        overrides = load_overrides(tmp_path / "missing.csv")
        assert overrides == {}


class TestResolveStep4:
    def test_match(self):
        overrides = {
            "trastuzumab": {"chembl_id": "CHEMBL1201585", "molecular_type": "monoclonal_antibody"},
        }
        resolved = resolve_step4_overrides(["Trastuzumab"], overrides)
        assert "Trastuzumab" in resolved
        assert resolved["Trastuzumab"]["chembl_id"] == "CHEMBL1201585"


# ============================================================
# MOL TYPE MAPPING TESTS
# ============================================================


class TestMapMolType:
    def test_small_molecule(self):
        assert _map_mol_type("Small molecule") == "small_molecule"

    def test_antibody(self):
        assert _map_mol_type("Antibody") == "monoclonal_antibody"

    def test_protein(self):
        assert _map_mol_type("Protein") == "peptide"

    def test_none(self):
        assert _map_mol_type(None) == "unknown"

    def test_unknown(self):
        assert _map_mol_type("Unknown") == "unknown"


# ============================================================
# UPDATE INTERVENTIONS TESTS
# ============================================================


class TestUpdateInterventions:
    def test_basic_update(self, ct_db):
        conn = get_connection(ct_db)
        try:
            conn.execute(
                "INSERT INTO interventions (intervention_type, intervention_name) "
                "VALUES ('drug', 'TestDrug')"
            )
            conn.commit()

            resolutions = {
                1: {
                    "chembl_id": "CHEMBL941",
                    "canonical_smiles": "CC(=O)OC1=CC=CC=C1",
                    "molecular_type": "small_molecule",
                },
            }
            n = update_interventions(conn, resolutions)
            assert n == 1

            row = conn.execute(
                "SELECT chembl_id, canonical_smiles, molecular_type "
                "FROM interventions WHERE intervention_id = 1"
            ).fetchone()
            assert row[0] == "CHEMBL941"
            assert row[1] == "CC(=O)OC1=CC=CC=C1"
            assert row[2] == "small_molecule"
        finally:
            conn.close()


# ============================================================
# INSERT TARGETS TESTS
# ============================================================


class TestInsertInterventionTargets:
    def test_basic_insert(self, ct_db):
        conn = get_connection(ct_db)
        try:
            conn.execute(
                "INSERT INTO interventions (intervention_type, intervention_name) "
                "VALUES ('drug', 'TestDrug')"
            )
            conn.commit()

            targets = [{
                "chembl_id": "CHEMBL941",
                "uniprot_accession": "P00519",
                "gene_symbol": "ABL1",
                "action_type": "INHIBITOR",
            }]
            chembl_to_interv = {"CHEMBL941": [1]}
            n = insert_intervention_targets(conn, targets, chembl_to_interv)
            assert n == 1

            row = conn.execute(
                "SELECT uniprot_accession, source "
                "FROM intervention_targets WHERE intervention_id = 1"
            ).fetchone()
            assert row[0] == "P00519"
            assert row[1] == "chembl"
        finally:
            conn.close()

    def test_dedup(self, ct_db):
        conn = get_connection(ct_db)
        try:
            conn.execute(
                "INSERT INTO interventions (intervention_type, intervention_name) "
                "VALUES ('drug', 'TestDrug')"
            )
            conn.commit()

            targets = [
                {"chembl_id": "CHEMBL941", "uniprot_accession": "P00519",
                 "gene_symbol": "ABL1", "action_type": "INHIBITOR"},
                {"chembl_id": "CHEMBL941", "uniprot_accession": "P00519",
                 "gene_symbol": "ABL1", "action_type": "INHIBITOR"},
            ]
            chembl_to_interv = {"CHEMBL941": [1]}
            n = insert_intervention_targets(conn, targets, chembl_to_interv)
            assert n == 1  # deduped
        finally:
            conn.close()


# ============================================================
# NON-DRUG NAME FILTER TESTS
# ============================================================


class TestIsNonDrugName:
    def test_placebo(self):
        assert is_non_drug_name("Placebo") is True

    def test_placebo_oral_tablet(self):
        assert is_non_drug_name("Placebo Oral Tablet") is True

    def test_saline(self):
        assert is_non_drug_name("0.9% Saline") is True

    def test_sugar_pill(self):
        assert is_non_drug_name("sugar pill") is True

    def test_standard_of_care(self):
        assert is_non_drug_name("Standard of Care") is True

    def test_vehicle_cream(self):
        assert is_non_drug_name("Vehicle Cream") is True

    def test_blood_sample(self):
        assert is_non_drug_name("Blood sample") is True

    def test_sham(self):
        assert is_non_drug_name("Sham procedure") is True

    def test_real_drug(self):
        assert is_non_drug_name("Imatinib") is False

    def test_real_biologic(self):
        assert is_non_drug_name("Trastuzumab") is False

    def test_empty(self):
        assert is_non_drug_name("") is False

    def test_best_supportive_care(self):
        assert is_non_drug_name("Best supportive care plus placebo") is True


# ============================================================
# ENHANCED PUBCHEM API TESTS
# ============================================================


class TestPubchemNameLookup:
    def test_returns_dict_with_all_fields(self, monkeypatch):
        """Mock PubChem API to return CID, SMILES, InChIKey."""
        import urllib.request

        mock_response = json.dumps({
            "PropertyTable": {"Properties": [{
                "CID": 2244,
                "CanonicalSMILES": "CC(=O)OC1=CC=CC=C1C(=O)O",
                "InChIKey": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N",
            }]}
        }).encode()

        class MockResponse:
            def read(self):
                return mock_response
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pubchem_name_lookup("aspirin", rate_limit=100.0)
        assert result is not None
        assert result["cid"] == 2244
        assert "BSYNRYMUTXBXSQ" in result["inchikey"]
        assert result["smiles"] is not None

    def test_returns_none_on_404(self, monkeypatch):
        import urllib.request
        import urllib.error

        def mock_urlopen(*a, **kw):
            raise urllib.error.HTTPError(None, 404, "Not Found", {}, None)

        monkeypatch.setattr(urllib.request, "urlopen", mock_urlopen)
        result = _pubchem_name_lookup("nonexistent_compound_xyz", rate_limit=100.0)
        assert result is None


class TestResolveStep2PubchemEnhanced:
    def test_cache_roundtrip(self, tmp_path, monkeypatch):
        """Test that enhanced cache stores and restores dict entries."""
        import urllib.request

        mock_response = json.dumps({
            "PropertyTable": {"Properties": [{
                "CID": 5090,
                "CanonicalSMILES": "C1=CC=C(C=C1)C(=O)O",
                "InChIKey": "WPYMKLBDIGXBTP-UHFFFAOYSA-N",
            }]}
        }).encode()

        class MockResponse:
            def read(self):
                return mock_response
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())

        cache_path = tmp_path / "test_cache.json"
        result = resolve_step2_pubchem(["Benzoic Acid"], cache_path, rate_limit=100.0)
        assert "Benzoic Acid" in result
        assert result["Benzoic Acid"]["cid"] == 5090

        # Verify cache file
        with open(cache_path) as f:
            cache = json.load(f)
        assert "benzoic acid" in cache
        assert cache["benzoic acid"]["cid"] == 5090

    def test_backward_compat_int_cache(self, tmp_path, monkeypatch):
        """Old cache with int CIDs should still work."""
        cache_path = tmp_path / "old_cache.json"
        cache_path.write_text(json.dumps({"aspirin": 2244, "unknown_x": None}))

        # No API calls needed — all from cache
        result = resolve_step2_pubchem(
            ["Aspirin", "Unknown_X"], cache_path, rate_limit=100.0,
        )
        assert "Aspirin" in result
        assert result["Aspirin"]["cid"] == 2244
        assert "Unknown_X" not in result


# ============================================================
# INCHIKEY → CHEMBL CROSS-REFERENCE TESTS
# ============================================================


class TestCrossrefInchikeyToChembl:
    def test_missing_db(self, tmp_path):
        result = crossref_inchikey_to_chembl(
            ["BSYNRYMUTXBXSQ-UHFFFAOYSA-N"],
            tmp_path / "nonexistent.db",
        )
        assert result == {}

    def test_empty_list(self, tmp_path):
        result = crossref_inchikey_to_chembl([], tmp_path / "nonexistent.db")
        assert result == {}

    def test_match_in_chembl(self, tmp_path):
        """Create a minimal ChEMBL-like DB with compound_structures."""
        db_path = tmp_path / "mini_chembl.db"
        conn = sqlite3.connect(str(db_path))
        conn.execute(
            "CREATE TABLE molecule_dictionary "
            "(molregno INTEGER PRIMARY KEY, chembl_id TEXT)"
        )
        conn.execute(
            "CREATE TABLE compound_structures "
            "(molregno INTEGER PRIMARY KEY, standard_inchi_key TEXT)"
        )
        conn.execute("INSERT INTO molecule_dictionary VALUES (1, 'CHEMBL25')")
        conn.execute(
            "INSERT INTO compound_structures VALUES "
            "(1, 'BSYNRYMUTXBXSQ-UHFFFAOYSA-N')"
        )
        conn.commit()
        conn.close()

        result = crossref_inchikey_to_chembl(
            ["BSYNRYMUTXBXSQ-UHFFFAOYSA-N", "NONEXISTENT-KEY"],
            db_path,
        )
        assert result == {"BSYNRYMUTXBXSQ-UHFFFAOYSA-N": "CHEMBL25"}


# ============================================================
# XML ESCAPE TESTS
# ============================================================


class TestXmlEscape:
    def test_ampersand(self):
        assert _xml_escape("A&B") == "A&B"

    def test_angle_brackets(self):
        assert _xml_escape("<tag>") == "&lt;tag&gt;"

    def test_quotes(self):
        assert _xml_escape('say "hello"') == 'say &quot;hello&quot;'

    def test_no_escape_needed(self):
        assert _xml_escape("imatinib") == "imatinib"

    def test_braces_pass_through(self):
        # Braces are NOT XML special chars — they pass through xml_escape.
        # But they must not break the template (we use .replace, not .format).
        assert _xml_escape("drug{1}") == "drug{1}"


# ============================================================
# PUG BATCH TSV DOWNLOAD TESTS
# ============================================================


class TestPugDownloadResults:
    def test_parse_tsv(self, monkeypatch):
        import urllib.request

        tsv_data = "aspirin\t2244\nimatinib\t123631\nunknown\t\n".encode()

        class MockResponse:
            def read(self):
                return tsv_data
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pug_download_results("https://example.com/results.tsv")
        assert result == {"aspirin": 2244, "imatinib": 123631}

    def test_lowercase_keys(self, monkeypatch):
        import urllib.request

        tsv_data = "Aspirin\t2244\nIMATINIB\t123631\n".encode()

        class MockResponse:
            def read(self):
                return tsv_data
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pug_download_results("https://example.com/results.tsv")
        assert "aspirin" in result
        assert "imatinib" in result

    def test_empty_response(self, monkeypatch):
        import urllib.request

        class MockResponse:
            def read(self):
                return b""
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pug_download_results("https://example.com/results.tsv")
        assert result == {}

    def test_ftp_to_https_conversion(self, monkeypatch):
        """Verify ftp:// URLs are converted to https://."""
        import urllib.request

        captured_urls = []

        class MockResponse:
            def read(self):
                return b""
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        def mock_urlopen(req, **kw):
            captured_urls.append(req.full_url)
            return MockResponse()

        monkeypatch.setattr(urllib.request, "urlopen", mock_urlopen)
        _pug_download_results("ftp://ftp.ncbi.nlm.nih.gov/pubchem/result.tsv")
        assert captured_urls[0].startswith("https://")


# ============================================================
# BATCH CID→PROPERTIES TESTS
# ============================================================


class TestPubchemBatchCidToProperties:
    def test_parses_response(self, monkeypatch):
        import urllib.request

        mock_data = json.dumps({
            "PropertyTable": {"Properties": [
                {"CID": 2244, "IsomericSMILES": "CC(=O)OC1=CC=CC=C1C(O)=O", "InChIKey": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N"},
                {"CID": 5090, "CanonicalSMILES": "OC(=O)C1=CC=CC=C1", "InChIKey": "WPYMKLBDIGXBTP-UHFFFAOYSA-N"},
            ]}
        }).encode()

        class MockResponse:
            def read(self):
                return mock_data
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pubchem_batch_cid_to_properties([2244, 5090])
        assert 2244 in result
        assert 5090 in result
        assert result[2244]["smiles"] == "CC(=O)OC1=CC=CC=C1C(O)=O"  # IsomericSMILES preferred
        assert result[2244]["inchikey"] == "BSYNRYMUTXBXSQ-UHFFFAOYSA-N"

    def test_prefers_isomeric_over_canonical(self, monkeypatch):
        import urllib.request

        mock_data = json.dumps({
            "PropertyTable": {"Properties": [{
                "CID": 1,
                "IsomericSMILES": "ISO_SMILES",
                "CanonicalSMILES": "CAN_SMILES",
                "InChIKey": "TESTKEY",
            }]}
        }).encode()

        class MockResponse:
            def read(self):
                return mock_data
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())
        result = _pubchem_batch_cid_to_properties([1])
        assert result[1]["smiles"] == "ISO_SMILES"

    def test_retries_on_http_error(self, monkeypatch):
        import urllib.request
        import urllib.error

        call_count = [0]

        def mock_urlopen(*a, **kw):
            call_count[0] += 1
            if call_count[0] < 3:
                raise urllib.error.HTTPError(None, 503, "Service Unavailable", {}, None)
            mock_data = json.dumps({
                "PropertyTable": {"Properties": [
                    {"CID": 1, "IsomericSMILES": "C", "InChIKey": "KEY"},
                ]}
            }).encode()

            class MockResponse:
                def read(self):
                    return mock_data
                def __enter__(self):
                    return self
                def __exit__(self, *args):
                    pass

            return MockResponse()

        monkeypatch.setattr(urllib.request, "urlopen", mock_urlopen)
        monkeypatch.setattr("time.sleep", lambda _: None)
        result = _pubchem_batch_cid_to_properties([1], max_retries=3)
        assert 1 in result
        assert call_count[0] == 3


# ============================================================
# BATCH RESOLVE STEP 2 TESTS
# ============================================================


class TestResolveStep2BatchMode:
    def test_batch_mode_dispatches(self, tmp_path, monkeypatch):
        """With >100 names and use_batch=True, batch path should be used."""
        from negbiodb_ct import drug_resolver

        batch_called = [False]
        original_batch = drug_resolver._pubchem_batch_names_to_cids

        def mock_batch(names, batch_size=5000):
            batch_called[0] = True
            return {"drugname_001": 1}

        def mock_props(cids, batch_size=500, max_retries=3):
            return {1: {"smiles": "C", "inchikey": "KEY-A-B"}}

        monkeypatch.setattr(drug_resolver, "_pubchem_batch_names_to_cids", mock_batch)
        monkeypatch.setattr(drug_resolver, "_pubchem_batch_cid_to_properties", mock_props)

        names = [f"DrugName_{i:03d}" for i in range(150)]
        cache_path = tmp_path / "cache.json"
        result = resolve_step2_pubchem(names, cache_path, use_batch=True)
        assert batch_called[0] is True

    def test_single_mode_for_small_sets(self, tmp_path, monkeypatch):
        """With ≤100 names, single-name REST should be used."""
        import urllib.request

        mock_data = json.dumps({
            "PropertyTable": {"Properties": [{
                "CID": 2244, "IsomericSMILES": "C", "InChIKey": "KEY",
            }]}
        }).encode()

        class MockResponse:
            def read(self):
                return mock_data
            def __enter__(self):
                return self
            def __exit__(self, *args):
                pass

        monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: MockResponse())

        cache_path = tmp_path / "cache.json"
        result = resolve_step2_pubchem(
            ["aspirin"], cache_path, rate_limit=100.0, use_batch=False,
        )
        assert "aspirin" in result