Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Refactor Phylopic to use ProviderDataIngester (#747)

Madison Swain-Bowden1506d6d9d391
diff --git a/DAGs.md b/DAGs.md
index 929f72188..e01e36642 100644
--- a/DAGs.md
+++ b/DAGs.md
@@ -85,7 +85,7 @@ The following are DAGs grouped by their primary tag:
| [`metropolitan_museum_workflow`](#metropolitan_museum_workflow) | `@daily` | `True` | image |
| `museum_victoria_workflow` | `@monthly` | `False` | image |
| `nypl_workflow` | `@monthly` | `False` | image |
-| [`phylopic_workflow`](#phylopic_workflow) | `@weekly` | `True` | image |
+| [`phylopic_workflow`](#phylopic_workflow) | `@daily` | `True` | image |
| `rawpixel_workflow` | `@monthly` | `False` | image |
| `science_museum_workflow` | `@monthly` | `False` | image |
| [`smithsonian_workflow`](#smithsonian_workflow) | `@weekly` | `False` | image |
diff --git a/openverse_catalog/dags/common/loader/provider_details.py b/openverse_catalog/dags/common/loader/provider_details.py
index e9e6eab49..55922c407 100644
--- a/openverse_catalog/dags/common/loader/provider_details.py
+++ b/openverse_catalog/dags/common/loader/provider_details.py
@@ -33,6 +33,7 @@ STOCKSNAP_DEFAULT_PROVIDER = "stocksnap"
WORDPRESS_DEFAULT_PROVIDER = "wordpress"
FREESOUND_DEFAULT_PROVIDER = "freesound"
INATURALIST_DEFAULT_PROVIDER = "inaturalist"
+PHYLOPIC_DEFAULT_PROVIDER = "phylopic"
# Finnish parameters
FINNISH_SUB_PROVIDERS = {
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
index a3dc32e1d..6e8dd3681 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
@@ -13,272 +13,238 @@ Notes: http://phylopic.org/api/
import argparse
import logging
from datetime import date, timedelta
-from typing import Dict
+from common import constants
from common.licenses import get_license_info
-from common.requester import DelayedRequester
-from common.storage.image import ImageStore
+from common.loader import provider_details as prov
+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
-logging.basicConfig(
- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
-)
logger = logging.getLogger(__name__)
-DELAY = 5.0
-HOST = "phylopic.org"
-ENDPOINT = f"http://{HOST}/api/a"
-PROVIDER = "phylopic"
-LIMIT = 5
-# Default number of days to process if date_end is not defined
-DEFAULT_PROCESS_DAYS = 7
-delayed_requester = DelayedRequester(DELAY)
-image_store = ImageStore(provider=PROVIDER)
-
-
-def main(date_start: str = "all", date_end: str = None):
- """
- This script pulls the data for a given date from the PhyloPic
- API, and writes it into a .TSV file to be eventually read
- into our DB.
-
- Required Arguments:
-
- date_start: Date String in the form YYYY-MM-DD. This date defines the beginning
- of the range that the script will pull data from.
- date_end: Date String in the form YYYY-MM-DD. Similar to `date_start`, this
- defines the end of the range of data pulled. Defaults to
- DEFAULT_PROCESS_DAYS (7) if undefined.
- """
-
- offset = 0
-
- logger.info("Begin: PhyloPic API requests")
-
- if date_start == "all":
- logger.info("Processing all images")
- param = {"offset": offset}
-
- image_count = _get_total_images()
- logger.info(f"Total images: {image_count}")
-
- while offset <= image_count:
- _add_data_to_buffer(**param)
- offset += LIMIT
- param = {"offset": offset}
-
- else:
- if date_end is None:
- date_end = _compute_date_range(date_start)
- param = {"date_start": date_start, "date_end": date_end}
-
- logger.info(f"Processing from {date_start} to {date_end}")
- _add_data_to_buffer(**param)
-
- image_store.commit()
-
- logger.info("Terminated!")
-
-
-def _add_data_to_buffer(**kwargs):
- endpoint = _create_endpoint_for_IDs(**kwargs)
- IDs = _get_image_IDs(endpoint)
- if IDs is None:
- return
-
- for id_ in IDs:
- item_data = _get_object_json(id_)
- if item_data:
- _process_item(item_data)
-
-
-def _process_item(item_data: Dict) -> None:
- details = _get_meta_data(item_data)
- if details is not None:
- image_store.add_item(**details)
-
-
-def _get_total_images() -> int:
- # Get the total number of PhyloPic images
- total = 0
- endpoint = "http://phylopic.org/api/a/image/count"
- result = delayed_requester.get_response_json(endpoint, retries=2)
-
- if result and result.get("success") is True:
- total = result.get("result", 0)
-
- return total
-
-
-def _create_endpoint_for_IDs(**kwargs):
- limit = LIMIT
-
- if ((date_start := kwargs.get("date_start")) is not None) and (
- (date_end := kwargs.get("date_end")) is not None
- ):
- # Get a list of objects uploaded/updated from a given date to another date
- # http://phylopic.org/api/#method-image-time-range
- endpoint = (
- f"http://phylopic.org/api/a/image/list/modified/{date_start}/{date_end}"
- )
-
- elif (offset := kwargs.get("offset")) is not None:
- # Get all images and limit the results for each request.
- endpoint = f"http://phylopic.org/api/a/image/list/{offset}/{limit}"
-
- else:
- raise ValueError("No valid selection criteria found!")
- return endpoint
-
-
-def _get_image_IDs(_endpoint) -> list | None:
- result = delayed_requester.get_response_json(_endpoint, retries=2)
- image_IDs = []
-
- if result and result.get("success") is True:
- data = list(result.get("result"))
-
- if len(data) > 0:
- for item in data:
- image_IDs.append(item.get("uid"))
-
- if not image_IDs:
- logger.warning("No content available!")
- return None
-
- return image_IDs
-
-
-def _get_object_json(_uuid: str) -> Dict | None:
- logger.info(f"Processing UUID: {_uuid}")
-
- endpoint = (
- f"http://phylopic.org/api/a/image/{_uuid}?options=credit+"
- "licenseURL+pngFiles+submitted+submitter+taxa+canonicalName"
- "+string+firstName+lastName"
- )
- result = None
- request = delayed_requester.get_response_json(endpoint, retries=2)
- if request and request.get("success") is True:
- result = request["result"]
- return result
-
-
-def _get_meta_data(result: Dict) -> Dict:
- base_url = "http://phylopic.org"
- meta_data = {}
- _uuid = result.get("uid")
- license_url = result.get("licenseURL")
-
- meta_data["taxa"], title = _get_taxa_details(result)
-
- foreign_url = f"{base_url}/image/{_uuid}"
-
- (creator, meta_data["credit_line"], meta_data["pub_date"]) = _get_creator_details(
- result
- )
-
- img_url, width, height = _get_image_info(result, _uuid)
-
- if img_url is None:
- return None
-
- details = {
- "foreign_identifier": _uuid,
- "foreign_landing_url": foreign_url,
- "image_url": img_url,
- "license_info": get_license_info(license_url=license_url),
- "width": width,
- "height": height,
- "creator": creator,
- "title": title,
- "meta_data": meta_data,
- }
- return details
-
-
-def _get_creator_details(result):
- credit_line = None
- pub_date = None
- creator = None
- first_name = result.get("submitter", {}).get("firstName")
- last_name = result.get("submitter", {}).get("lastName")
- if first_name and last_name:
- creator = f"{first_name} {last_name}".strip()
-
- if result.get("credit"):
- credit_line = result.get("credit").strip()
- pub_date = result.get("submitted").strip()
-
- return creator, credit_line, pub_date
-
-
-def _get_taxa_details(result):
- taxa = result.get("taxa", [])
- # [0].get('canonicalName', {}).get('string')
- taxa_list = None
- title = ""
- if taxa:
- taxa = [
- _.get("canonicalName") for _ in taxa if _.get("canonicalName") is not None
- ]
- taxa_list = [_.get("string", "") for _ in taxa]
-
- if taxa_list:
- title = taxa_list[0]
-
- return taxa_list, title
-
-
-def _get_image_info(result, _uuid):
- base_url = "http://phylopic.org"
- img_url = None
- width = None
- height = None
-
- image_info = result.get("pngFiles")
- if image_info:
- images = list(
- filter(lambda x: (int(str(x.get("width", "0"))) >= 257), image_info)
- )
- if len(images) > 0:
- image = sorted(images, key=lambda x: x["width"], reverse=True)[0]
- img_url = image.get("url")
- if not img_url:
- logging.warning(f"Image not detected in url: {base_url}/image/{_uuid}")
- else:
- img_url = f"{base_url}{img_url}"
- width = image.get("width")
- height = image.get("height")
-
- return img_url, width, height
-
-
-def _compute_date_range(date_start: str, days: int = DEFAULT_PROCESS_DAYS) -> str:
- """
- Given an ISO formatted date string and a number of days, compute the
- ISO string that represents the start date plus the days provided.
- """
- date_end = date.fromisoformat(date_start) + timedelta(days=days)
- return date_end.isoformat()
+class PhylopicDataIngester(ProviderDataIngester):
+ delay = 5
+ host = "http://phylopic.org"
+ # Use "base_endpoint" since class's "endpoint" parameter gets defined as a property
+ base_endpoint = f"{host}/api/a/image"
+ providers = {"image": prov.PHYLOPIC_DEFAULT_PROVIDER}
+ batch_limit = 25
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # This is made an instance attribute rather than passed around via query params
+ # because the URL we hit includes it in the path (not the params) depending on
+ # whether we're running a dated DAG or not. This needs to start at 0 after
+ # getting called once, so we do not set it as a sentinel for the
+ # get_next_query_params function.
+ self.offset = None
+
+ def get_media_type(self, record: dict) -> str:
+ return constants.IMAGE
+
+ @property
+ def endpoint(self) -> str:
+ """
+ If this is being run as a dated DAG, **only one request is ever issued** to
+ retrieve all updated IDs. As such, the dated version will only return one
+ endpoint. The full run DAG does require the typical offset + limit, which gets
+ recomputed on each call to this property.
+ """
+ list_endpoint = f"{self.base_endpoint}/list"
+ if self.date:
+ # Process for a given date
+ end_date = (date.fromisoformat(self.date) + timedelta(days=1)).isoformat()
+ # Get a list of objects uploaded/updated within a date range
+ # http://phylopic.org/api/#method-image-time-range
+ endpoint = f"{list_endpoint}/modified/{self.date}/{end_date}"
+ else:
+ # Get all images and limit the results for each request.
+ endpoint = f"{list_endpoint}/{self.offset}/{self.batch_limit}"
+ logger.info(f"Constructed endpoint: {endpoint}")
+ return endpoint
+
+ def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ """
+ Since the query range is determined via endpoint, this only increments the range
+ to query.
+ """
+ if self.offset is None:
+ self.offset = 0
+ else:
+ self.offset += self.batch_limit
+ return {}
+
+ def get_should_continue(self, response_json):
+ """
+ Override for upstream "return True". Dated runs will only ever make 1 query so
+ they should not continue to loop.
+ """
+ return not bool(self.date)
+
+ @staticmethod
+ def _get_response_data(response_json) -> dict | list | None:
+ """
+ Intermediate method for pulling out results from a Phylopic API request.
+ """
+ if response_json and response_json.get("success") is True:
+ return response_json.get("result")
+
+ def get_batch_data(self, response_json):
+ """
+ Process the returned IDs.
+
+ The Phylopic API returns only lists of IDs in the initial request. We must take
+ this request and iterate through all the IDs to get the metadata for each one.
+ """
+ data = self._get_response_data(response_json)
+
+ if not data:
+ logger.warning("No content available!")
+ return None
+
+ return data
+
+ @staticmethod
+ def _image_url(uid: str) -> str:
+ return f"{PhylopicDataIngester.host}/image/{uid}"
+
+ @staticmethod
+ def _get_image_info(
+ result: dict, uid: str
+ ) -> tuple[str | None, int | None, int | None]:
+ img_url = None
+ width = None
+ height = None
+
+ image_info = result.get("pngFiles")
+ if image_info:
+ images = list(
+ filter(lambda x: (int(str(x.get("width", "0"))) >= 257), image_info)
+ )
+ if images:
+ image = sorted(images, key=lambda x: x["width"], reverse=True)[0]
+ img_url = image.get("url")
+ if not img_url:
+ logging.warning(
+ "Image not detected in url: "
+ f"{PhylopicDataIngester._image_url(uid)}"
+ )
+ else:
+ img_url = f"{PhylopicDataIngester.host}{img_url}"
+ width = image.get("width")
+ height = image.get("height")
+
+ return img_url, width, height
+
+ @staticmethod
+ def _get_taxa_details(result: dict) -> tuple[list[str] | None, str]:
+ taxa = result.get("taxa", [])
+ taxa_list = None
+ title = ""
+ if taxa:
+ taxa = [
+ _.get("canonicalName")
+ for _ in taxa
+ if _.get("canonicalName") is not None
+ ]
+ taxa_list = [_.get("string", "") for _ in taxa]
+
+ if taxa_list:
+ title = taxa_list[0]
+
+ return taxa_list, title
+
+ @staticmethod
+ def _get_creator_details(result: dict) -> tuple[str | None, str | None, str | None]:
+ credit_line = None
+ pub_date = None
+ creator = None
+ submitter = result.get("submitter", {})
+ first_name = submitter.get("firstName")
+ last_name = submitter.get("lastName")
+ if first_name and last_name:
+ creator = f"{first_name} {last_name}".strip()
+
+ if credit := result.get("credit"):
+ credit_line = credit.strip()
+ pub_date = result.get("submitted").strip()
+
+ return creator, credit_line, pub_date
+
+ def get_record_data(self, data: dict) -> dict | list[dict] | None:
+ uid = data.get("uid")
+ if not uid:
+ return
+ logger.debug(f"Processing UUID: {uid}")
+ params = {
+ "options": " ".join(
+ [
+ "credit",
+ "licenseURL",
+ "pngFiles",
+ "submitted",
+ "submitter",
+ "taxa",
+ "canonicalName",
+ "string",
+ "firstName",
+ "lastName",
+ ]
+ )
+ }
+ endpoint = f"{self.base_endpoint}/{uid}"
+ response_json = self.get_response_json(params, endpoint)
+ result = self._get_response_data(response_json)
+ if not result:
+ return None
+
+ meta_data = {}
+ uid = result.get("uid")
+ license_url = result.get("licenseURL")
+
+ img_url, width, height = self._get_image_info(result, uid)
+
+ if img_url is None:
+ return None
+
+ meta_data["taxa"], title = self._get_taxa_details(result)
+
+ foreign_url = self._image_url(uid)
+
+ (
+ creator,
+ meta_data["credit_line"],
+ meta_data["pub_date"],
+ ) = self._get_creator_details(result)
+
+ return {
+ "foreign_identifier": uid,
+ "foreign_landing_url": foreign_url,
+ "image_url": img_url,
+ "license_info": get_license_info(license_url=license_url),
+ "width": width,
+ "height": height,
+ "creator": creator,
+ "title": title,
+ "meta_data": meta_data,
+ }
+
+
+def main(date: str = None):
+ logger.info("Begin: Phylopic provider script")
+ ingester = PhylopicDataIngester(date=date)
+ ingester.ingest_records()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="PhyloPic API Job", add_help=True)
parser.add_argument(
- "--date-start",
- default="all",
- help="Identify all images starting from a particular date (YYYY-MM-DD).",
- )
- parser.add_argument(
- "--date-end",
+ "--date",
default=None,
- help="Used in conjunction with --date-start, identify all images ending on "
- f"a particular date (YYYY-MM-DD), defaults to {DEFAULT_PROCESS_DAYS} "
- "if not defined.",
+ help="Identify all images updated on a particular date (YYYY-MM-DD).",
)
args = parser.parse_args()
- main(args.date_start, args.date_end)
+ main(args.date)
diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.py
index 55b9c53e2..eac4ff9a3 100644
--- a/openverse_catalog/dags/providers/provider_workflows.py
+++ b/openverse_catalog/dags/providers/provider_workflows.py
@@ -12,6 +12,7 @@ from providers.provider_api_scripts.jamendo import JamendoDataIngester
from providers.provider_api_scripts.metropolitan_museum import MetMuseumDataIngester
from providers.provider_api_scripts.museum_victoria import VictoriaDataIngester
from providers.provider_api_scripts.nypl import NyplDataIngester
+from providers.provider_api_scripts.phylopic import PhylopicDataIngester
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
from providers.provider_api_scripts.science_museum import ScienceMuseumDataIngester
from providers.provider_api_scripts.smk import SmkDataIngester
@@ -180,8 +181,9 @@ PROVIDER_WORKFLOWS = [
),
ProviderWorkflow(
provider_script="phylopic",
- start_date=datetime(2011, 1, 1),
- schedule_string="@weekly",
+ ingestion_callable=PhylopicDataIngester,
+ start_date=datetime(2011, 2, 7),
+ schedule_string="@daily",
dated=True,
pull_timeout=timedelta(hours=12),
),
diff --git a/tests/dags/providers/provider_api_scripts/resources/phylopic/total_images_example.json b/tests/dags/providers/provider_api_scripts/resources/phylopic/total_images_example.json
deleted file mode 100644
index 1610580ba..000000000
--- a/tests/dags/providers/provider_api_scripts/resources/phylopic/total_images_example.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "result": 10,
- "success": true
-}
diff --git a/tests/dags/providers/provider_api_scripts/test_phylopic.py b/tests/dags/providers/provider_api_scripts/test_phylopic.py
index a569381ce..07c7aba65 100644
--- a/tests/dags/providers/provider_api_scripts/test_phylopic.py
+++ b/tests/dags/providers/provider_api_scripts/test_phylopic.py
@@ -1,20 +1,14 @@
import json
-import logging
-from functools import partial
from pathlib import Path
from unittest.mock import patch
import pytest
-from common.licenses import get_license_info
-from providers.provider_api_scripts import phylopic as pp
+from common.licenses import LicenseInfo
+from providers.provider_api_scripts.phylopic import PhylopicDataIngester
RESOURCES = Path(__file__).parent / "resources/phylopic"
-
-logging.basicConfig(
- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s",
- level=logging.DEBUG,
-)
+pp = PhylopicDataIngester()
@pytest.fixture
@@ -27,171 +21,183 @@ def get_json(filename):
return json.load(f)
-def test_get_total_images_giving_zero():
- with patch.object(pp.delayed_requester, "get_response_json", return_value=None):
- img_count = pp._get_total_images()
- assert img_count == 0
-
-
-def test_get_total_images_correct():
- r = get_json("total_images_example.json")
- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):
- img_count = pp._get_total_images()
- assert img_count == 10
-
-
-invalid_endpoint = partial(pytest.param, marks=pytest.mark.raises(exception=ValueError))
+def ingester() -> PhylopicDataIngester:
+ _pp = PhylopicDataIngester()
+ offset = _pp.offset
+ batch_limit = _pp.batch_limit
+ yield _pp
+ _pp.offset = offset
+ _pp.batch_limit = batch_limit
@pytest.mark.parametrize(
- "data, expected",
+ "offset, limit, non_dated_endpoint",
+ [
+ # Basic limit/offset changes
+ (0, 25, "http://phylopic.org/api/a/image/list/0/25"),
+ (0, 30, "http://phylopic.org/api/a/image/list/0/30"),
+ (60, 30, "http://phylopic.org/api/a/image/list/60/30"),
+ ],
+)
+ "date, dated_endpoint",
[
- # Happy paths
+ # Defer to non-dated case
+ (None, None),
+ # Dated DAG produces specific endpoint irrespective of everything else
(
- {"date_start": "2020-02-10", "date_end": "2020-02-11"},
- "http://phylopic.org/api/a/image/list/modified/2020-02-10/2020-02-11",
+ "2022-01-01",
+ "http://phylopic.org/api/a/image/list/modified/2022-01-01/2022-01-02",
),
- ({"offset": 0}, "http://phylopic.org/api/a/image/list/0/5"),
- # Missing/None parameters
- invalid_endpoint({}, None),
- invalid_endpoint({"offset": None}, None),
- invalid_endpoint({"date_start": None}, None),
- invalid_endpoint({"date_start": None, "date_end": None}, None),
- invalid_endpoint({"date_start": "2020-02-10", "date_end": None}, None),
],
)
-def test_create_endpoint_for_IDs(data, expected):
- actual = pp._create_endpoint_for_IDs(**data)
- assert actual == expected
+def test_endpoint(
+ offset,
+ limit,
+ non_dated_endpoint,
+ date,
+ dated_endpoint,
+ ingester,
+):
+ # Defer to dated endpoint if provided
+ expected_endpoint = dated_endpoint or non_dated_endpoint
+ ingester.date = date
+ ingester.offset = offset
+ ingester.batch_limit = limit
+ assert ingester.endpoint == expected_endpoint
+
+
+def test_get_next_query_params(ingester):
+ # Initial call sets offset to 0
+ ingester.batch_limit = 50
+ # Offset after the first call should be 0, then increment by batch limit
+ # each other iteration
+ for expected_offset in [0, 50, 100]:
+ ingester.get_next_query_params({})
+ assert ingester.offset == expected_offset
+
+
[email protected]("dated", [True, False])
+def test_get_should_continue(dated, ingester):
+ ingester.date = dated
+ actual = ingester.get_should_continue({})
+ # Should continue only if we're running as non-dated
+ assert actual == (not dated)
-def test_get_image_IDs_for_no_content():
- with patch.object(pp.delayed_requester, "get_response_json", return_value=None):
- image_ids = pp._get_image_IDs("")
- expect_image_ids = None
- assert image_ids == expect_image_ids
+ "response_json, expected",
+ [
+ # Empty cases
+ (None, None),
+ ({}, None),
+ ({"other": "yes"}, None),
+ # Failure
+ ({"success": False}, None),
+ # Success, but no results
+ ({"success": True}, None),
+ # Success with results
+ ({"success": True, "result": 123}, 123),
+ ],
+)
+def test_get_response_data(response_json, expected):
+ actual = pp._get_response_data(response_json)
+ assert actual == expected
-def test_get_img_IDs_correct():
+def test_get_batch_data():
r = get_json("image_ids_example.json")
- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):
- actual_img_ids = pp._get_image_IDs("")
- expect_img_ids = [
- "863694ac-9f36-40f5-9452-1b435337d9cc",
- "329ff574-4bec-4f94-9dd6-9acfec2a6275",
- "9c98ff56-8044-483e-b9f1-bf368e4f3322",
- ]
- assert actual_img_ids == expect_img_ids
-
-
-def test_get_meta_data_with_no_img_url():
- r = get_json("no_image_url_example.json")
- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):
- meta_data = pp._get_meta_data({})
- assert meta_data is None
-
-
-cc0_license = get_license_info(
- license_url="http://creativecommons.org/publicdomain/zero/1.0/"
-)
+ actual_img_ids = [data.get("uid") for data in pp.get_batch_data(r)]
+ expect_img_ids = [
+ "863694ac-9f36-40f5-9452-1b435337d9cc",
+ "329ff574-4bec-4f94-9dd6-9acfec2a6275",
+ "9c98ff56-8044-483e-b9f1-bf368e4f3322",
+ ]
+ assert actual_img_ids == expect_img_ids
def test_get_creator_details(image_data):
- with patch.object(
- pp.delayed_requester, "get_response_json", return_value=image_data
- ):
- result = image_data["result"]
- actual_creator_details = pp._get_creator_details(result)
- expect_creator_details = (
- "Jonathan Wells",
- "Jonathan Wells",
- "2020-02-26 11:59:53",
- )
- assert actual_creator_details == expect_creator_details
+ result = image_data["result"]
+ actual_creator_details = pp._get_creator_details(result)
+ expect_creator_details = (
+ "Jonathan Wells",
+ "Jonathan Wells",
+ "2020-02-26 11:59:53",
+ )
+ assert actual_creator_details == expect_creator_details
def test_get_taxa_details(image_data):
- with patch.object(
- pp.delayed_requester, "get_response_json", return_value=image_data
- ):
- result = image_data["result"]
- actual_taxa = pp._get_taxa_details(result)
- expect_taxa = (
- ["Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"],
- "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996",
- )
- assert actual_taxa == expect_taxa
+ result = image_data["result"]
+ actual_taxa = pp._get_taxa_details(result)
+ expect_taxa = (
+ ["Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"],
+ "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996",
+ )
+ assert actual_taxa == expect_taxa
-def test_get_image_info(image_data):
- with patch.object(
- pp.delayed_requester, "get_response_json", return_value=image_data
- ):
- result = image_data["result"]
- actual_img_info = pp._get_image_info(
- result, "e9df48fe-68ea-419e-b9df-441e0b208335"
- )
- expect_img_info = (
- (
- "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-"
- "419e-b9df-441e0b208335.1024.png"
- ),
- 847,
- 1024,
- )
- assert actual_img_info == expect_img_info
-
-
-def test_process_item(image_data):
+def test_get_record_data(image_data):
image_uuid = "e9df48fe-68ea-419e-b9df-441e0b208335"
- with patch.object(pp.image_store, "save_item") as mock_save:
- item_data = image_data["result"]
- pp._process_item(item_data)
- actual_image = mock_save.call_args[0][0]
- expected_image = {
+ expected = {
"foreign_identifier": image_uuid,
"foreign_landing_url": f"http://phylopic.org/image/{image_uuid}",
- "url": "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-419e-b9df-441e0b208335.1024.png",
"width": 847,
"height": 1024,
- "filetype": "png",
"creator": "Jonathan Wells",
- "license_": "cc0",
- "license_version": "1.0",
"title": "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996",
+ "image_url": "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-419e-b9df-441e0b208335.1024.png",
+ "license_info": LicenseInfo(
+ license="cc0",
+ version="1.0",
+ url="https://creativecommons.org/publicdomain/zero/1.0/",
+ raw_url="http://creativecommons.org/publicdomain/zero/1.0/",
+ ),
"meta_data": {
"taxa": [
"Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"
],
"credit_line": "Jonathan Wells",
"pub_date": "2020-02-26 11:59:53",
- "license_url": "https://creativecommons.org/publicdomain/zero/1.0/",
- "raw_license_url": "http://creativecommons.org/publicdomain/zero/1.0/",
},
}
- for key, value in expected_image.items():
- assert getattr(actual_image, key) == value
+ with patch.object(pp, "get_response_json", return_value=image_data):
+ actual = pp.get_record_data({"uid": image_uuid})
+ assert actual == expected
-def test_get_image_info_with_no_img_url():
+def test_get_record_data_no_data():
+ actual = pp.get_record_data({})
+ assert actual is None
+
+
+def test_get_record_data_with_no_img_url():
r = get_json("no_image_url_example.json")
- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):
- result = r["result"]
- actual_img_info = list(
- pp._get_image_info(result, "7f7431c6-8f78-498b-92e2-ebf8882a8923")
- )
- expect_img_info = [None, None, None]
- assert actual_img_info == expect_img_info
+ with patch.object(pp, "get_response_json", return_value=r):
+ actual = pp.get_record_data({"uid": r["result"]["uid"]})
+ assert actual is None
- "date_start, days, expected",
- [
- ("2022-01-10", 10, "2022-01-20"),
- ("2022-02-28", 7, "2022-03-07"),
- ("2022-02-28", -7, "2022-02-21"),
- ],
-)
-def test_compute_date_range(date_start, days, expected):
- actual = pp._compute_date_range(date_start, days)
- assert actual == expected
+def test_get_image_info(image_data):
+ result = image_data["result"]
+ actual_img_info = pp._get_image_info(result, "e9df48fe-68ea-419e-b9df-441e0b208335")
+ expect_img_info = (
+ (
+ "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-"
+ "419e-b9df-441e0b208335.1024.png"
+ ),
+ 847,
+ 1024,
+ )
+ assert actual_img_info == expect_img_info
+
+
+def test_get_image_info_with_no_img_url():
+ r = get_json("no_image_url_example.json")
+ result = r["result"]
+ actual_img_info = list(
+ pp._get_image_info(result, "7f7431c6-8f78-498b-92e2-ebf8882a8923")
+ )
+ expect_img_info = [None, None, None]
+ assert actual_img_info == expect_img_info