|
| 1 | +import importlib.util |
| 2 | +import logging |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | +from types import ModuleType, SimpleNamespace |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | + |
| 10 | +class FakeBiolinkToolkit: |
| 11 | + def get_ancestors(self, biolink_type): |
| 12 | + return [biolink_type] |
| 13 | + |
| 14 | + def get_element(self, ancestor): |
| 15 | + return {"class_uri": ancestor} |
| 16 | + |
| 17 | + |
| 18 | +def load_normalized_nodes_module(): |
| 19 | + module_name = "_normalized_nodes_under_test" |
| 20 | + module_path = Path(__file__).parents[1] / "src" / "nodenorm" / "handlers" / "normalized_nodes.py" |
| 21 | + fake_biolink = ModuleType("nodenorm.biolink") |
| 22 | + fake_biolink.BIOLINK_MODEL_VERSION = "test" |
| 23 | + fake_biolink.toolkit = FakeBiolinkToolkit() |
| 24 | + |
| 25 | + original_biolink = sys.modules.get("nodenorm.biolink") |
| 26 | + sys.modules["nodenorm.biolink"] = fake_biolink |
| 27 | + try: |
| 28 | + spec = importlib.util.spec_from_file_location(module_name, module_path) |
| 29 | + module = importlib.util.module_from_spec(spec) |
| 30 | + sys.modules[module_name] = module |
| 31 | + spec.loader.exec_module(module) |
| 32 | + finally: |
| 33 | + if original_biolink is None: |
| 34 | + sys.modules.pop("nodenorm.biolink", None) |
| 35 | + else: |
| 36 | + sys.modules["nodenorm.biolink"] = original_biolink |
| 37 | + |
| 38 | + return module |
| 39 | + |
| 40 | + |
| 41 | +normalized_nodes = load_normalized_nodes_module() |
| 42 | +_lookup_curie_metadata = normalized_nodes._lookup_curie_metadata |
| 43 | +_lookup_equivalent_identifiers = normalized_nodes._lookup_equivalent_identifiers |
| 44 | + |
| 45 | + |
| 46 | +class FakeAsyncElasticsearch: |
| 47 | + def __init__(self, response_batches): |
| 48 | + self.response_batches = list(response_batches) |
| 49 | + self.calls = [] |
| 50 | + |
| 51 | + async def msearch(self, **kwargs): |
| 52 | + self.calls.append(kwargs) |
| 53 | + return SimpleNamespace(body={"responses": self.response_batches.pop(0)}) |
| 54 | + |
| 55 | + |
| 56 | +def fake_namespace(response_batches, indices=None): |
| 57 | + return SimpleNamespace( |
| 58 | + elasticsearch=SimpleNamespace( |
| 59 | + async_client=FakeAsyncElasticsearch(response_batches), |
| 60 | + indices=indices or ["nodenorm"], |
| 61 | + ) |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +def hit_response(curie, source=None, total=1): |
| 66 | + if source is None: |
| 67 | + source = { |
| 68 | + "identifiers": [{"i": curie, "l": curie}], |
| 69 | + "type": "biolink:ChemicalEntity", |
| 70 | + "ic": 1.0, |
| 71 | + "preferred_name": curie, |
| 72 | + "taxa": [], |
| 73 | + } |
| 74 | + return {"hits": {"total": {"value": total}, "hits": [{"_id": curie, "_source": source}]}} |
| 75 | + |
| 76 | + |
| 77 | +def no_hit_response(): |
| 78 | + return {"hits": {"total": {"value": 0}, "hits": []}} |
| 79 | + |
| 80 | + |
| 81 | +@pytest.mark.asyncio |
| 82 | +async def test_lookup_equivalent_identifiers_uses_shared_msearch_index(): |
| 83 | + namespace = fake_namespace([[hit_response("CHEBI:17310"), no_hit_response()]]) |
| 84 | + |
| 85 | + lookup, malformed = await _lookup_equivalent_identifiers(namespace, ["CHEBI:17310", "MISSING:1"]) |
| 86 | + |
| 87 | + assert set(lookup) == {"CHEBI:17310"} |
| 88 | + assert malformed == {"MISSING:1"} |
| 89 | + |
| 90 | + msearch_call = namespace.elasticsearch.async_client.calls[0] |
| 91 | + assert msearch_call["index"] == ["nodenorm"] |
| 92 | + assert msearch_call["searches"][0] == {} |
| 93 | + assert msearch_call["searches"][1]["query"]["bool"]["filter"][0]["terms"] == {"identifiers.i": ["CHEBI:17310"]} |
| 94 | + assert msearch_call["searches"][2] == {} |
| 95 | + assert msearch_call["searches"][3]["query"]["bool"]["filter"][0]["terms"] == {"identifiers.i": ["MISSING:1"]} |
| 96 | + |
| 97 | + |
| 98 | +@pytest.mark.asyncio |
| 99 | +async def test_lookup_equivalent_identifiers_rejects_msearch_response_count_mismatch(): |
| 100 | + namespace = fake_namespace([[hit_response("CHEBI:17310")]]) |
| 101 | + |
| 102 | + with pytest.raises(RuntimeError, match="returned 1 responses for 2 CURIEs"): |
| 103 | + await _lookup_equivalent_identifiers(namespace, ["CHEBI:17310", "CHEBI:12"]) |
| 104 | + |
| 105 | + |
| 106 | +@pytest.mark.asyncio |
| 107 | +async def test_lookup_equivalent_identifiers_raises_on_per_search_error(): |
| 108 | + namespace = fake_namespace([[{"error": {"type": "query_shard_exception", "reason": "boom"}}]]) |
| 109 | + |
| 110 | + with pytest.raises(RuntimeError, match="Elasticsearch msearch failed for CURIE CHEBI:17310"): |
| 111 | + await _lookup_equivalent_identifiers(namespace, ["CHEBI:17310"]) |
| 112 | + |
| 113 | + |
| 114 | +@pytest.mark.asyncio |
| 115 | +async def test_lookup_curie_metadata_falls_back_when_all_conflation_curies_are_missing(caplog): |
| 116 | + base_source = { |
| 117 | + "identifiers": [{"i": "BASE:1", "l": "base", "c": {"dc": ["MISSING:1"]}}], |
| 118 | + "type": "biolink:ChemicalEntity", |
| 119 | + "ic": 1.0, |
| 120 | + "preferred_name": "base", |
| 121 | + "taxa": [], |
| 122 | + } |
| 123 | + namespace = fake_namespace([[hit_response("BASE:1", base_source)], [no_hit_response()]]) |
| 124 | + |
| 125 | + with caplog.at_level(logging.WARNING): |
| 126 | + nodes = await _lookup_curie_metadata(namespace, ["BASE:1"], {"DrugChemical": True}) |
| 127 | + |
| 128 | + assert len(nodes) == 1 |
| 129 | + assert nodes[0].curie == "BASE:1" |
| 130 | + assert [identifier["i"] for identifier in nodes[0].identifiers] == ["BASE:1"] |
| 131 | + assert "falling back to base normalized node" in caplog.text |
| 132 | + assert not [record for record in caplog.records if record.levelno >= logging.ERROR] |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.asyncio |
| 136 | +async def test_lookup_curie_metadata_logs_skipped_conflation_curies_once(caplog): |
| 137 | + base_source = { |
| 138 | + "identifiers": [{"i": "BASE:1", "l": "base", "c": {"dc": ["MISSING:1", "CONF:1"]}}], |
| 139 | + "type": "biolink:ChemicalEntity", |
| 140 | + "ic": 1.0, |
| 141 | + "preferred_name": "base", |
| 142 | + "taxa": [], |
| 143 | + } |
| 144 | + conflation_source = { |
| 145 | + "identifiers": [{"i": "CONF:1", "l": "conflated"}], |
| 146 | + "type": "biolink:Drug", |
| 147 | + "ic": 2.0, |
| 148 | + "preferred_name": "conflated", |
| 149 | + "taxa": [], |
| 150 | + } |
| 151 | + namespace = fake_namespace( |
| 152 | + [ |
| 153 | + [hit_response("BASE:1", base_source)], |
| 154 | + [no_hit_response(), hit_response("CONF:1", conflation_source)], |
| 155 | + ] |
| 156 | + ) |
| 157 | + |
| 158 | + with caplog.at_level(logging.WARNING): |
| 159 | + nodes = await _lookup_curie_metadata(namespace, ["BASE:1"], {"DrugChemical": True}) |
| 160 | + |
| 161 | + assert len(nodes) == 1 |
| 162 | + assert [identifier["i"] for identifier in nodes[0].identifiers] == ["CONF:1"] |
| 163 | + skip_logs = [record for record in caplog.records if "Skipped 1 conflation CURIEs" in record.message] |
| 164 | + assert len(skip_logs) == 1 |
0 commit comments