File size: 24,536 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
"""Tests for NegBioDB PPI domain database layer."""

import sqlite3
from pathlib import Path

import pytest

from negbiodb_ppi.ppi_db import (
    create_ppi_database,
    get_connection,
    refresh_all_ppi_pairs,
    run_ppi_migrations,
)

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


@pytest.fixture
def ppi_db(tmp_path):
    """Create a temporary PPI database with all migrations applied."""
    db_path = tmp_path / "test_ppi.db"
    run_ppi_migrations(db_path, MIGRATIONS_DIR)
    return db_path


class TestPPIMigrations:
    """Test PPI schema creation and migrations."""

    def test_create_ppi_database(self, tmp_path):
        db_path = tmp_path / "test.db"
        result = create_ppi_database(db_path, MIGRATIONS_DIR)
        assert result == db_path
        assert db_path.exists()

    def test_migration_001_applied(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            versions = conn.execute(
                "SELECT version FROM schema_migrations"
            ).fetchall()
            assert ("001",) in versions
        finally:
            conn.close()

    def test_idempotent_migrations(self, ppi_db):
        """Running migrations twice should not fail."""
        applied = run_ppi_migrations(ppi_db, MIGRATIONS_DIR)
        assert applied == []

    def test_all_tables_exist(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            tables = {
                row[0]
                for row in conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='table'"
                ).fetchall()
            }
            expected = {
                "schema_migrations",
                "dataset_versions",
                "proteins",
                "ppi_experiments",
                "ppi_negative_results",
                "protein_protein_pairs",
                "ppi_split_definitions",
                "ppi_split_assignments",
            }
            assert expected.issubset(tables), f"Missing: {expected - tables}"
        finally:
            conn.close()

    def test_all_indices_exist(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            indices = {
                row[0]
                for row in conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='index'"
                ).fetchall()
            }
            expected = {
                "idx_proteins_uniprot",
                "idx_proteins_gene",
                "idx_ppi_exp_source",
                "idx_ppi_nr_protein1",
                "idx_ppi_nr_protein2",
                "idx_ppi_nr_pair",
                "idx_ppi_nr_tier",
                "idx_ppi_nr_source",
                "idx_ppi_nr_unique_source",
                "idx_ppp_protein1",
                "idx_ppp_protein2",
                "idx_ppp_confidence",
                "idx_ppi_splits_fold",
            }
            assert expected.issubset(indices), f"Missing: {expected - indices}"
        finally:
            conn.close()


class TestPPISchema:
    """Test PPI schema constraints and foreign keys."""

    def test_protein_unique_constraint(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('P12345')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO proteins (uniprot_accession) VALUES ('P12345')"
                )
        finally:
            conn.close()

    def test_evidence_type_check(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            # Insert required proteins
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            # Valid evidence type
            conn.execute(
                "INSERT INTO ppi_negative_results "
                "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                " source_db, source_record_id, extraction_method) "
                "VALUES (1, 2, 'experimental_non_interaction', 'gold', "
                "'intact', 'R001', 'database_direct')"
            )
            conn.commit()

            # Invalid evidence type
            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (1, 2, 'invalid_type', 'gold', "
                    "'intact', 'R002', 'database_direct')"
                )
        finally:
            conn.close()

    def test_confidence_tier_check(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (1, 2, 'experimental_non_interaction', 'platinum', "
                    "'intact', 'R001', 'database_direct')"
                )
        finally:
            conn.close()

    def test_canonical_ordering_enforced(self, ppi_db):
        """protein1_id must be < protein2_id."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            # protein1_id=2, protein2_id=1 violates CHECK
            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (2, 1, 'experimental_non_interaction', 'gold', "
                    "'intact', 'R001', 'database_direct')"
                )
        finally:
            conn.close()

    def test_canonical_ordering_equal_ids_rejected(self, ppi_db):
        """protein1_id == protein2_id violates CHECK (strict less-than)."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (1, 1, 'experimental_non_interaction', 'gold', "
                    "'intact', 'R001', 'database_direct')"
                )
        finally:
            conn.close()

    def test_extraction_method_check(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (1, 2, 'experimental_non_interaction', 'gold', "
                    "'intact', 'R001', 'invalid_method')"
                )
        finally:
            conn.close()

    def test_foreign_key_enforcement(self, ppi_db):
        """FK violations should raise errors."""
        conn = get_connection(ppi_db)
        try:
            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (999, 1000, 'experimental_non_interaction', 'gold', "
                    "'intact', 'R001', 'database_direct')"
                )
        finally:
            conn.close()

    def test_dedup_unique_index(self, ppi_db):
        """Same (pair, experiment, source, record) should fail."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            conn.execute(
                "INSERT INTO ppi_negative_results "
                "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                " source_db, source_record_id, extraction_method) "
                "VALUES (1, 2, 'experimental_non_interaction', 'gold', "
                "'intact', 'R001', 'database_direct')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_negative_results "
                    "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                    " source_db, source_record_id, extraction_method) "
                    "VALUES (1, 2, 'ml_predicted_negative', 'silver', "
                    "'intact', 'R001', 'database_direct')"
                )
        finally:
            conn.close()

    def test_dedup_allows_different_source_records(self, ppi_db):
        """Same pair but different source_record_id is OK."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            conn.execute(
                "INSERT INTO ppi_negative_results "
                "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                " source_db, source_record_id, extraction_method) "
                "VALUES (1, 2, 'experimental_non_interaction', 'gold', "
                "'intact', 'R001', 'database_direct')"
            )
            conn.execute(
                "INSERT INTO ppi_negative_results "
                "(protein1_id, protein2_id, evidence_type, confidence_tier, "
                " source_db, source_record_id, extraction_method) "
                "VALUES (1, 2, 'experimental_non_interaction', 'gold', "
                "'intact', 'R002', 'database_direct')"
            )
            conn.commit()
            count = conn.execute(
                "SELECT COUNT(*) FROM ppi_negative_results"
            ).fetchone()[0]
            assert count == 2
        finally:
            conn.close()

    def test_experiment_source_db_check(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            # Valid source_db
            conn.execute(
                "INSERT INTO ppi_experiments "
                "(source_db, source_experiment_id) "
                "VALUES ('intact', 'EXP001')"
            )
            conn.commit()

            # Invalid source_db
            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_experiments "
                    "(source_db, source_experiment_id) "
                    "VALUES ('invalid_db', 'EXP002')"
                )
        finally:
            conn.close()

    def test_experiment_huri_source_db(self, ppi_db):
        """HuRI is a valid source_db."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO ppi_experiments "
                "(source_db, source_experiment_id) "
                "VALUES ('huri', 'HI-III-20')"
            )
            conn.commit()
            count = conn.execute(
                "SELECT COUNT(*) FROM ppi_experiments WHERE source_db = 'huri'"
            ).fetchone()[0]
            assert count == 1
        finally:
            conn.close()

    def test_split_strategy_check(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            # Valid strategy
            conn.execute(
                "INSERT INTO ppi_split_definitions "
                "(split_name, split_strategy) "
                "VALUES ('random_v1', 'random')"
            )
            conn.commit()

            # Invalid strategy
            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO ppi_split_definitions "
                    "(split_name, split_strategy) "
                    "VALUES ('bad_v1', 'invalid_strategy')"
                )
        finally:
            conn.close()

    def test_pairs_canonical_ordering(self, ppi_db):
        """protein_protein_pairs also enforces protein1 < protein2."""
        conn = get_connection(ppi_db)
        try:
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
            )
            conn.execute(
                "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
            )
            conn.commit()

            with pytest.raises(sqlite3.IntegrityError):
                conn.execute(
                    "INSERT INTO protein_protein_pairs "
                    "(protein1_id, protein2_id, num_experiments, num_sources, "
                    " best_confidence) "
                    "VALUES (2, 1, 1, 1, 'gold')"
                )
        finally:
            conn.close()


class TestRefreshPPIPairs:
    """Test protein_protein_pairs aggregation."""

    def _insert_test_data(self, conn):
        """Insert minimal test data for aggregation testing."""
        # 3 proteins: A(1), B(2), C(3)
        conn.execute(
            "INSERT INTO proteins (uniprot_accession) VALUES ('A00001')"
        )
        conn.execute(
            "INSERT INTO proteins (uniprot_accession) VALUES ('B00002')"
        )
        conn.execute(
            "INSERT INTO proteins (uniprot_accession) VALUES ('C00003')"
        )

        # Experiments
        conn.execute(
            "INSERT INTO ppi_experiments "
            "(source_db, source_experiment_id) "
            "VALUES ('intact', 'EXP001')"
        )
        conn.execute(
            "INSERT INTO ppi_experiments "
            "(source_db, source_experiment_id) "
            "VALUES ('humap', 'HUMAP001')"
        )

        # A-B: 2 results (gold + silver, different sources)
        conn.execute(
            "INSERT INTO ppi_negative_results "
            "(protein1_id, protein2_id, experiment_id, evidence_type, "
            " confidence_tier, source_db, source_record_id, "
            " extraction_method, publication_year, interaction_score) "
            "VALUES (1, 2, 1, 'experimental_non_interaction', 'gold', "
            "'intact', 'R001', 'database_direct', 2020, 0.05)"
        )
        conn.execute(
            "INSERT INTO ppi_negative_results "
            "(protein1_id, protein2_id, experiment_id, evidence_type, "
            " confidence_tier, source_db, source_record_id, "
            " extraction_method, publication_year, interaction_score) "
            "VALUES (1, 2, 2, 'ml_predicted_negative', 'silver', "
            "'humap', 'R002', 'ml_classifier', 2023, 0.01)"
        )

        # A-C: 1 result (bronze)
        conn.execute(
            "INSERT INTO ppi_negative_results "
            "(protein1_id, protein2_id, evidence_type, "
            " confidence_tier, source_db, source_record_id, "
            " extraction_method, publication_year) "
            "VALUES (1, 3, 'low_score_negative', 'bronze', "
            "'string', 'R003', 'score_threshold', 2022)"
        )

        # B-C: 1 result (copper)
        conn.execute(
            "INSERT INTO ppi_negative_results "
            "(protein1_id, protein2_id, evidence_type, "
            " confidence_tier, source_db, source_record_id, "
            " extraction_method, publication_year) "
            "VALUES (2, 3, 'compartment_separated', 'copper', "
            "'string', 'R004', 'score_threshold', 2021)"
        )
        conn.commit()

    def test_refresh_pair_count(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            count = refresh_all_ppi_pairs(conn)
            conn.commit()
            assert count == 3  # A-B, A-C, B-C
        finally:
            conn.close()

    def test_best_confidence_aggregation(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            row = conn.execute(
                "SELECT best_confidence, num_experiments, num_sources "
                "FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == "gold"  # best of gold + silver
            assert row[1] == 2  # 2 distinct experiments
            assert row[2] == 2  # 2 distinct sources (intact, humap)
        finally:
            conn.close()

    def test_best_evidence_type_priority(self, ppi_db):
        """experimental_non_interaction should rank above ml_predicted."""
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            row = conn.execute(
                "SELECT best_evidence_type FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == "experimental_non_interaction"
        finally:
            conn.close()

    def test_score_range(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            row = conn.execute(
                "SELECT min_interaction_score, max_interaction_score "
                "FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == pytest.approx(0.01)
            assert row[1] == pytest.approx(0.05)
        finally:
            conn.close()

    def test_earliest_year(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            row = conn.execute(
                "SELECT earliest_year FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == 2020
        finally:
            conn.close()

    def test_degree_computation_protein1(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # Protein A (id=1) appears as protein1 in A-B and A-C → degree 2
            row = conn.execute(
                "SELECT protein1_degree FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == 2
        finally:
            conn.close()

    def test_degree_computation_protein2(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # Protein C (id=3) appears as protein2 in A-C and B-C → degree 2
            row = conn.execute(
                "SELECT protein2_degree FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 3"
            ).fetchone()
            assert row[0] == 2
        finally:
            conn.close()

    def test_degree_computation_both_sides(self, ppi_db):
        """Protein B (id=2) appears as protein2 in A-B and protein1 in B-C.
        True degree = 2 (partners A and C) regardless of which side it's on."""
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # In A-B row, protein2 is B → protein2_degree = B's full degree = 2
            row = conn.execute(
                "SELECT protein2_degree FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 2"
            ).fetchone()
            assert row[0] == 2

            # In B-C row, protein1 is B → protein1_degree = B's full degree = 2
            row = conn.execute(
                "SELECT protein1_degree FROM protein_protein_pairs "
                "WHERE protein1_id = 2 AND protein2_id = 3"
            ).fetchone()
            assert row[0] == 2
        finally:
            conn.close()

    def test_refresh_is_idempotent(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            count1 = refresh_all_ppi_pairs(conn)
            conn.commit()
            count2 = refresh_all_ppi_pairs(conn)
            conn.commit()
            assert count1 == count2
        finally:
            conn.close()

    def test_refresh_clears_split_assignments(self, ppi_db):
        """Refresh should succeed even when split assignments exist (FK)."""
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # Create a split and assign a pair
            conn.execute(
                "INSERT INTO ppi_split_definitions "
                "(split_name, split_strategy) VALUES ('test_v1', 'random')"
            )
            conn.execute(
                "INSERT INTO ppi_split_assignments (pair_id, split_id, fold) "
                "VALUES (1, 1, 'train')"
            )
            conn.commit()

            # Re-refresh should not crash despite FK to split_assignments
            count = refresh_all_ppi_pairs(conn)
            conn.commit()
            assert count == 3

            # Split assignments should be cleared
            sa_count = conn.execute(
                "SELECT COUNT(*) FROM ppi_split_assignments"
            ).fetchone()[0]
            assert sa_count == 0
        finally:
            conn.close()

    def test_null_experiment_counted(self, ppi_db):
        """Results without experiment_id should use COALESCE sentinel."""
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # A-C has NULL experiment_id → COALESCE(-1) → counted as 1
            row = conn.execute(
                "SELECT num_experiments FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 3"
            ).fetchone()
            assert row[0] == 1
        finally:
            conn.close()

    def test_single_source_count(self, ppi_db):
        conn = get_connection(ppi_db)
        try:
            self._insert_test_data(conn)
            refresh_all_ppi_pairs(conn)
            conn.commit()

            # A-C has 1 source (string)
            row = conn.execute(
                "SELECT num_sources FROM protein_protein_pairs "
                "WHERE protein1_id = 1 AND protein2_id = 3"
            ).fetchone()
            assert row[0] == 1
        finally:
            conn.close()