Add backend endpoint for author works search
This commit is contained in:
@@ -14,7 +14,7 @@ task test(type: Exec) {
|
||||
|
||||
task runServeContainer(type: Exec) {
|
||||
dependsOn createImage
|
||||
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
|
||||
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
|
||||
}
|
||||
|
||||
task stopServeContainer(type: Exec) {
|
||||
|
||||
@@ -19,6 +19,11 @@ class Settings(BaseSettings):
|
||||
auth_disabled: bool = False
|
||||
auth_standalone: bool = True
|
||||
auth_secret: str = 'change-me-to-a-secure-secret-key'
|
||||
# OpenAlex works search config
|
||||
openalex_works_search_base_url: str = 'https://project.nes.uni-due.de/elastic'
|
||||
openalex_works_search_index: str = 'openalex-works'
|
||||
openalex_works_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=='
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
|
||||
settings = Settings()
|
||||
logger.info(f"Database URL: {settings.database_url}.")
|
||||
logger.info(f"Database URL: {settings.database_url}.")
|
||||
|
||||
@@ -22,6 +22,7 @@ from . import schema
|
||||
from . import database
|
||||
from . import security
|
||||
from . import util
|
||||
from .works import service as works_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -32,6 +33,7 @@ app = FastAPI(redoc_url=None,
|
||||
title='My App Service',
|
||||
summary='My App Service API',
|
||||
version='1.0.0')
|
||||
app.include_router(works_service.router)
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def show_api():
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Works domain package.
|
||||
"""
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for publication works.
|
||||
"""
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from . import model
|
||||
from .search_client import MissingApiKeyError
|
||||
from .search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_author_works(
|
||||
author_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> model.WorkPage:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
try:
|
||||
data = await search_client.search_author_works(author_id, page, size)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
|
||||
hits = data.get("hits", {})
|
||||
total = hits.get("total", 0)
|
||||
if isinstance(total, dict):
|
||||
total = total.get("value", 0)
|
||||
|
||||
try:
|
||||
elements = [
|
||||
model.WorkSummary.model_validate(_to_work_summary(hit.get("_source", {})))
|
||||
for hit in hits.get("hits", [])
|
||||
]
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex works search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
return model.WorkPage(elements=elements, page=page, size=size, total=total)
|
||||
|
||||
|
||||
def _to_work_summary(source: dict) -> dict:
|
||||
return {
|
||||
"doi": source.get("doi"),
|
||||
"title": source.get("title") or source.get("display_name"),
|
||||
"type": source.get("type"),
|
||||
"language": source.get("language"),
|
||||
"publication_year": source.get("publication_year"),
|
||||
"cited_by_count": source.get("cited_by_count") or 0,
|
||||
"topics": [
|
||||
topic["display_name"]
|
||||
for topic in source.get("topics") or []
|
||||
if topic.get("display_name")
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Pydantic models for publication works.
|
||||
"""
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import ConfigDict
|
||||
from pydantic import Field
|
||||
|
||||
|
||||
class OpenAlexModel(BaseModel):
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class Source(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The source id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The source display name.")
|
||||
issn_l: Optional[str] = Field(default=None, description="The linking ISSN.")
|
||||
issn: Optional[List[str]] = Field(default=None, description="The ISSNs of the source.")
|
||||
is_oa: Optional[bool] = Field(default=None, description="Whether the source is open access.")
|
||||
is_in_doaj: Optional[bool] = Field(default=None, description="Whether the source is in DOAJ.")
|
||||
is_core: Optional[bool] = Field(default=None, description="Whether the source is a core source.")
|
||||
host_organization: Optional[str] = Field(default=None, description="The host organization id.")
|
||||
host_organization_name: Optional[str] = Field(default=None, description="The host organization name.")
|
||||
host_organization_lineage: Optional[List[str]] = Field(default=None, description="The host organization lineage.")
|
||||
type: Optional[str] = Field(default=None, description="The source type.")
|
||||
|
||||
|
||||
class Location(OpenAlexModel):
|
||||
is_oa: Optional[bool] = Field(default=None, description="Whether this location is open access.")
|
||||
landing_page_url: Optional[str] = Field(default=None, description="The landing page URL.")
|
||||
pdf_url: Optional[str] = Field(default=None, description="The PDF URL.")
|
||||
source: Optional[Source] = Field(default=None, description="The publication source.")
|
||||
license: Optional[str] = Field(default=None, description="The license label.")
|
||||
license_id: Optional[str] = Field(default=None, description="The license id.")
|
||||
is_accepted: Optional[bool] = Field(default=None, description="Whether this manuscript is accepted.")
|
||||
is_published: Optional[bool] = Field(default=None, description="Whether this manuscript is published.")
|
||||
|
||||
|
||||
class OpenAccess(OpenAlexModel):
|
||||
is_oa: Optional[bool] = Field(default=None, description="Whether the work is open access.")
|
||||
oa_url: Optional[str] = Field(default=None, description="The open access URL.")
|
||||
any_repository_has_fulltext: Optional[bool] = Field(default=None, description="Whether a repository has full text.")
|
||||
|
||||
|
||||
class Author(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The author id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The display name of the author.")
|
||||
orcid: Optional[str] = Field(default=None, description="The optional ORCID of the author.")
|
||||
|
||||
|
||||
class Institution(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The institution id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The institution display name.")
|
||||
ror: Optional[str] = Field(default=None, description="The ROR id.")
|
||||
country_code: Optional[str] = Field(default=None, description="The country code.")
|
||||
type: Optional[str] = Field(default=None, description="The institution type.")
|
||||
lineage: Optional[List[str]] = Field(default=None, description="The institution lineage.")
|
||||
|
||||
|
||||
class Authorship(OpenAlexModel):
|
||||
author: Optional[Author] = Field(default=None, description="The author.")
|
||||
institutions: List[Institution] = Field(default_factory=list, description="The author's institutions.")
|
||||
countries: List[str] = Field(default_factory=list, description="The author's countries.")
|
||||
is_corresponding: Optional[bool] = Field(default=None, description="Whether this author is corresponding.")
|
||||
raw_author_name: Optional[str] = Field(default=None, description="The raw author name.")
|
||||
raw_affiliation_strings: List[str] = Field(default_factory=list, description="The raw affiliation strings.")
|
||||
|
||||
|
||||
class WorkIds(OpenAlexModel):
|
||||
openalex: Optional[str] = Field(default=None, description="The OpenAlex id.")
|
||||
doi: Optional[str] = Field(default=None, description="The DOI.")
|
||||
mag: Optional[int] = Field(default=None, description="The MAG id.")
|
||||
pmid: Optional[str] = Field(default=None, description="The PubMed id.")
|
||||
pmcid: Optional[str] = Field(default=None, description="The PubMed Central id.")
|
||||
|
||||
|
||||
class Biblio(OpenAlexModel):
|
||||
volume: Optional[str] = Field(default=None, description="The volume.")
|
||||
issue: Optional[str] = Field(default=None, description="The issue.")
|
||||
first_page: Optional[str] = Field(default=None, description="The first page.")
|
||||
last_page: Optional[str] = Field(default=None, description="The last page.")
|
||||
|
||||
|
||||
class TopicLevel(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The topic level id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The topic level display name.")
|
||||
|
||||
|
||||
class Topic(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The topic id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The topic display name.")
|
||||
score: Optional[float] = Field(default=None, description="The topic score.")
|
||||
subfield: Optional[TopicLevel] = Field(default=None, description="The topic subfield.")
|
||||
field: Optional[TopicLevel] = Field(default=None, description="The topic field.")
|
||||
domain: Optional[TopicLevel] = Field(default=None, description="The topic domain.")
|
||||
|
||||
|
||||
class Keyword(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The keyword id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The keyword display name.")
|
||||
score: Optional[float] = Field(default=None, description="The keyword score.")
|
||||
|
||||
|
||||
class Funder(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The funder id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The funder display name.")
|
||||
ror: Optional[str] = Field(default=None, description="The ROR id.")
|
||||
|
||||
|
||||
class Award(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The award id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The award display name.")
|
||||
funder_award_id: Optional[str] = Field(default=None, description="The funder award id.")
|
||||
funder_id: Optional[str] = Field(default=None, description="The funder id.")
|
||||
funder_display_name: Optional[str] = Field(default=None, description="The funder display name.")
|
||||
doi: Optional[str] = Field(default=None, description="The award DOI.")
|
||||
|
||||
|
||||
class CitationNormalizedPercentile(OpenAlexModel):
|
||||
value: Optional[float] = Field(default=None, description="The normalized citation percentile.")
|
||||
is_in_top_1_percent: Optional[bool] = Field(default=None, description="Whether the work is in the top 1 percent.")
|
||||
is_in_top_10_percent: Optional[bool] = Field(default=None, description="Whether the work is in the top 10 percent.")
|
||||
|
||||
|
||||
class CitedByPercentileYear(OpenAlexModel):
|
||||
min: Optional[int] = Field(default=None, description="The minimum percentile year.")
|
||||
max: Optional[int] = Field(default=None, description="The maximum percentile year.")
|
||||
|
||||
|
||||
class CountByYear(OpenAlexModel):
|
||||
year: Optional[int] = Field(default=None, description="The year.")
|
||||
cited_by_count: int = Field(default=0, description="The citation count for the year.")
|
||||
|
||||
|
||||
class SustainableDevelopmentGoal(OpenAlexModel):
|
||||
id: Optional[str] = Field(default=None, description="The sustainable development goal id.")
|
||||
display_name: Optional[str] = Field(default=None, description="The sustainable development goal display name.")
|
||||
score: Optional[float] = Field(default=None, description="The sustainable development goal score.")
|
||||
|
||||
|
||||
class Mesh(OpenAlexModel):
|
||||
descriptor_ui: Optional[str] = Field(default=None, description="The descriptor UI.")
|
||||
descriptor_name: Optional[str] = Field(default=None, description="The descriptor name.")
|
||||
qualifier_ui: Optional[str] = Field(default=None, description="The qualifier UI.")
|
||||
qualifier_name: Optional[str] = Field(default=None, description="The qualifier name.")
|
||||
is_major_topic: Optional[bool] = Field(default=None, description="Whether this is a major topic.")
|
||||
|
||||
|
||||
class HasContent(OpenAlexModel):
|
||||
pdf: Optional[bool] = Field(default=None, description="Whether PDF content exists.")
|
||||
grobid_xml: Optional[bool] = Field(default=None, description="Whether GROBID XML content exists.")
|
||||
|
||||
|
||||
class Work(OpenAlexModel):
|
||||
id: str = Field(description="The external id of the work.")
|
||||
doi: Optional[str] = Field(default=None, description="The optional DOI of the work.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the work.")
|
||||
display_name: Optional[str] = Field(default=None, description="The display name of the work.")
|
||||
publication_year: Optional[int] = Field(default=None, description="The publication year.")
|
||||
publication_date: Optional[str] = Field(default=None, description="The publication date.")
|
||||
type: Optional[str] = Field(default=None, description="The work type.")
|
||||
language: Optional[str] = Field(default=None, description="The work language.")
|
||||
cited_by_count: int = Field(default=0, description="The number of citations.")
|
||||
is_retracted: Optional[bool] = Field(default=None, description="Whether the work is retracted.")
|
||||
is_paratext: Optional[bool] = Field(default=None, description="Whether the work is paratext.")
|
||||
primary_location: Optional[Location] = Field(default=None, description="The primary location.")
|
||||
locations: List[Location] = Field(default_factory=list, description="The work locations.")
|
||||
best_oa_location: Optional[Location] = Field(default=None, description="The best open access location.")
|
||||
open_access: Optional[OpenAccess] = Field(default=None, description="Open access information.")
|
||||
authorships: List[Authorship] = Field(default_factory=list, description="The authorships.")
|
||||
ids: Optional[WorkIds] = Field(default=None, description="External ids.")
|
||||
biblio: Optional[Biblio] = Field(default=None, description="Bibliographic information.")
|
||||
abstract_inverted_index: dict[str, List[int]] = Field(default_factory=dict, description="The inverted abstract index.")
|
||||
referenced_works: List[str] = Field(default_factory=list, description="Referenced work ids.")
|
||||
referenced_works_count: int = Field(default=0, description="The number of referenced works.")
|
||||
related_works: List[str] = Field(default_factory=list, description="Related work ids.")
|
||||
topics: List[Topic] = Field(default_factory=list, description="The topics.")
|
||||
primary_topic: Optional[Topic] = Field(default=None, description="The primary topic.")
|
||||
keywords: List[Keyword] = Field(default_factory=list, description="The keywords.")
|
||||
funders: List[Funder] = Field(default_factory=list, description="The funders.")
|
||||
awards: List[Award] = Field(default_factory=list, description="The awards.")
|
||||
fwci: Optional[float] = Field(default=None, description="The field weighted citation impact.")
|
||||
citation_normalized_percentile: Optional[CitationNormalizedPercentile] = Field(default=None, description="The normalized citation percentile.")
|
||||
cited_by_percentile_year: Optional[CitedByPercentileYear] = Field(default=None, description="The cited by percentile year.")
|
||||
counts_by_year: List[CountByYear] = Field(default_factory=list, description="Citation counts by year.")
|
||||
sustainable_development_goals: List[SustainableDevelopmentGoal] = Field(default_factory=list, description="Sustainable development goals.")
|
||||
mesh: List[Mesh] = Field(default_factory=list, description="MeSH terms.")
|
||||
indexed_in: List[str] = Field(default_factory=list, description="Indexes containing the work.")
|
||||
has_content: Optional[HasContent] = Field(default=None, description="Available content flags.")
|
||||
content_url: Optional[str] = Field(default=None, description="The content URL.")
|
||||
created_date: Optional[str] = Field(default=None, description="The creation date.")
|
||||
updated_date: Optional[str] = Field(default=None, description="The last update timestamp.")
|
||||
|
||||
|
||||
class WorkSummary(BaseModel):
|
||||
doi: Optional[str] = Field(default=None, description="The optional DOI of the work.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the work.")
|
||||
type: Optional[str] = Field(default=None, description="The work type.")
|
||||
language: Optional[str] = Field(default=None, description="The work language.")
|
||||
publication_year: Optional[int] = Field(default=None, description="The publication year.")
|
||||
cited_by_count: int = Field(default=0, description="The number of citations.")
|
||||
topics: List[str] = Field(default_factory=list, description="The display names of the work topics.")
|
||||
|
||||
|
||||
class WorkPage(BaseModel):
|
||||
elements: List[WorkSummary] = Field(default_factory=list, description="The works on this page.")
|
||||
page: int = Field(default=1, description="The current page number.")
|
||||
size: int = Field(default=20, description="The requested page size.")
|
||||
total: int = Field(default=0, description="The total number of works.")
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for the OpenAlex works Elasticsearch index.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class OpenAlexWorksSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
index: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
|
||||
self.index = index or config.settings.openalex_works_search_index
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
def author_works_query(self, author_id: str, page: int, size: int) -> dict[str, Any]:
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": indexed_author_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"sort": [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
}
|
||||
|
||||
async def search_author_works(self, author_id: str, page: int, size: int) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=self.author_works_query(author_id, page, size),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for publication works.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Depends
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
from .. import security
|
||||
from . import logic
|
||||
from . import model
|
||||
|
||||
|
||||
router = APIRouter(prefix="/authors", tags=["Works"])
|
||||
|
||||
|
||||
@router.get("/{author_id}/works",
|
||||
operation_id="getAuthorWorks",
|
||||
response_model=model.WorkPage,
|
||||
summary="Returns a page of works for an author.")
|
||||
async def get_author_works(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
page: Annotated[int, Query(description="The page number.", ge=1)] = 1,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1, le=100)] = 20,
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_author_works(author_id, page, size)
|
||||
@@ -0,0 +1,103 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.works import logic
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/W2741809807",
|
||||
"doi": "https://doi.org/10.7717/peerj.4375",
|
||||
"display_name": "Example work",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"publication_year": 2023,
|
||||
"cited_by_count": 42,
|
||||
"topics": [
|
||||
{
|
||||
"id": "https://openalex.org/T10102",
|
||||
"display_name": "Machine learning",
|
||||
"score": 0.91,
|
||||
}
|
||||
],
|
||||
"primary_location": {
|
||||
"source": {
|
||||
"id": "https://openalex.org/S123",
|
||||
"display_name": "Example Source",
|
||||
"issn": None,
|
||||
}
|
||||
},
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5023888391",
|
||||
"display_name": "Example Author",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
page = await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
assert page.total == 1
|
||||
assert page.elements[0].doi == "https://doi.org/10.7717/peerj.4375"
|
||||
assert page.elements[0].title == "Example work"
|
||||
assert page.elements[0].type == "article"
|
||||
assert page.elements[0].language == "en"
|
||||
assert page.elements[0].publication_year == 2023
|
||||
assert page.elements[0].cited_by_count == 42
|
||||
assert page.elements[0].topics == ["Machine learning"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_missing_api_key_to_service_unavailable():
|
||||
client = OpenAlexWorksSearchClient(api_key="")
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(500, json={"error": "upstream failed"})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
assert exc.value.status_code == 502
|
||||
@@ -0,0 +1,49 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.works.search_client import MissingApiKeyError
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_author_works_query_searches_authorship_author_id():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
query = client.author_works_query("A5023888391", page=2, size=25)
|
||||
|
||||
assert query["from"] == 25
|
||||
assert query["size"] == 25
|
||||
assert query["query"]["nested"]["path"] == "authorships"
|
||||
assert query["query"]["nested"]["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391"
|
||||
|
||||
|
||||
@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": []}})
|
||||
|
||||
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)
|
||||
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_requires_api_key():
|
||||
client = OpenAlexWorksSearchClient(api_key="")
|
||||
|
||||
with pytest.raises(MissingApiKeyError):
|
||||
await client.search_author_works("A5023888391", page=1, size=20)
|
||||
@@ -0,0 +1,53 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from inse import config
|
||||
from inse.works import logic
|
||||
from inse.works import model
|
||||
from inse.main import app
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_get_author_works_returns_page(monkeypatch):
|
||||
config.settings.auth_disabled = True
|
||||
|
||||
async def fake_get_author_works(author_id: str, page: int, size: int):
|
||||
assert author_id == "A5023888391"
|
||||
assert page == 2
|
||||
assert size == 5
|
||||
return model.WorkPage(
|
||||
elements=[
|
||||
model.WorkSummary(
|
||||
doi="https://doi.org/10.7717/peerj.4375",
|
||||
title="Example work",
|
||||
type="article",
|
||||
language="en",
|
||||
publication_year=2023,
|
||||
cited_by_count=42,
|
||||
topics=["Machine learning"],
|
||||
)
|
||||
],
|
||||
page=page,
|
||||
size=size,
|
||||
total=1,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(logic, "get_author_works", fake_get_author_works)
|
||||
|
||||
response = client.get("/inse-service/authors/A5023888391/works?page=2&size=5")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["page"] == 2
|
||||
assert data["size"] == 5
|
||||
assert data["total"] == 1
|
||||
assert data["elements"][0] == {
|
||||
"doi": "https://doi.org/10.7717/peerj.4375",
|
||||
"title": "Example work",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"publication_year": 2023,
|
||||
"cited_by_count": 42,
|
||||
"topics": ["Machine learning"],
|
||||
}
|
||||
Reference in New Issue
Block a user