diff --git a/README.md b/README.md index 52fd7c6..041dee9 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ result.short_name | `EFO` | [Experimental Factor Ontology](https://www.ebi.ac.uk/efo/) | ✅ | | `EMPTY` | [Experimental Measurements, Purposes, and Treatments ontologY](https://github.com/Waltham-Data-Science/empty-ontology) | ✅ | | `NDIC` | NDI Controlled Vocabulary (local) | ✅ | -| `WBStrain` | [WormBase Strain Database](https://wormbase.org) | ✅ | +| `WBStrain` / `wormbase` | [WormBase](https://wormbase.org) strains, read from [WormMine](https://wormmine.alliancegenome.org) | ✅ | | `UBERON` | [Uberon Multi-Species Anatomy Ontology](http://obofoundry.org/ontology/uberon.html) | ✅ | | `NCIT` | [NCI Thesaurus](http://obofoundry.org/ontology/ncit.html) | ✅ | | `EDAM` / `format` | [EDAM Bioinformatics Ontology](http://edamontology.org) | ✅ | diff --git a/src/ndi_ontology/ndi_common/ontology/ontology_list.json b/src/ndi_ontology/ndi_common/ontology/ontology_list.json index 34058b3..2dde2c1 100644 --- a/src/ndi_ontology/ndi_common/ontology/ontology_list.json +++ b/src/ndi_ontology/ndi_common/ontology/ontology_list.json @@ -48,7 +48,8 @@ {"prefix": "EMPTY", "ontology_name": "EMPTY"}, {"prefix": "NCIT", "ontology_name": "NCIT"}, {"prefix": "SNOMED", "ontology_name": "SNOMED"}, - {"prefix": "WBStrain", "ontology_name": "WBStrain"}, + {"prefix": "WBStrain", "ontology_name": "WormBase"}, + {"prefix": "wormbase", "ontology_name": "WormBase"}, {"prefix": "EFO", "ontology_name": "EFO"}, {"prefix": "EDAM", "ontology_name": "EDAM"}, {"prefix": "format", "ontology_name": "EDAM"}, @@ -119,9 +120,9 @@ "api_url": "https://www.ebi.ac.uk/ols4/api/ontologies/ncit" }, { - "name": "WBStrain", + "name": "WormBase", "homepage": "https://wormbase.org", - "api_url": "https://wormbase.org/species/c_elegans/strain" + "api_url": "https://wormmine.alliancegenome.org/wormmine/service" }, { "name": "SNOMED", diff --git a/src/ndi_ontology/ndi_matlab_python_bridge.yaml b/src/ndi_ontology/ndi_matlab_python_bridge.yaml index 515aa4e..5bd0d0b 100644 --- a/src/ndi_ontology/ndi_matlab_python_bridge.yaml +++ b/src/ndi_ontology/ndi_matlab_python_bridge.yaml @@ -12,10 +12,12 @@ project_metadata: extracted into ndi-ontology-matlab (commit d302b0d) and is pulled back into NDI-matlab through requirements.txt. All MATLAB paths in this file are relative to ndi-ontology-matlab unless the entry says otherwise. - Examined against ndi-ontology-matlab at 984abef (2026-09-02). + Examined against ndi-ontology-matlab at 984abef (2026-09-02); re-examined + at 9d8fc03 (2026-10-14) for its PR #9 (WormBase, NCBITaxon synonyms, + string input). - matlab_examined_hash: "984abef" - matlab_examined_date: "2026-09-02" + matlab_examined_hash: "9d8fc03" + matlab_examined_date: "2026-10-14" examination_note: > Per the porting guide's section 3, each entry records matlab_last_sync_hash: the short hash of the MATLAB file the Python side @@ -431,23 +433,70 @@ providers: python_class: "NCBITaxonProvider" inherits: "OntologyProvider" status: ported - matlab_last_sync_hash: "8e109b0" + matlab_last_sync_hash: "0c18bf8" sync_status: > - NOT EXAMINED against NCBITaxon.m at 8e109b0. Python implementation predates - the extraction and mirrors NDI-python's pre-split behaviour, which was - never checked against this MATLAB class. + SYNONYMS EXAMINED against NCBITaxon.m at 0c18bf8 (2026-10-14); the id + and name-search paths are still NOT EXAMINED. + MATLAB's synonyms now come from the static parseOtherNames, ported as + NCBITaxonProvider.parseOtherNames under its MATLAB name, with the same + regular expressions, kept kinds and order (tagged elements first, then + entries of a kept , unescaped, trimmed, de-duplicated). + Python previously returned every -- authority citations and + misspellings included -- plus , and missed and + . Tests: tests/matlab_tests/test_ontology_parsing.py. + methods: + - name: parseOtherNames + kind: static + python_name: "NCBITaxonProvider.parseOtherNames" + input_arguments: + - name: xml_response + type_matlab: "char" + type_python: "str" + output_arguments: + - name: names + type_matlab: "cell column of char" + type_python: "list[str]" - - name: WBStrain - matlab_path: "src/ndi/+ndi/+ontology/WBStrain.m" + - name: WormBase + matlab_path: "src/ndi/+ndi/+ontology/WormBase.m" python_path: "ndi_ontology/providers.py" - python_class: "WBStrainProvider" + python_class: "WormBaseProvider" inherits: "OntologyProvider" status: ported - matlab_last_sync_hash: "8e109b0" + matlab_examined: true + matlab_last_sync_hash: "ff3c3fd" sync_status: > - NOT EXAMINED against WBStrain.m at 8e109b0. Python implementation predates - the extraction and mirrors NDI-python's pre-split behaviour, which was - never checked against this MATLAB class. + EXAMINED and PORTED against WormBase.m at ff3c3fd (2026-10-14). + Renamed from WBStrain / WBStrainProvider, as MATLAB renamed the class + (ff3c3fd); the WBStrain prefix is unchanged and a new `wormbase` prefix + (the Bioregistry CURIE, wormbase:WBStrain00000001) routes here too, its + id returned in that form. Strains are read from WormMine's InterMine + query service (jsonobjects), as MATLAB does since 0c18bf8: wormbase.org + and rest.wormbase.org answer scripts with a Cloudflare 403. The old + Python provider read rest.wormbase.org for ids and the Alliance search + API for names, and swallowed every error into an empty result. + Definition is "Genotype: ... Mutagen: ... Outcrossed: ...", synonyms the + otherName. Not found is an empty result (lookup() raises); a non-strain + WormBase id, a "*", an ambiguous or mismatched name, and a WormMine + error raise ValueError, where MATLAB raises ndi:ontology:WormBase:*. + methods: + - name: parseStrain + kind: static + python_name: "WormBaseProvider.parseStrain" + input_arguments: + - name: strain + type_matlab: "struct (one webread-decoded WormMine record)" + type_python: "dict (one JSON-decoded WormMine record)" + output_arguments: + - name: "[id, name, definition, synonyms]" + type_python: "tuple[str, str, str, list[str]]" + - name: queryWormMine + kind: static + python_name: "WormBaseProvider.queryWormMine" + decision_log: > + Private static in MATLAB; an instance method in Python so it goes + through the provider's _http_get_json, which the tests mock per + instance as they do for every other provider. Recorded 2026-10-14. - name: RRID matlab_path: "src/ndi/+ndi/+ontology/RRID.m" @@ -618,8 +667,12 @@ data_files: - name: ontology_list.json matlab_path: "src/ndi/ndi_common/ontology/ontology_list.json" python_path: "ndi_ontology/ndi_common/ontology/ontology_list.json" - matlab_last_sync_hash: "5c75ead" + matlab_last_sync_hash: "ff3c3fd" sync_status: > + IN SYNC as of 2026-10-14: byte-identical copy of ndi-ontology-matlab at + ff3c3fd -- 23 prefixes, WBStrain and the new wormbase both mapped to + WormBase, whose api_url is now WormMine. + Earlier history: IN SYNC as of 2026-09-02: copied from ndi-ontology-matlab at 5c75ead, 22 prefixes, alongside the six providers that make them all resolvable (NDI-python#98). Previously 17, and two of those -- Uberon and NCIT -- @@ -666,9 +719,37 @@ tests: so a local run without network is still usable. Recorded 2026-09-02. + - matlab_path: "tests/+ndi/+unittest/+ontology/TestNCBITaxonOtherNames.m" + python_path: "tests/matlab_tests/test_ontology_parsing.py" + matlab_last_sync_hash: "0c18bf8" + sync_status: "PORTED 1:1 at 0c18bf8 (2026-10-14), as TestNCBITaxonOtherNames. Offline." + + - matlab_path: "tests/+ndi/+unittest/+ontology/TestWormBaseParsing.m" + python_path: "tests/matlab_tests/test_ontology_parsing.py" + matlab_last_sync_hash: "ff3c3fd" + sync_status: > + PORTED 1:1 at ff3c3fd (2026-10-14), as TestWormBaseParsing. Offline. + The records are dicts with None where webread gives []. + + - matlab_path: "tests/+ndi/+unittest/+ontology/TestLookupStringInput.m" + python_path: "tests/matlab_tests/test_ontology_parsing.py" + matlab_last_sync_hash: "0c18bf8" + sync_status: > + PORTED at 0c18bf8 (2026-10-14), as TestLookupStringInput. MATLAB's fix + (convertStringsToChars in lookup) has no Python counterpart -- Python + has one string type -- so the test only checks two NDIC lookups agree. + Kept so the suites stay one-to-one. + + - matlab_path: "tests/+ndi/+unittest/+ontology/TestLookupSynonyms.m" + python_path: "tests/matlab_tests/test_ontology_parsing.py" + matlab_last_sync_hash: "0c18bf8" + sync_status: > + PORTED 1:1 at 0c18bf8 (2026-10-14), as TestLookupSynonymsLive, under the + `live` marker (NCBI and WormMine). + - matlab_path: "tests/+ndi/+unittest/+ontology/ontology_lookup_tests.json" python_path: "tests/test_shared_cases.py" - matlab_last_sync_hash: "8e109b0" + matlab_last_sync_hash: "ff3c3fd" role: symmetry sync_status: > CONSUMED DIRECTLY, not vendored. This is the parity check for the @@ -682,6 +763,9 @@ tests: reports parity that is not there. Of the 66: 47 run against ported providers, 19 skip themselves naming NDI-python#98, so the run doubles as a progress meter for the port. + ff3c3fd (2026-10-14) added seven WormBase cases (by id, by name, the + wormbase: CURIE, and four that must fail), so WormBase left + test_case_table_covers_every_ported_provider's known gaps. # ========================================================================= # Caching @@ -784,10 +868,10 @@ functions: type: function matlab_path: "src/ndi/+ndi/ontology.m (static method)" python_path: "ndi_ontology/__init__.py" - matlab_last_sync_hash: "9d9b4e1" + matlab_last_sync_hash: "0c18bf8" input_arguments: - name: lookup_string - type_matlab: "char" + type_matlab: "char or string scalar" type_python: "str" output_arguments: - name: result @@ -795,6 +879,9 @@ functions: decision_log: > Module-level convenience function. Delegates to provider registry. Uses @pydantic.validate_call. Synchronized 2026-03-13. + 0c18bf8 made MATLAB's lookup accept a string scalar + (convertStringsToChars); Python has one string type, so nothing to + port. Examined 2026-10-14. - name: clearCache type: function diff --git a/src/ndi_ontology/providers.py b/src/ndi_ontology/providers.py index c7ccbcc..2f0b51e 100644 --- a/src/ndi_ontology/providers.py +++ b/src/ndi_ontology/providers.py @@ -12,6 +12,7 @@ import re from typing import Any from urllib.parse import quote +from xml.sax.saxutils import escape import pydantic @@ -326,21 +327,75 @@ def _lookup_taxid(self, taxid: str) -> Any: return OntologyResult() name = taxon.findtext("ScientificName", "") - synonyms = [] - for other in taxon.findall(".//OtherNames/Name/DispName"): - if other.text: - synonyms.append(other.text) - common = taxon.findtext(".//OtherNames/CommonName", "") - if common: - synonyms.insert(0, common) return OntologyResult( id=f"NCBITaxon:{taxid}", name=name, prefix="NCBITaxon", - synonyms=synonyms, + synonyms=self.parseOtherNames(resp.text), ) + # The kinds of entry that name the same taxon. MATLAB: keptKinds in + # NCBITaxon.parseOtherNames. + _KEPT_KINDS = ( + "genbank common name", + "common name", + "synonym", + "genbank synonym", + "equivalent name", + "acronym", + "genbank acronym", + ) + + @staticmethod + @pydantic.validate_call + def parseOtherNames(xml_response: str) -> list[str]: + """The other names of a taxon in an efetch record. + + MATLAB equivalent: ndi.ontology.NCBITaxon.parseOtherNames + + Reads the first ```` block of an E-utilities efetch taxonomy + record and returns its names in the order they appear, without + duplicates. NCBI tags each name with its kind, either as its own element + (``house mouse``) or as a + ```` entry with a ```` and a ````. The kinds + kept are those naming the same taxon: common names, synonyms (such as a + former genus, 'Rhabditis elegans'), equivalent names and acronyms. + Authority citations ('Mus musculus Linnaeus, 1758'), misspellings, and + ```` (narrower groups such as 'nude mice') are left out. + Public so the parsing can be tested without the network. + + Regular expressions rather than an XML parser, as MATLAB does, so the + two read the same record the same way. + """ + block = re.search(r"(.*?)", xml_response, re.S) + if block is None: + return [] + block_text = block.group(1) + # entries carry their kind in + entry_names = [] + for entry in re.findall(r"(.*?)", block_text, re.S): + kind = re.search(r"(.*?)", entry, re.S) + disp_name = re.search(r"(.*?)", entry, re.S) + if ( + kind is not None + and disp_name is not None + and kind.group(1).strip().lower() in NCBITaxonProvider._KEPT_KINDS + ): + entry_names.append(disp_name.group(1)) + # the elements named by their kind, outside the entries + block_text = re.sub(r".*?", "", block_text, flags=re.S) + tagged = re.findall( + r"<(GenbankCommonName|CommonName|Synonym|GenbankSynonym|" + r"EquivalentName|Acronym|GenbankAcronym)>(.*?)", + block_text, + re.S, + ) + names = [_unescape_xml(n).strip() for _, n in tagged] + [ + _unescape_xml(n).strip() for n in entry_names + ] + return list(dict.fromkeys(n for n in names if n)) + def _search_name(self, name: str) -> Any: import defusedxml.ElementTree as ET import requests @@ -359,53 +414,155 @@ def _search_name(self, name: str) -> Any: return self._lookup_taxid(id_list[0].text or "") -class WBStrainProvider(OntologyProvider): - """WormBase Strain ndi_database.""" +class WormBaseProvider(OntologyProvider): + """WormBase strains, read from WormMine. - name = "WBStrain" + MATLAB equivalent: ndi-ontology-matlab src/ndi/+ndi/+ontology/WormBase.m + + Serves the ``WBStrain`` and ``wormbase`` prefixes. Strains are read from + WormMine, the Alliance of Genome Resources' InterMine copy of WormBase + (https://wormmine.alliancegenome.org). The WormBase site and REST API + (wormbase.org, rest.wormbase.org) answer programmatic requests with a + Cloudflare browser challenge (HTTP 403), so every lookup through them + failed. + """ + + name = "WormBase" + + SERVICE_URL = "https://wormmine.alliancegenome.org/wormmine/service/query/results" + _ID_PREFIX = "WBStrain" + _VIEW = ( + "Strain.primaryIdentifier Strain.name Strain.genotype " + "Strain.otherName Strain.mutagen Strain.outcrossed" + ) @pydantic.validate_call def lookup_term(self, term: str, prefix: str = "") -> Any: - from . import OntologyResult + """Look up a strain in WormBase by its ID or public name. - try: - if re.match(r"^\d{8}$", term): - return self._lookup_id(term) - return self._search_name(term) - except Exception: - return OntologyResult() + ``term`` is the part after the prefix: - def _lookup_id(self, strain_id: str) -> Any: + - ``WBStrain:00000001`` -- an eight-digit ID + - ``WBStrain:N2`` -- a strain name, matched ignoring case + - ``wormbase:WBStrain00000001`` -- the Bioregistry CURIE (prefix + ``wormbase``; Bioregistry has no ``wbstrain``) + + The id is in the form asked for: ``WBStrain:00000001`` for the first + two, ``wormbase:WBStrain00000001`` for the third. The name is the strain + name, the definition its genotype, mutagen and outcrossing, and the + synonyms its other name, if it has one. + + No strain found is an empty result, which lookup() raises on. Every + other failure MATLAB raises for raises here too. + """ from . import OntologyResult - data = self._http_get_json( - f"http://rest.wormbase.org/rest/widget/strain/{strain_id}/overview", - ) - overview = data.get("fields", {}) - name_data = overview.get("name", {}).get("data", {}) - name = name_data.get("label", "") if isinstance(name_data, dict) else "" - genotype = overview.get("genotype", {}).get("data", "") + id_prefix = self._ID_PREFIX + term = term.strip() + if "*" in term: + raise ValueError(f'A strain name or ID cannot contain "*" ("{term}").') + is_curie = re.fullmatch(rf"{id_prefix}\d{{8}}", term) is not None + if is_curie: + term = term[len(id_prefix) :] + elif re.fullmatch(r"CE\d{5}|WB[A-Z][a-z]+\d+", term): + # another kind of WormBase id, such as a gene (WBGene00000001) + raise ValueError( + f'"{term}" is a WormBase id but not a strain id ' + f"(WBStrain followed by eight digits)." + ) + is_id_lookup = re.fullmatch(r"\d{8}", term) is not None + if is_id_lookup: + path, value = "Strain.primaryIdentifier", id_prefix + term + else: + path, value = "Strain.name", term + strains = self.queryWormMine(path, value) + if not strains: + return OntologyResult() + if len(strains) > 1: + raise ValueError( + f'{len(strains)} WormBase strains match "{term}"; use the WBStrain ID instead.' + ) + + id_, name, definition, synonyms = self.parseStrain(strains[0]) + if is_curie: + id_ = "wormbase:" + id_.replace(":", "") + if not is_id_lookup and name.lower() != term.lower(): + raise ValueError( + f'WormMine returned strain "{name}" for the name "{term}". ' + f"Try the WBStrain ID instead." + ) return OntologyResult( - id=f"WBStrain:{strain_id}", + id=id_, name=name, - prefix="WBStrain", - definition=str(genotype) if genotype else "", + prefix=prefix or id_prefix, + definition=definition, + synonyms=synonyms, ) - def _search_name(self, name: str) -> Any: - from . import OntologyResult - - data = self._http_get_json( - "https://www.alliancegenome.org/api/search", - params={"category": "model", "q": f"{name}(Cel)"}, + @staticmethod + @pydantic.validate_call + def parseStrain(strain: dict) -> tuple[str, str, str, list[str]]: + """The lookup outputs for one WormMine strain record. + + MATLAB equivalent: ndi.ontology.WormBase.parseStrain + + ``strain`` is one record of a WormMine ``jsonobjects`` query: a dict + with keys primaryIdentifier, name, genotype, otherName, mutagen and + outcrossed, any of which may be missing or None. Returns + ``(id, name, definition, synonyms)``. Public so the parsing can be + tested without the network. + + Raises: + ValueError: the record has no valid WBStrain ID, or no name. + """ + id_prefix = WormBaseProvider._ID_PREFIX + + def field(key: str) -> str: + value = strain.get(key) + return "" if value is None else str(value).strip() + + wb_id = field("primaryIdentifier") + if not re.fullmatch(rf"{id_prefix}\d{{8}}", wb_id): + raise ValueError(f'WormMine returned a strain without a valid WBStrain ID ("{wb_id}").') + id_ = f"{id_prefix}:{wb_id[len(id_prefix):]}" + + name = field("name") + if not name: + raise ValueError(f"WormMine returned strain {id_} without a name.") + + parts = [] + if field("genotype"): + parts.append("Genotype: " + field("genotype")) + if field("mutagen"): + parts.append("Mutagen: " + field("mutagen")) + if field("outcrossed"): + parts.append("Outcrossed: " + field("outcrossed")) + definition = ". ".join(parts).replace("..", ".") + if definition and not definition.endswith("."): + definition += "." + + synonyms = [field("otherName")] if field("otherName") else [] + return id_, name, definition, synonyms + + def queryWormMine(self, path: str, value: str) -> list[dict]: + """The WormMine strain records whose ``path`` equals ``value``. + + MATLAB equivalent: ndi.ontology.WormBase.queryWormMine (private there) + """ + query = ( + f'' + f'' + f"" ) - results = data.get("results", []) - if not results: - return OntologyResult() - primary_id = results[0].get("primaryId", "") - strain_id = primary_id.split(":")[-1] if ":" in primary_id else primary_id - return self._lookup_id(strain_id) + response = self._http_get_json( + self.SERVICE_URL, params={"query": query, "format": "jsonobjects"} + ) + if not isinstance(response, dict) or "results" not in response: + raise ValueError("WormMine returned an unexpected response.") + if response.get("wasSuccessful") is False: + raise ValueError(f"WormMine reported an error: {response.get('error')}") + return list(response["results"] or []) class RRIDProvider(OntologyProvider): @@ -1017,7 +1174,7 @@ def lookup_term(self, term: str, prefix: str = "") -> Any: "NCIm": NCImProvider, "CHEBI": CHEBIProvider, "NCBITaxon": NCBITaxonProvider, - "WBStrain": WBStrainProvider, + "WormBase": WormBaseProvider, "SNOMED": SNOMEDProvider, "RRID": RRIDProvider, "EFO": EFOProvider, diff --git a/tests/matlab_tests/test_ontology_parsing.py b/tests/matlab_tests/test_ontology_parsing.py new file mode 100644 index 0000000..8716fc6 --- /dev/null +++ b/tests/matlab_tests/test_ontology_parsing.py @@ -0,0 +1,210 @@ +""" +Port of MATLAB ndi.unittest.ontology.* tests added with the WormBase rename. + +MATLAB source files: + +ontology/TestNCBITaxonOtherNames.m -> TestNCBITaxonOtherNames + +ontology/TestWormBaseParsing.m -> TestWormBaseParsing + +ontology/TestLookupStringInput.m -> TestLookupStringInput + +ontology/TestLookupSynonyms.m -> TestLookupSynonymsLive + +The first three run offline; TestLookupSynonymsLive queries NCBI and WormMine. +""" + +import pytest + +from ndi_ontology import clearCache, lookup +from ndi_ontology.providers import NCBITaxonProvider, WormBaseProvider +from tests._live import network_available + +# =========================================================================== +# TestNCBITaxonOtherNames +# =========================================================================== + + +class TestNCBITaxonOtherNames: + """The names NCBITaxon returns as synonyms, read from literal efetch records. + + The parser this replaces read only and every , so a + or a was never returned, and authority + citations ('Mus musculus Linnaeus, 1758') and misspellings were. + """ + + def test_former_genus_is_a_synonym(self): + # NCBITaxon:6239, as efetch returns it + xml = ( + "6239" + "Caenorhabditis elegans" + "" + "Rhabditis elegans" + "authority" + "Caenorhabditis elegans (Maupas, 1900)" + "authority" + "Rhabditis elegans Maupas, 1899" + "" + ) + assert NCBITaxonProvider.parseOtherNames(xml) == ["Rhabditis elegans"] + + def test_common_names_and_not_includes_or_misspellings(self): + # NCBITaxon:10090, shortened + xml = ( + "" + "house mouse" + "mouse" + "nude mice" + "authority" + "Mus musculus Linnaeus, 1758" + "misspelling" + "mice C57BL/6xCBA/CaJ hybrid" + "" + ) + assert NCBITaxonProvider.parseOtherNames(xml) == ["house mouse", "mouse"] + + def test_name_entries_of_a_kept_kind(self): + xml = ( + "" + "equivalent name" + "Escherichia coli & relatives" + "synonym" + "Bacillus coli" + "Bacillus coli" + "" + ) + assert NCBITaxonProvider.parseOtherNames(xml) == [ + "Bacillus coli", + "Escherichia coli & relatives", + ] + + def test_no_other_names(self): + assert ( + NCBITaxonProvider.parseOtherNames("x") + == [] + ) + assert ( + NCBITaxonProvider.parseOtherNames( + "authority" + "x Smith, 1900" + ) + == [] + ) + + +# =========================================================================== +# TestWormBaseParsing +# =========================================================================== + + +class TestWormBaseParsing: + """How a WormMine strain record becomes the WBStrain lookup outputs. + + The records are the ones WormMine returns for N2, MT13113 and BK6. + """ + + def test_wild_type(self): + s = { + "primaryIdentifier": "WBStrain00000001", + "name": "N2", + "genotype": "Caenorhabditis elegans wild isolate.", + "otherName": None, + "mutagen": None, + "outcrossed": None, + } + id_, name, definition, synonyms = WormBaseProvider.parseStrain(s) + assert id_ == "WBStrain:00000001" + assert name == "N2" + assert definition == "Genotype: Caenorhabditis elegans wild isolate." + assert synonyms == [] + + def test_mutant(self): + s = { + "primaryIdentifier": "WBStrain00027424", + "name": "MT13113", + "genotype": "tdc-1(n3419) II.", + "otherName": None, + "mutagen": "UV+TMP", + "outcrossed": "x11", + } + id_, name, definition, _ = WormBaseProvider.parseStrain(s) + assert id_ == "WBStrain:00027424" + assert name == "MT13113" + assert definition == "Genotype: tdc-1(n3419) II. Mutagen: UV+TMP. Outcrossed: x11." + + def test_other_name_is_a_synonym(self): + s = { + "primaryIdentifier": "WBStrain00003818", + "name": "BK6", + "genotype": None, + "otherName": "BK006", + "mutagen": None, + "outcrossed": None, + } + _, _, definition, synonyms = WormBaseProvider.parseStrain(s) + assert definition == "" + assert synonyms == ["BK006"] + + def test_record_without_an_id_is_an_error(self): + # MATLAB: verifyError(..., 'ndi:ontology:WormBase:APIParsingFailed') + with pytest.raises(ValueError, match="valid WBStrain ID"): + WormBaseProvider.parseStrain({"primaryIdentifier": None, "name": "N2"}) + + +# =========================================================================== +# TestLookupStringInput +# =========================================================================== + + +class TestLookupStringInput: + """lookup() of a string gives the same result as of a character vector. + + MATLAB's fix (convertStringsToChars at the top of ndi.ontology.lookup) has + nothing to port: Python has one string type. The test is kept so the two + suites stay one-to-one. NDIC is read from a packaged file, so no network. + """ + + def test_string_gives_the_same_result_as_char(self): + clearCache() + first = lookup("NDIC:8") + clearCache() + second = lookup("NDIC:8") + assert first.id == second.id + assert first.name == second.name + assert first.prefix == "NDIC" + assert second.prefix == "NDIC" + + +# =========================================================================== +# TestLookupSynonyms - Live network +# =========================================================================== + + +@pytest.mark.live +class TestLookupSynonymsLive: + """The synonyms lookup() returns, from the live services.""" + + @pytest.fixture(autouse=True) + def _requires_network(self): + if not network_available(): + pytest.skip("No network access for ontology lookup") + + def test_c_elegans_former_genus(self): + clearCache() + result = lookup("NCBITaxon:6239") + assert result.name == "Caenorhabditis elegans" + assert ( + "Rhabditis elegans" in result.synonyms + ), "NCBI lists Rhabditis elegans as a synonym of C. elegans." + assert not any( + "Maupas" in s for s in result.synonyms + ), "Authority citations are not synonyms." + + def test_mouse_common_names(self): + clearCache() + result = lookup("NCBITaxon:10090") + assert {"house mouse", "mouse"} <= set( + result.synonyms + ), 'NCBI lists "house mouse" (GenBank) and "mouse" for Mus musculus.' + + def test_strain_definition(self): + clearCache() + result = lookup("WBStrain:MT13113") + assert result.name == "MT13113" + assert "tdc-1(n3419)" in result.definition, "The definition carries the strain genotype." diff --git a/tests/test_ontology.py b/tests/test_ontology.py index 9c09ad2..80627c0 100644 --- a/tests/test_ontology.py +++ b/tests/test_ontology.py @@ -2,6 +2,8 @@ from unittest.mock import MagicMock, patch +import pytest + # --------------------------------------------------------------------------- # OntologyResult tests # --------------------------------------------------------------------------- @@ -219,7 +221,7 @@ def test_registry_populated(self): assert "NCIm" in PROVIDER_REGISTRY assert "CHEBI" in PROVIDER_REGISTRY assert "NCBITaxon" in PROVIDER_REGISTRY - assert "WBStrain" in PROVIDER_REGISTRY + assert "WormBase" in PROVIDER_REGISTRY assert "SNOMED" in PROVIDER_REGISTRY assert "RRID" in PROVIDER_REGISTRY assert "EFO" in PROVIDER_REGISTRY @@ -685,37 +687,120 @@ def test_not_found(self): # --------------------------------------------------------------------------- -# WBStrainProvider tests +# WormBaseProvider tests # --------------------------------------------------------------------------- -class TestWBStrainProvider: - """Tests for WormBase strain provider.""" +def _wormmine(*records): + """A WormMine jsonobjects response holding RECORDS.""" + return {"results": list(records), "wasSuccessful": True, "error": None} + + +_N2 = { + "primaryIdentifier": "WBStrain00000001", + "name": "N2", + "genotype": "Caenorhabditis elegans wild isolate.", + "otherName": None, + "mutagen": None, + "outcrossed": None, +} + + +class TestWormBaseProvider: + """Tests for the WormBase strain provider (WormMine-backed).""" def test_numeric_id_lookup(self): - from ndi_ontology.providers import WBStrainProvider + from ndi_ontology.providers import WormBaseProvider - provider = WBStrainProvider() - mock_data = { - "fields": { - "name": {"data": {"label": "N2"}}, - "genotype": {"data": "wild type"}, - } - } - with patch.object(provider, "_http_get_json", return_value=mock_data): - result = provider.lookup_term("00000001") + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json", return_value=_wormmine(_N2)) as get: + result = provider.lookup_term("00000001", "WBStrain") assert result.id == "WBStrain:00000001" assert result.name == "N2" - assert result.definition == "wild type" + assert result.prefix == "WBStrain" + assert result.definition == "Genotype: Caenorhabditis elegans wild isolate." + query = get.call_args.kwargs["params"]["query"] + assert 'path="Strain.primaryIdentifier"' in query + assert 'value="WBStrain00000001"' in query + + def test_name_lookup_ignores_case(self): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json", return_value=_wormmine(_N2)) as get: + result = provider.lookup_term("n2", "WBStrain") + assert result.id == "WBStrain:00000001" + assert 'path="Strain.name"' in get.call_args.kwargs["params"]["query"] - def test_api_error(self): - from ndi_ontology.providers import WBStrainProvider + def test_bioregistry_curie_keeps_its_form(self): + from ndi_ontology.providers import WormBaseProvider - provider = WBStrainProvider() - with patch.object(provider, "_http_get_json", side_effect=Exception("error")): - result = provider.lookup_term("N2") + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json", return_value=_wormmine(_N2)): + result = provider.lookup_term("WBStrain00000001", "wormbase") + assert result.id == "wormbase:WBStrain00000001" + assert result.prefix == "wormbase" + + def test_not_found_is_empty(self): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json", return_value=_wormmine()): + result = provider.lookup_term("99999999", "WBStrain") assert not result + @pytest.mark.parametrize("term", ["WBGene00000001", "CE12345", "N*"]) + def test_not_a_strain_raises_without_a_query(self, term): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json") as get: + with pytest.raises(ValueError): + provider.lookup_term(term, "wormbase") + get.assert_not_called() + + def test_ambiguous_name_raises(self): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + other = dict(_N2, primaryIdentifier="WBStrain00000002") + with patch.object(provider, "_http_get_json", return_value=_wormmine(_N2, other)): + with pytest.raises(ValueError, match="2 WormBase strains"): + provider.lookup_term("N2", "WBStrain") + + def test_name_mismatch_raises(self): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + with patch.object(provider, "_http_get_json", return_value=_wormmine(_N2)): + with pytest.raises(ValueError, match="Try the WBStrain ID"): + provider.lookup_term("N3", "WBStrain") + + def test_wormmine_error_raises(self): + from ndi_ontology.providers import WormBaseProvider + + provider = WormBaseProvider() + response = {"results": [], "wasSuccessful": False, "error": "bad query"} + with patch.object(provider, "_http_get_json", return_value=response): + with pytest.raises(ValueError, match="bad query"): + provider.lookup_term("N2", "WBStrain") + + def test_api_error_reaches_lookup_as_lookup_error(self): + from ndi_ontology import NDIOntologyLookupError, clearCache, lookup + from ndi_ontology.providers import WormBaseProvider + + clearCache() + with patch.object(WormBaseProvider, "_http_get_json", side_effect=Exception("403")): + with pytest.raises(NDIOntologyLookupError, match="403"): + lookup("WBStrain:N2") + + def test_both_prefixes_route_to_wormbase(self): + from ndi_ontology import _load_prefix_map + + m = _load_prefix_map() + assert m["WBStrain"] == "WormBase" + assert m["wormbase"] == "WormBase" + # --------------------------------------------------------------------------- # EMPTYProvider tests diff --git a/tests/test_shared_cases.py b/tests/test_shared_cases.py index 7bb8ae4..c39bb52 100644 --- a/tests/test_shared_cases.py +++ b/tests/test_shared_cases.py @@ -247,7 +247,9 @@ def test_case_table_covers_every_ported_provider() -> None: # NCIT joined this list when it was ported for NDI-python#98 -- the table # covers fifteen ontologies and NCIT is not one of them. This test is what # noticed; that is what it is for. - known_gaps = {"WBStrain", "SNOMED", "EFO", "NCIT"} + # + # WormBase left it when ndi-ontology-matlab added its strain cases (9d8fc03). + known_gaps = {"SNOMED", "EFO", "NCIT"} unexpected = set(uncovered) - known_gaps assert not unexpected, ( f"ported providers with no case in ndi-ontology-matlab's table: " f"{sorted(unexpected)}"