From aca6ae20b2ae94ad7f673a3934c8a8a295303525 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 12:22:13 +0200 Subject: [PATCH] replaced tests to mock async behavior --- service/src/main/inse/funders/test_logic.py | 492 ++++++++---------- .../inse/patents/test_ipc_search_client.py | 88 ++-- .../src/main/inse/works/test_search_client.py | 132 ++--- 3 files changed, 329 insertions(+), 383 deletions(-) diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py index 234ffdcf..9c95dbd4 100644 --- a/service/src/main/inse/funders/test_logic.py +++ b/service/src/main/inse/funders/test_logic.py @@ -1,7 +1,5 @@ -import json - -import httpx import pytest +from unittest.mock import AsyncMock, patch from fastapi import HTTPException from inse.funders import logic @@ -68,201 +66,177 @@ def _funded_publication_hit( @pytest.mark.anyio -async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - assert payload["from"] == 0 - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - author_position="first", - pdf_url="https://example.org/w1.pdf", - abstract_inverted_index={ - "This": [0], - "is": [1], - "an": [2], - "abstract.": [3], +async def test_get_funders_by_author_id_aggregates_funders_and_awards(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + author_position="first", + pdf_url="https://example.org/w1.pdf", + abstract_inverted_index={ + "This": [0], + "is": [1], + "an": [2], + "abstract.": [3], + }, + extra_source={ + "title": "Example publication: full detail", + "funders": [ + { + "id": "https://openalex.org/F456", + "display_name": "Funder B", + } + ], + "publication_year": 2020, + "publication_date": "2020-05-10", + "type": "article", + "language": "en", + "cited_by_count": 12, + "is_retracted": False, + "primary_location": { + "pdf_url": "https://example.org/w1.pdf", + "is_oa": True, + "license": "cc-by", + "source": { + "display_name": "Example Journal", + "type": "journal", }, - extra_source={ - "title": "Example publication: full detail", - "funders": [ - { - "id": "https://openalex.org/F456", - "display_name": "Funder B", - } - ], - "publication_year": 2020, - "publication_date": "2020-05-10", - "type": "article", - "language": "en", - "cited_by_count": 12, - "is_retracted": False, - "primary_location": { - "pdf_url": "https://example.org/w1.pdf", - "is_oa": True, - "license": "cc-by", - "source": { - "display_name": "Example Journal", - "type": "journal", - }, - }, - "open_access": { - "is_oa": True, - "oa_status": "gold", - "any_repository_has_fulltext": True, - }, - "primary_topic": { - "display_name": "Clinical Trials", - "subfield": {"display_name": "Medicine"}, - "field": {"display_name": "Health Sciences"}, - "domain": {"display_name": "Life Sciences"}, - }, - "topics": [ - {"display_name": "Trials", "score": 0.8}, - {"display_name": "Guidelines", "score": 0.6}, - ], - "keywords": [ - {"display_name": "randomised trials", "score": 0.9}, - {"display_name": "reporting guideline", "score": 0.7}, - ], - "counts_by_year": [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ], - }, - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name="Project Grant", - award_number="PG-42", - author_position="last", - ), - ], - }, - }, - ) + }, + "open_access": { + "is_oa": True, + "oa_status": "gold", + "any_repository_has_fulltext": True, + }, + "primary_topic": { + "display_name": "Clinical Trials", + "subfield": {"display_name": "Medicine"}, + "field": {"display_name": "Health Sciences"}, + "domain": {"display_name": "Life Sciences"}, + }, + "topics": [ + {"display_name": "Trials", "score": 0.8}, + {"display_name": "Guidelines", "score": 0.6}, + ], + "keywords": [ + {"display_name": "randomised trials", "score": 0.9}, + {"display_name": "reporting guideline", "score": 0.7}, + ], + "counts_by_year": [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ], + }, + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name="Project Grant", + award_number="PG-42", + author_position="last", + ), + ], + }, + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + mock_author_result = type( + "Result", + (), + {"results": [type("Author", (), {"display_name": "Example Author"})()]} + )() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert response.author_id == "https://openalex.org/A5023888391" - assert response.author_name == "Example Author" - assert response.funder_count == 2 - assert response.funders[0].funder_id == "https://openalex.org/F123" - assert response.funders[0].funder_name == "Funder A" - assert response.funders[0].publication_count == 2 - assert response.funders[0].author_position_count.first == 1 - assert response.funders[0].author_position_count.last == 1 - assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"] - assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"] - assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" - assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" - publication_detail = response.funders[0].publication_details["https://openalex.org/W1"] - assert publication_detail.title == "Example publication: full detail" - assert publication_detail.funder_names == ["Funder A", "Funder B"] - assert publication_detail.abstract == "This is an abstract." - assert publication_detail.publication_date == "2020-05-10" - assert publication_detail.publication_type == "article" - assert publication_detail.source_name == "Example Journal" - assert publication_detail.source_type == "journal" - assert publication_detail.is_open_access is True - assert publication_detail.open_access_status == "gold" - assert publication_detail.has_fulltext is True - assert publication_detail.license == "cc-by" - assert publication_detail.cited_by_count == 12 - assert publication_detail.primary_topic == "Clinical Trials" - assert publication_detail.topic_field == "Health Sciences" - assert publication_detail.topic_subfield == "Medicine" - assert publication_detail.topic_domain == "Life Sciences" - assert publication_detail.topics == ["Trials", "Guidelines"] - assert publication_detail.keywords == ["randomised trials", "reporting guideline"] - assert publication_detail.counts_by_year == [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ] - assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [ - "Project Grant" - ] + assert response.author_id == "https://openalex.org/A5023888391" + assert response.author_name == "Example Author" + assert response.funder_count == 2 + + funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123") + assert funder_a.funder_name == "Funder A" + assert funder_a.publication_count == 2 + assert funder_a.author_position_count.first == 1 + assert funder_a.author_position_count.last == 1 + assert funder_a.publication_ids.first == ["https://openalex.org/W1"] + assert funder_a.publication_ids.last == ["https://openalex.org/W2"] + assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" + assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" + + pub1_detail = funder_a.publication_details["https://openalex.org/W1"] + assert pub1_detail.title == "Example publication: full detail" + assert pub1_detail.funder_names == ["Funder A", "Funder B"] + assert pub1_detail.abstract == "This is an abstract." + assert pub1_detail.publication_date == "2020-05-10" + assert pub1_detail.publication_type == "article" + assert pub1_detail.source_name == "Example Journal" + assert pub1_detail.source_type == "journal" + assert pub1_detail.is_open_access is True + assert pub1_detail.open_access_status == "gold" + assert pub1_detail.has_fulltext is True + assert pub1_detail.license == "cc-by" + assert pub1_detail.cited_by_count == 12 + assert pub1_detail.primary_topic == "Clinical Trials" + assert pub1_detail.topic_field == "Health Sciences" + assert pub1_detail.topic_subfield == "Medicine" + assert pub1_detail.topic_domain == "Life Sciences" + assert pub1_detail.topics == ["Trials", "Guidelines"] + assert pub1_detail.keywords == ["randomised trials", "reporting guideline"] + assert pub1_detail.counts_by_year == [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ] + assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"] @pytest.mark.anyio -async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 1}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W3", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name=None, - award_number="ANR-12-1234", - ), - ], - }, - }, - ) +async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(): + mock_es_response = { + "hits": { + "total": {"value": 1}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W3", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name=None, + award_number="ANR-12-1234", + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - response = await logic.get_funders_by_author_id("A5023888391", client=client) - - assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] + assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch): +async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(): requested_pages: list[int] = [] - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - size = payload["size"] - offset = payload["from"] + async def mock_search_func(index, body, cluster=None): + size = body["size"] + offset = body["from"] page = offset // size + 1 requested_pages.append(page) total = size + 1 @@ -284,115 +258,89 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m ) ] - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": total}, - "hits": hits, - }, + return { + "hits": { + "total": {"value": total}, + "hits": hits, }, - ) + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + mock_author_result = type("Result", (), {"results": []})() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert requested_pages == [1, 2] - assert response.funder_count > 1 - funder_names = {funder.funder_name for funder in response.funders} - assert "Funder 1" in funder_names + assert requested_pages == [1, 2] + assert response.funder_count > 1 + funder_names = {funder.funder_name for funder in response.funders} + assert "Funder 1" in funder_names @pytest.mark.anyio -async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Bundesministerium", - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - ), - ], - }, - }, - ) +async def test_get_funders_by_author_id_ignores_publications_without_funders(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Bundesministerium", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 1 - assert response.funders[0].funder_name == "Bundesministerium" - assert response.funders[0].publication_count == 1 + assert response.funder_count == 1 + assert response.funders[0].funder_name == "Bundesministerium" + assert response.funders[0].publication_count == 1 @pytest.mark.anyio -async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={"hits": {"total": {"value": 0}, "hits": []}}, - ) +async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(): + mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}} + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 0 - assert response.funders == [] + assert response.funder_count == 0 + assert response.funders == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch): - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) - client = FundedPublicationsSearchClient(api_key="") +async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(): + mock_author_result = type("Result", (), {"results": []})() - with pytest.raises(HTTPException) as exc: - await logic.get_funders_by_author_id("A5023888391", client=client) + with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - assert exc.value.status_code == 503 + client = FundedPublicationsSearchClient(api_key="") + + with pytest.raises(HTTPException) as exc: + await logic.get_funders_by_author_id("A5023888391", client=client) + + assert exc.value.status_code == 503 diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py index 4bf064bd..78df758e 100644 --- a/service/src/main/inse/patents/test_ipc_search_client.py +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -1,4 +1,4 @@ -import httpx +from unittest.mock import AsyncMock, patch import pytest from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient @@ -11,57 +11,51 @@ def anyio_backend(): @pytest.mark.anyio async def test_resolve_symbols_posts_to_ipc_index(): - requests: list[str] = [] + mock_response = { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + }, + { + "_source": { + "cpc_class_number": "H01L", + "cpc_class_name": "SEMICONDUCTOR DEVICES", + } + }, + { + "_source": { + "cpc_group_number": "H01L21/02", + "cpc_group_name": "Manufacture or treatment of semiconductor devices", + } + }, + ] + } + } - def handler(request: httpx.Request) -> httpx.Response: - requests.append(request.url.path) - return httpx.Response( - 200, - json={ - "hits": { - "hits": [ - { - "_source": { - "cpc_section_number": "H", - "cpc_section_name": "ELECTRICITY", - } - }, - { - "_source": { - "cpc_class_number": "H01L", - "cpc_class_name": "SEMICONDUCTOR DEVICES", - } - }, - { - "_source": { - "cpc_group_number": "H01L21/02", - "cpc_group_name": "Manufacture or treatment of semiconductor devices", - } - }, - ] - } - }, - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = mock_response + client = IpcSearchClient() - transport = httpx.MockTransport(handler) - client = IpcSearchClient(api_key="test-key", transport=transport) + result = await client.resolve_symbols(["H01L 21/02"]) - result = await client.resolve_symbols(["H01L 21/02"]) - - assert len(requests) >= 1 - assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests) - assert "H01L 21/02" in result - assert result["H01L 21/02"].section == "H - ELECTRICITY" - assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" + assert mock_search.call_count >= 1 + _, kwargs = mock_search.call_args + assert kwargs.get("index") == IPC_INDEX + assert "H01L 21/02" in result + assert result["H01L 21/02"].section == "H - ELECTRICITY" + assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" @pytest.mark.anyio async def test_resolve_symbols_does_not_crash_for_subclass_codes(): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, json={"hits": {"hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"hits": []}} + client = IpcSearchClient() + result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler)) - result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - - assert "A61J 1/14" in result - assert "C07D 319/06" in result + assert "A61J 1/14" in result + assert "C07D 319/06" in result diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 0bfe1a44..1297d848 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter(): ] +from unittest.mock import AsyncMock, patch + + @pytest.mark.anyio async def test_search_author_works_passes_institution_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) - assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( - "authorships.institutions" + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") + assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions" assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { "authorships.institutions.id": ["https://openalex.org/I205640436"], } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - institution_id=["https://openalex.org/I205640436"], - ) @pytest.mark.anyio async def test_search_author_works_passes_topic_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body["query"]["bool"]["filter"] == [ { "bool": { @@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query(): }, }, ] - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - topic_id=["https://openalex.org/T12419"], - ) @pytest.mark.anyio async def test_search_author_works_calls_elasticsearch_index_with_api_key(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "POST" - assert request.url.path == "/elastic/openalex-works/_search" - assert request.headers["Authorization"] == "ApiKey test-key" - return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + result = await client.search_author_works("A5023888391", page=1, size=20) - result = await client.search_author_works("A5023888391", page=1, size=20) - - assert result == {"hits": {"total": {"value": 0}, "hits": []}} + assert result == {"hits": {"total": {"value": 0}, "hits": []}} @pytest.mark.anyio async def test_search_work_filters_by_work_id(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_work("W2741809807") + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body == { - "size": 1, - "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + "query": { + "bool": { + "should": [ + { + "term": { + "_id": { + "value": "W2741809807", + "boost": 5 + } + } + }, + { + "term": { + "doi": { + "value": "https://doi.org/w2741809807", + "boost": 3 + } + } + } + ], + "minimum_should_match": 1 + } + } } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_work("W2741809807") @pytest.mark.anyio