diff --git a/tests/test_backend_workflow.py b/tests/test_backend_workflow.py new file mode 100644 index 0000000..8baef5b --- /dev/null +++ b/tests/test_backend_workflow.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import importlib +import sys +import types + +from dataclasses import dataclass, field +from enum import Enum +from pathlib import Path +from typing import Any + +import pytest + +from hphbiome import ( + CuratedKnowledgeRecord, + KnowledgeCollection, + ScientificReference, + build_structured_knowledge_context, + build_text_knowledge_context, + knowledge_collection_to_json, + load_knowledge_collection_json, + retrieve_knowledge, + save_knowledge_collection_json, +) + + +class FakeStage(str, Enum): + DIAGNOSIS = 'diagnosis' + TREATMENT = 'treatment' + + +@dataclass(frozen=True) +class FakeSkillMetadata: + name: str + version: str = '0.1.0' + stages: tuple[str, ...] = () + description: str = '' + + +@dataclass +class FakeInquiry: + skill_name: str + stage: str + field: str + label: str + description: str = '' + priority: str = 'supplementary' + input_type: str = 'text' + choices: list[str] | None = None + + +class FakeBaseSkill: + def __init__(self, metadata: FakeSkillMetadata) -> None: + self.metadata = metadata + + +@dataclass +class FakePipelineContext: + patient: dict[str, Any] = field(default_factory=dict) + results: dict[str, Any] = field(default_factory=dict) + extras: dict[str, Any] = field(default_factory=dict) + + +def import_skill_module( + monkeypatch: pytest.MonkeyPatch, +) -> types.ModuleType: + pipeline = types.ModuleType('hiperhealth.pipeline') + pipeline.BaseSkill = FakeBaseSkill + pipeline.Inquiry = FakeInquiry + pipeline.SkillMetadata = FakeSkillMetadata + pipeline.Stage = FakeStage + + context = types.ModuleType('hiperhealth.pipeline.context') + context.PipelineContext = FakePipelineContext + + hiperhealth = types.ModuleType('hiperhealth') + hiperhealth.pipeline = pipeline + + monkeypatch.setitem(sys.modules, 'hiperhealth', hiperhealth) + monkeypatch.setitem(sys.modules, 'hiperhealth.pipeline', pipeline) + monkeypatch.setitem(sys.modules, 'hiperhealth.pipeline.context', context) + monkeypatch.delitem(sys.modules, 'hphbiome_hiperhealth', raising=False) + monkeypatch.delitem( + sys.modules, + 'hphbiome_hiperhealth.skill', + raising=False, + ) + return importlib.import_module('hphbiome_hiperhealth.skill') + + +def test_curated_knowledge_backend_workflow_reaches_hiperhealth( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + alpha_reference = ScientificReference( + title='Fictional amber source', + authors=['Example Author Alpha'], + source='Imaginary Research Review', + identifier='fictional-id:alpha', + canonical_url='https://example.test/sources/alpha', + ) + beta_reference = ScientificReference( + title='Fictional comet source', + authors=['Example Author Beta', 'Example Author Gamma'], + source='Imaginary Research Review', + identifier='fictional-id:beta', + canonical_url='https://example.test/sources/beta', + ) + partial_record = CuratedKnowledgeRecord( + id='fictional-record-partial', + title='Fictional amber observation', + synthesis='A fictional observation with one query token.', + references=[alpha_reference.canonical_url], + review_status='fictional-visible', + ) + full_record = CuratedKnowledgeRecord( + id='fictional-record-full', + title='Fictional amber comet observation', + synthesis='A fictional synthesis preserving its supplied wording.', + references=[ + beta_reference.canonical_url, + alpha_reference.identifier, + ], + review_status='fictional-visible', + ) + hidden_record = CuratedKnowledgeRecord( + id='fictional-record-hidden', + title='Fictional amber comet hidden observation', + synthesis='A fictional result excluded by caller-defined status.', + references=[beta_reference.identifier], + review_status='fictional-hidden', + ) + collection = KnowledgeCollection( + records=[partial_record, full_record, hidden_record], + references=[alpha_reference, beta_reference], + ) + + collection_path = tmp_path / 'fictional-knowledge.json' + save_knowledge_collection_json(collection, collection_path) + loaded_collection = load_knowledge_collection_json(collection_path) + + assert collection_path.read_text(encoding='utf-8') == ( + knowledge_collection_to_json(collection) + ) + assert loaded_collection == collection + + query = 'amber comet' + allowed_review_statuses = ['fictional-visible'] + first_results = retrieve_knowledge( + loaded_collection, + query, + allowed_review_statuses=allowed_review_statuses, + limit=2, + ) + second_results = retrieve_knowledge( + loaded_collection, + query, + allowed_review_statuses=allowed_review_statuses, + limit=2, + ) + + assert first_results == second_results + assert tuple(result.record.id for result in first_results) == ( + 'fictional-record-full', + 'fictional-record-partial', + ) + assert tuple(first_results[0].references) == ( + beta_reference, + alpha_reference, + ) + assert all( + result.record.review_status == 'fictional-visible' + for result in first_results + ) + + structured_context = build_structured_knowledge_context(first_results) + text_context = build_text_knowledge_context(first_results) + + assert [ + result['record_id'] for result in structured_context['results'] + ] == ['fictional-record-full', 'fictional-record-partial'] + assert structured_context['results'][0]['references'] == [ + { + 'identifier': 'fictional-id:beta', + 'canonical_url': 'https://example.test/sources/beta', + }, + { + 'identifier': 'fictional-id:alpha', + 'canonical_url': 'https://example.test/sources/alpha', + }, + ] + assert text_context.index('Record ID: fictional-record-full') < ( + text_context.index('Record ID: fictional-record-partial') + ) + assert 'fictional-id:beta' in text_context + assert 'https://example.test/sources/alpha' in text_context + assert 'fictional-record-hidden' not in text_context + + skill_module = import_skill_module(monkeypatch) + skill = skill_module.HPHBiomeSkill(collection=loaded_collection) + pipeline_context = FakePipelineContext( + patient={'symptoms': 'fictional patient context'}, + extras={ + '_run_kwargs': { + 'hphbiome_query': query, + 'hphbiome_allowed_review_statuses': allowed_review_statuses, + 'hphbiome_limit': 2, + } + }, + ) + + pipeline_context = skill.pre(FakeStage.DIAGNOSIS, pipeline_context) + pipeline_context = skill.execute( + FakeStage.DIAGNOSIS, + pipeline_context, + ) + biome_result = pipeline_context.results['diagnosis']['hphbiome'] + final_knowledge = biome_result['curated_knowledge'] + + assert biome_result['available_fields'] == { + 'symptoms': 'fictional patient context' + } + assert [ + result['record']['id'] for result in final_knowledge['results'] + ] == ['fictional-record-full', 'fictional-record-partial'] + assert final_knowledge['results'][0]['references'][0] == ( + beta_reference.to_dict() + ) + assert final_knowledge['results'][0]['references'][1] == ( + alpha_reference.to_dict() + ) + assert final_knowledge['structured_context'] == structured_context + assert final_knowledge['text_context'] == text_context + assert 'fictional-record-hidden' not in str(final_knowledge)