Skip to content

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

Fix advanced provider options for dags that override ingest records (#4214)

Staci Mullins7f4fb7c91363
diff --git a/catalog/dags/providers/provider_api_scripts/auckland_museum.py b/catalog/dags/providers/provider_api_scripts/auckland_museum.py
index 519212a2d..d4dd1ae99 100644
--- a/catalog/dags/providers/provider_api_scripts/auckland_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/auckland_museum.py
@@ -70,7 +70,7 @@ class AucklandMuseumDataIngester(ProviderDataIngester):
}
}
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
# Return default query params on the first request
# primaryRepresentation contain a image url for each data
# "+" is a query string syntax for must be present
diff --git a/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py b/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
index e1e6e2804..3a5260f13 100644
--- a/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/brooklyn_museum.py
@@ -21,7 +21,7 @@ class BrooklynMuseumDataIngester(ProviderDataIngester):
self.api_key = Variable.get("API_KEY_BROOKLYN_MUSEUM")
self.headers = {"api_key": self.api_key}
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return {
"has_images": 1,
diff --git a/catalog/dags/providers/provider_api_scripts/cc_mixter.py b/catalog/dags/providers/provider_api_scripts/cc_mixter.py
index 6f345b57e..e27d3a4c6 100644
--- a/catalog/dags/providers/provider_api_scripts/cc_mixter.py
+++ b/catalog/dags/providers/provider_api_scripts/cc_mixter.py
@@ -112,7 +112,7 @@ class CcMixterDataIngester(ProviderDataIngester):
delay=self.delay, headers=self.headers
)
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
# This means this is the first request, so we start with offset 0.
return {
diff --git a/catalog/dags/providers/provider_api_scripts/cleveland_museum.py b/catalog/dags/providers/provider_api_scripts/cleveland_museum.py
index b63ab4e8d..f1145fc96 100644
--- a/catalog/dags/providers/provider_api_scripts/cleveland_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/cleveland_museum.py
@@ -16,7 +16,7 @@ class ClevelandDataIngester(ProviderDataIngester):
batch_limit = 1000
delay = 5
- def get_next_query_params(self, prev_query_params, **kwargs):
+ def get_next_query_params(self, prev_query_params: dict | None):
if not prev_query_params:
# Return default query params on the first request
return {"cc": "1", "has_image": "1", "limit": self.batch_limit, "skip": 0}
diff --git a/catalog/dags/providers/provider_api_scripts/europeana.py b/catalog/dags/providers/provider_api_scripts/europeana.py
index e3da34c7e..5cc2030dc 100644
--- a/catalog/dags/providers/provider_api_scripts/europeana.py
+++ b/catalog/dags/providers/provider_api_scripts/europeana.py
@@ -231,7 +231,7 @@ class EuropeanaDataIngester(ProviderDataIngester):
return f"timestamp_update:[{start_timestamp} TO {end_timestamp}]"
- def get_next_query_params(self, prev_query_params) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return self.base_request_body
diff --git a/catalog/dags/providers/provider_api_scripts/finnish_museums.py b/catalog/dags/providers/provider_api_scripts/finnish_museums.py
index 43d769ebc..1103a32af 100644
--- a/catalog/dags/providers/provider_api_scripts/finnish_museums.py
+++ b/catalog/dags/providers/provider_api_scripts/finnish_museums.py
@@ -16,8 +16,11 @@ Notes: <https://api.finna.fi/swagger-ui/>
"""
import logging
+from datetime import datetime
from itertools import chain
+from airflow.exceptions import AirflowSkipException
+
from common.licenses import LicenseInfo, get_license_info
from common.loader import provider_details as prov
from providers.provider_api_scripts.time_delineated_provider_data_ingester import (
@@ -54,23 +57,79 @@ class FinnishMuseumsDataIngester(TimeDelineatedProviderDataIngester):
min_divisions = 12
max_divisions = 20
- def ingest_records(self, **kwargs):
- for building in self.buildings:
- logger.info(f"Obtaining images of building {building}")
- super().ingest_records(building=building)
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # The Finnish Museums API expected double quotes in the params (for
+ # example, 'format:"0/Image"'). Since query params supplied through the
+ # DagRun conf advanced options must be supplied as valid json with outer
+ # double quotes, these inner quotes must be escaped in the form
+ # (i.e., "format:\"0/Image\""). For convenience and to prevent the DAG
+ # from breaking if the user inputs single quotes, they are replaced here.
+ self.initial_query_params = self._replace_single_quotes_in_params(
+ self.initial_query_params
+ )
- def get_next_query_params(self, prev_query_params, **kwargs):
- if not prev_query_params:
- building = kwargs.get("building")
- start_ts = self.format_ts(kwargs.get("start_ts"))
- end_ts = self.format_ts(kwargs.get("end_ts"))
+ if self.override_query_params_list:
+ self.override_query_params = (
+ self._replace_single_quotes_in_params(qp)
+ for qp in self.override_query_params_list
+ )
+ def _replace_single_quotes_in_params(self, params: dict | None):
+ """Ensure that the values in the "filter[]" param do not contain single quotes."""
+ if not params:
+ return None
+
+ return {
+ **params,
+ "filter[]": [
+ param.replace("'", '"') for param in params.get("filter[]", [])
+ ],
+ }
+
+ def get_fixed_query_params(self):
+ """
+ Get the set of fixed params. Ingestion will be run separately for each of
+ these.
+ """
+ fixed_query_params = []
+
+ # Build out timestamp pairs for each building.
+ for building in self.buildings:
+ logger.info(f"Generating timestamp pairs for {building}.")
+ timestamp_pairs = super()._get_timestamp_pairs(building=building)
+ fixed_query_params += [
+ self.get_timestamp_query_params(start, end, building=building)
+ for start, end in timestamp_pairs
+ ]
+
+ # If no fixed_query_params were generated (which happens when there are no
+ # records for this ingestion date for any of the buildings), then skip
+ if not fixed_query_params:
+ raise AirflowSkipException("No data to ingest.")
+
+ return fixed_query_params
+
+ def get_timestamp_query_params(
+ self, start: datetime, end: datetime, **kwargs
+ ) -> dict:
+ """Format the timestamp params appropriately."""
+ building = kwargs.get("building")
+ return {
+ "filter[]": [
+ f'format:"{self.format_type}"',
+ f'building:"{building}"',
+ f'last_indexed:"[{self.format_ts(start)} TO {self.format_ts(end)}]"',
+ ]
+ }
+
+ def get_next_query_params(self, prev_query_params: dict | None):
+ """
+ Get the next query params, based on the previous ones. Fixed query params
+ will be merged in by the base class as appropriate.
+ """
+ if not prev_query_params:
return {
- "filter[]": [
- f'format:"{self.format_type}"',
- f'building:"{building}"',
- f'last_indexed:"[{start_ts} TO {end_ts}]"',
- ],
"field[]": [
"authors",
"buildings",
diff --git a/catalog/dags/providers/provider_api_scripts/flickr.py b/catalog/dags/providers/provider_api_scripts/flickr.py
index 9ad2a5fa6..ea14cafcf 100644
--- a/catalog/dags/providers/provider_api_scripts/flickr.py
+++ b/catalog/dags/providers/provider_api_scripts/flickr.py
@@ -85,6 +85,9 @@ class FlickrDataIngester(TimeDelineatedProviderDataIngester):
# during different stages of the ingestion process.
self.process_large_batch = False
+ # Keep track of the current timestamp pair being processed.
+ self.current_timestamp_pair = ()
+
def ingest_records(self, **kwargs):
"""
Ingest records, handling large batches.
@@ -105,7 +108,7 @@ class FlickrDataIngester(TimeDelineatedProviderDataIngester):
all the unique records over this time period. We will process up to the
max_unique_records count and then move on to the next batch.
"""
- # Perform ingestion as normal, splitting requests into time-slices of at most
+ # Perform full ingestion as normal, splitting requests into time-slices of at most
# 5 minutes. When a batch is encountered which contains more than
# max_unique_records, it is skipped and added to the `large_batches` list for
# later processing.
@@ -121,8 +124,13 @@ class FlickrDataIngester(TimeDelineatedProviderDataIngester):
# For each large batch, ingest records for that interval one license
# type at a time.
for license_ in LICENSE_INFO.keys():
- super().ingest_records_for_timestamp_pair(
- start_ts=start_ts, end_ts=end_ts, license=license_
+ super()._ingest_records(
+ initial_query_params=None,
+ fixed_query_params={
+ "min_upload_date": start_ts,
+ "max_upload_date": end_ts,
+ "license": license_,
+ },
)
logger.info("Completed large batch processing by license type.")
@@ -131,22 +139,28 @@ class FlickrDataIngester(TimeDelineatedProviderDataIngester):
# additional requests when generating timestamp pairs.
logger.info(f"Made {self.requests_count + 25} requests to the Flickr API.")
- def get_next_query_params(self, prev_query_params, **kwargs):
- if not prev_query_params:
- # Initial request, return default params
- start_timestamp = kwargs.get("start_ts")
- end_timestamp = kwargs.get("end_ts")
+ def _ingest_records(
+ self, initial_query_params: dict | None, fixed_query_params: dict | None
+ ) -> None:
+ # Update `current_timestamp_pair` to keep track of what we are processing.
+ self.current_timestamp_pair = (
+ fixed_query_params["min_upload_date"],
+ fixed_query_params["max_upload_date"],
+ )
+ return super()._ingest_records(initial_query_params, fixed_query_params)
- # license will be available in the params if we're dealing
- # with a large batch. If not, fall back to all licenses
- license_ = kwargs.get("license", self.default_license_param)
+ def get_timestamp_query_params(
+ self, start: datetime, end: datetime, **kwargs
+ ) -> dict:
+ return {"min_upload_date": start, "max_upload_date": end}
+ def get_next_query_params(self, prev_query_params: dict | None):
+ if not prev_query_params:
+ # Initial request, return default params
return {
- "min_upload_date": start_timestamp,
- "max_upload_date": end_timestamp,
"page": 0,
"api_key": self.api_key,
- "license": license_,
+ "license": self.default_license_param,
"per_page": self.batch_limit,
"method": "flickr.photos.search",
"media": "photos",
diff --git a/catalog/dags/providers/provider_api_scripts/freesound.py b/catalog/dags/providers/provider_api_scripts/freesound.py
index 0f04cc053..9a41a2377 100644
--- a/catalog/dags/providers/provider_api_scripts/freesound.py
+++ b/catalog/dags/providers/provider_api_scripts/freesound.py
@@ -53,7 +53,7 @@ class FreesoundDataIngester(ProviderDataIngester):
super().__init__(*args, **kwargs)
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
start_date = "*"
# Allow self.date to be undefined, necessary for the first full, successful
diff --git a/catalog/dags/providers/provider_api_scripts/inaturalist.py b/catalog/dags/providers/provider_api_scripts/inaturalist.py
index f270d00a4..b454ff093 100644
--- a/catalog/dags/providers/provider_api_scripts/inaturalist.py
+++ b/catalog/dags/providers/provider_api_scripts/inaturalist.py
@@ -55,7 +55,7 @@ COL_URL = "https://download.checklistbank.org/col/latest_coldp.zip"
class INaturalistDataIngester(ProviderDataIngester):
providers = {"image": provider_details.INATURALIST_DEFAULT_PROVIDER}
- def get_next_query_params(self, prev_query_params=None, **kwargs):
+ def get_next_query_params(self, prev_query_params=None):
raise NotImplementedError(
"Instead we use get_batches to dynamically create subtasks."
)
diff --git a/catalog/dags/providers/provider_api_scripts/jamendo.py b/catalog/dags/providers/provider_api_scripts/jamendo.py
index 6f351bbea..b55c830eb 100644
--- a/catalog/dags/providers/provider_api_scripts/jamendo.py
+++ b/catalog/dags/providers/provider_api_scripts/jamendo.py
@@ -45,7 +45,7 @@ class JamendoDataIngester(ProviderDataIngester):
batch_limit = 200
headers = {"Accept": "application/json"}
- def get_next_query_params(self, prev_query_params, **kwargs):
+ def get_next_query_params(self, prev_query_params):
if not prev_query_params:
# On first request, build default params.
return {
diff --git a/catalog/dags/providers/provider_api_scripts/justtakeitfree.py b/catalog/dags/providers/provider_api_scripts/justtakeitfree.py
index ce15dd753..12c9f95a9 100644
--- a/catalog/dags/providers/provider_api_scripts/justtakeitfree.py
+++ b/catalog/dags/providers/provider_api_scripts/justtakeitfree.py
@@ -30,7 +30,7 @@ class JusttakeitfreeDataIngester(ProviderDataIngester):
creator = "Justtakeitfree Free Photos"
creator_url = "https://justtakeitfree.com"
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return {"page": 1, "key": Variable.get("API_KEY_JUSTTAKEITFREE")}
else:
diff --git a/catalog/dags/providers/provider_api_scripts/museum_victoria.py b/catalog/dags/providers/provider_api_scripts/museum_victoria.py
index 9b1bf4c47..b19091b64 100644
--- a/catalog/dags/providers/provider_api_scripts/museum_victoria.py
+++ b/catalog/dags/providers/provider_api_scripts/museum_victoria.py
@@ -42,19 +42,17 @@ class VictoriaDataIngester(ProviderDataIngester):
# This set is used to prevent duplicate images of the same items
self.RECORDS_IDS = set()
- def ingest_records(self, **kwargs):
- for license_ in self.LICENSE_LIST:
- super().ingest_records(license_=license_)
-
def get_batch_data(self, response_json):
return response_json or None
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_fixed_query_params(self):
+ return [{"imagelicense": license_} for license_ in self.LICENSE_LIST]
+
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return {
"hasimages": "yes",
"perpage": self.batch_limit,
- "imagelicense": kwargs["license_"],
"page": 0,
}
else:
diff --git a/catalog/dags/providers/provider_api_scripts/nappy.py b/catalog/dags/providers/provider_api_scripts/nappy.py
index d5eaa6a9c..89e06a790 100644
--- a/catalog/dags/providers/provider_api_scripts/nappy.py
+++ b/catalog/dags/providers/provider_api_scripts/nappy.py
@@ -32,7 +32,7 @@ class NappyDataIngester(ProviderDataIngester):
"https://creativecommons.org/publicdomain/zero/1.0/"
)
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return {
"page": 1,
diff --git a/catalog/dags/providers/provider_api_scripts/nypl.py b/catalog/dags/providers/provider_api_scripts/nypl.py
index 3dd4196ec..2dcdd9e12 100644
--- a/catalog/dags/providers/provider_api_scripts/nypl.py
+++ b/catalog/dags/providers/provider_api_scripts/nypl.py
@@ -58,7 +58,7 @@ class NyplDataIngester(ProviderDataIngester):
NyplDataIngester.headers = {"Authorization": f"Token token={NYPL_API}"}
super().__init__(*args, **kwargs)
- def get_next_query_params(self, prev_query_params, **kwargs):
+ def get_next_query_params(self, prev_query_params):
if not prev_query_params:
return {
"q": "CC_0",
diff --git a/catalog/dags/providers/provider_api_scripts/phylopic.py b/catalog/dags/providers/provider_api_scripts/phylopic.py
index cf031034a..05571bebc 100644
--- a/catalog/dags/providers/provider_api_scripts/phylopic.py
+++ b/catalog/dags/providers/provider_api_scripts/phylopic.py
@@ -79,7 +79,7 @@ class PhylopicDataIngester(ProviderDataIngester):
f"Total pages: {self.total_pages}."
)
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if prev_query_params is not None:
self.current_page += 1
diff --git a/catalog/dags/providers/provider_api_scripts/provider_data_ingester.py b/catalog/dags/providers/provider_api_scripts/provider_data_ingester.py
index 982dc4bc9..13c9703bb 100644
--- a/catalog/dags/providers/provider_api_scripts/provider_data_ingester.py
+++ b/catalog/dags/providers/provider_api_scripts/provider_data_ingester.py
@@ -173,11 +173,12 @@ class ProviderDataIngester(ABC):
# An optional list of `query_params`. When provided, ingestion will be run for
# just these sets of params.
self.override_query_params = None
- if query_params_list := conf.get("query_params_list"):
+ self.override_query_params_list = conf.get("query_params_list")
+ if self.override_query_params_list:
# Create a generator to facilitate fetching the next set of query_params.
- self.override_query_params = (qp for qp in query_params_list)
+ self.override_query_params = (qp for qp in self.override_query_params_list)
- # An optional set of query params to add to each query
+ # An optional set of query params to add to all queries
self.additional_query_params = conf.get("additional_query_params", {})
# A configuration option that is used to skip over ALL errors and continue
@@ -207,17 +208,31 @@ class ProviderDataIngester(ABC):
return media_stores
- def ingest_records(self, **kwargs) -> None:
+ def _ingest_records(
+ self, initial_query_params: dict | None, fixed_query_params: dict | None
+ ) -> None:
"""
- Ingest all records.
+ Perform ingestion.
- This is the main ingestion function that is called during the `pull_data` task.
+ Required Arguments:
Optional Arguments:
- **kwargs: Optional arguments to be passed to `get_next_query_params`.
+ initial_query_params: Optional override for the query params to be used in the
+ first batch.
+ fixed_query_params: Optional, fixed query params which should be passed to
+ `get_next_query_params`. These should not change during this
+ round of ingestion.
"""
should_continue = True
- query_params = None
+ # Use initial_query_params if provided, or get the next set of params.
+ query_params = initial_query_params or self._get_query_params(
+ None, fixed_query_params
+ )
+ if initial_query_params:
+ logger.info(
+ "Using initial_query_params from dag_run conf:"
+ f" {json.dumps(self.initial_query_params)}"
+ )
# If an ingestion limit has been set and we have already ingested records
# in excess of the limit, exit early. This may happen if `ingest_records`
@@ -228,7 +243,6 @@ class ProviderDataIngester(ABC):
logger.info(f"Begin ingestion for {self.__class__.__name__}")
while should_continue:
- query_params = self._get_query_params(query_params, **kwargs)
if query_params is None:
# Break out of ingestion if no query_params are supplied. This can
# happen when the final `override_query_params` is processed.
@@ -268,6 +282,11 @@ class ProviderDataIngester(ABC):
# Add this to the errors list but continue processing
self.ingestion_errors.append(ingestion_error)
logger.error(f"Skipping batch due to ingestion error: {error}")
+
+ # Continue from the next batch
+ query_params = self._get_query_params(
+ query_params, fixed_query_params
+ )
continue
# Commit whatever records we were able to process, and rethrow the
@@ -279,10 +298,62 @@ class ProviderDataIngester(ABC):
logger.info(f"Ingestion limit of {self.limit} has been reached.")
should_continue = False
+ # Get next query params
+ query_params = self._get_query_params(query_params, fixed_query_params)
+
# Commit whatever records we were able to process
self._commit_records()
- # If errors were caught during processing, raise them now
+ def ingest_records(self) -> None:
+ """
+ Ingest all records.
+
+ If fixed_query_params are provided, ingestion will be performed separately
+ for each set of fixed_query_params.
+
+ This is the main ingestion function that is called during the `pull_data` task.
+ """
+ if not (fixed_query_params := self.get_fixed_query_params()):
+ # If no fixed params were provided, simply begin ingestion
+ self._ingest_records(self.initial_query_params, {})
+ else:
+ # Else, ingestion should be run separately for each set of fixed_query_params.
+ logger.info(
+ "Ingestion will be performed for each of the following sets of"
+ f" fixed query parameters: {fixed_query_params}"
+ )
+
+ # If initial_query_params were also provided, we should begin ingestion
+ # from the first set of fixed_query_params that is included in the
+ # initial_query_params
+ if self.initial_query_params:
+ initial_fixed_params = next(
+ (
+ qp
+ for qp in fixed_query_params
+ if qp.items() <= self.initial_query_params.items()
+ ),
+ fixed_query_params[0],
+ )
+
+ logger.info(
+ f"==Starting ingestion with fixed params: {initial_fixed_params}=="
+ )
+
+ # Run ingestion on the first batch, passing in the initial_query_params
+ self._ingest_records(self.initial_query_params, initial_fixed_params)
+
+ # Resume from the _next_ set of fixed_query_params
+ fixed_query_params = fixed_query_params[
+ fixed_query_params.index(initial_fixed_params) + 1 :
+ ]
+
+ for fixed_params in fixed_query_params:
+ logger.info(f"==Starting ingestion with fixed params: {fixed_params}==")
+ # Subsequent batches should not start at the initial_query_params
+ self._ingest_records(None, fixed_params)
+
+ # Finally, raise any errors that were skipped at any point during processing.
if error_summary := self._get_ingestion_errors():
raise error_summary
@@ -330,7 +401,7 @@ class ProviderDataIngester(ABC):
return None
def _get_query_params(
- self, prev_query_params: dict | None, **kwargs
+ self, prev_query_params: dict | None, fixed_query_params: dict | None = None
) -> dict | None:
"""
Return the next set of query_params for the next request.
@@ -338,15 +409,6 @@ class ProviderDataIngester(ABC):
This handles optional overrides via the dag_run conf.
This method should not be overridden; instead override get_next_query_params.
"""
- # If we are getting query_params for the first batch and initial_query_params
- # have been set, return them.
- if prev_query_params is None and self.initial_query_params:
- logger.info(
- "Using initial_query_params from dag_run conf:"
- f" {json.dumps(self.initial_query_params)}"
- )
- return self.initial_query_params
-
# If a list of query_params was provided, return the next value.
if self.override_query_params:
next_params = next(self.override_query_params, None)
@@ -356,13 +418,27 @@ class ProviderDataIngester(ABC):
)
return next_params
- # Default behavior; build the next set of query params, given the previous,
- # along with any extra params if additional_query_params were provided
- next_query_params = self.get_next_query_params(prev_query_params, **kwargs)
- return next_query_params | self.additional_query_params
+ # Default behavior: build the next set of query params, given the previous.
+ # The final set of query params returned merges:
+ # * the `next_query_params` calculated based on the previous params
+ # * any `fixed_query_params`, which are fixed params that do not change
+ # depending on the previous params, and are applied to all batches in this
+ # round of ingestion
+ # * any `additional_query_params`, which are provided via the DagRun conf
+ # and applied to all batches, in every round of ingestion
+ next_query_params = self.get_next_query_params(prev_query_params)
+ fixed_query_params = fixed_query_params or {}
+ return next_query_params | fixed_query_params | self.additional_query_params
+
+ def get_fixed_query_params(self) -> list[dict] | None:
+ """
+ Return a list of fixed query params, for each of which ingestion will be
+ performed.
+ """
+ return []
@abstractmethod
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
"""
Get the next set of query parameters.
@@ -373,7 +449,6 @@ class ProviderDataIngester(ABC):
Required arguments:
prev_query_params: dictionary of query string params used in the previous
request. If None, this is the first request.
- **kwargs: Optional kwargs passed through from `ingest_records`.
"""
pass
diff --git a/catalog/dags/providers/provider_api_scripts/rawpixel.py b/catalog/dags/providers/provider_api_scripts/rawpixel.py
index 9931a07b3..aaa881e3e 100644
--- a/catalog/dags/providers/provider_api_scripts/rawpixel.py
+++ b/catalog/dags/providers/provider_api_scripts/rawpixel.py
@@ -120,7 +120,7 @@ class RawpixelDataIngester(ProviderDataIngester):
# Convert back to a string
return signature.decode("utf-8")
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
params = {
"tags": "$publicdomain",
diff --git a/catalog/dags/providers/provider_api_scripts/science_museum.py b/catalog/dags/providers/provider_api_scripts/science_museum.py
index 36da85c7c..221322c98 100644
--- a/catalog/dags/providers/provider_api_scripts/science_museum.py
+++ b/catalog/dags/providers/provider_api_scripts/science_museum.py
@@ -74,28 +74,29 @@ class ScienceMuseumDataIngester(ProviderDataIngester):
)
return year_ranges
- def ingest_records(self, **kwargs):
+ def get_fixed_query_params(self):
+ """
+ Provide a set of year ranges. Ingestion will be performed for each range,
+ with the dates set as fixed query params.
+ """
next_year = date.today().year + 1
- for year_range in self._get_year_ranges(next_year):
- logger.info(f"==Starting on year range: {year_range}==")
- super().ingest_records(year_range=year_range)
+ year_ranges = self._get_year_ranges(next_year)
+
+ return [{"date[from]": from_, "date[to]": to_} for from_, to_ in year_ranges]
- def get_next_query_params(self, prev_query_params, **kwargs):
- from_, to_ = kwargs["year_range"]
+ def get_next_query_params(self, prev_query_params):
if not prev_query_params:
# Reset the page number to 0
self.page_number = 0
else:
# Increment the page number
- self.page_number += 1
+ self.page_number = prev_query_params["page[number]"] + 1
return {
"has_image": 1,
"image_license": "CC",
"page[size]": LIMIT,
"page[number]": self.page_number,
- "date[from]": from_,
- "date[to]": to_,
}
def get_batch_data(self, response_json):
diff --git a/catalog/dags/providers/provider_api_scripts/smithsonian.py b/catalog/dags/providers/provider_api_scripts/smithsonian.py
index b1bfe4241..e881dac2b 100644
--- a/catalog/dags/providers/provider_api_scripts/smithsonian.py
+++ b/catalog/dags/providers/provider_api_scripts/smithsonian.py
@@ -114,17 +114,20 @@ class SmithsonianDataIngester(ProviderDataIngester):
license_url="https://creativecommons.org/publicdomain/zero/1.0/"
)
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_fixed_query_params(self):
+ base_query_string = "online_media_type:Images AND media_usage:CC0"
+ return [
+ {"q": base_query_string + f" AND hash:{hash_prefix}*"}
+ for hash_prefix in self._get_hash_prefixes()
+ ]
+
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
# On the first request, `prev_query_params` will be `None`. We can detect this
# and return our default params.
- query_string = "online_media_type:Images AND media_usage:CC0"
- if hash_prefix := kwargs.get("hash_prefix"):
- query_string += f" AND hash:{hash_prefix}*"
if not prev_query_params:
return {
"api_key": self.api_key,
- "q": query_string,
"rows": self.batch_limit,
"start": 0,
}
@@ -407,11 +410,10 @@ class SmithsonianDataIngester(ProviderDataIngester):
)
return [tag for tag_list in tag_lists_generator for tag in tag_list if tag]
- def ingest_records(self, **kwargs) -> None:
+ def ingest_records(self) -> None:
+ # Validate unit codes before ingestion
self.validate_unit_codes_from_api()
- for hash_prefix in self._get_hash_prefixes():
- logger.debug(f"Getting records for hash prefix {hash_prefix}")
- super().ingest_records(hash_prefix=hash_prefix)
+ super().ingest_records()
def main():
diff --git a/catalog/dags/providers/provider_api_scripts/smk.py b/catalog/dags/providers/provider_api_scripts/smk.py
index 18b81c807..929c88687 100644
--- a/catalog/dags/providers/provider_api_scripts/smk.py
+++ b/catalog/dags/providers/provider_api_scripts/smk.py
@@ -26,7 +26,7 @@ class SmkDataIngester(ProviderDataIngester):
headers = {"Accept": "application/json"}
providers = {"image": prov.SMK_DEFAULT_PROVIDER}
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if not prev_query_params:
return {
"keys": "*",
diff --git a/catalog/dags/providers/provider_api_scripts/stocksnap.py b/catalog/dags/providers/provider_api_scripts/stocksnap.py
index 7b0858cfd..a5d5f4156 100644
--- a/catalog/dags/providers/provider_api_scripts/stocksnap.py
+++ b/catalog/dags/providers/provider_api_scripts/stocksnap.py
@@ -40,15 +40,15 @@ class StockSnapDataIngester(ProviderDataIngester):
super().__init__(*args, **kwargs)
self._page_counter = 1
- def get_next_query_params(self, prev_query_params, **kwargs):
+ def get_next_query_params(self, prev_query_params: dict | None):
if prev_query_params:
return {"page": prev_query_params["page"] + 1}
return {"page": 1}
def _get_query_params(
- self, prev_query_params: dict | None, **kwargs
+ self, prev_query_params: dict | None, fixed_query_params: dict | None = None
) -> dict | None:
- query_params = super()._get_query_params(prev_query_params, **kwargs)
+ query_params = super()._get_query_params(prev_query_params, fixed_query_params)
if query_params:
# Record the page that we are currently on so that it can be used as part of
# the endpoint URL.
diff --git a/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py b/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
index 38f08fe9d..1cf508e0e 100644
--- a/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
+++ b/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
@@ -62,9 +62,6 @@ class TimeDelineatedProviderDataIngester(ProviderDataIngester):
# Keep track of our ts pairs
self.timestamp_pairs = []
- # Keep track of the current ts pair
- self.current_timestamp_pair = ()
-
@staticmethod
def format_ts(timestamp):
return timestamp.isoformat().replace("+00:00", "Z")
@@ -109,9 +106,11 @@ class TimeDelineatedProviderDataIngester(ProviderDataIngester):
def _get_record_count(self, start: datetime, end: datetime, **kwargs) -> int:
"""Get the number of records returned by the API for a particular interval."""
- query_params = self.get_next_query_params(
- prev_query_params=None, start_ts=start, end_ts=end, **kwargs
+ query_params = self._get_query_params(
+ prev_query_params=None,
+ fixed_query_params=self.get_timestamp_query_params(start, end, **kwargs),
)
+
response_json = self.get_response_json(query_params)
return self.get_record_count_from_response(response_json)
@@ -195,28 +194,39 @@ class TimeDelineatedProviderDataIngester(ProviderDataIngester):
return pairs_list
- def ingest_records(self, **kwargs) -> None:
- self.timestamp_pairs = self._get_timestamp_pairs(**kwargs)
- if self.timestamp_pairs:
- logger.info(f"{len(self.timestamp_pairs)} timestamp pairs generated.")
+ @abstractmethod
+ def get_timestamp_query_params(
+ self, start: datetime, end: datetime, **kwargs
+ ) -> dict:
+ """
+ Given the start and end timestamps, return them in the appropriate shape
+ for query params for this ingester to be consumed by the API.
+ """
+ pass
- # Run ingestion for each timestamp pair
- for start_ts, end_ts in self.timestamp_pairs:
- self.ingest_records_for_timestamp_pair(start_ts, end_ts, **kwargs)
+ def get_fixed_query_params(self):
+ self.timestamp_pairs = self._get_timestamp_pairs()
- def ingest_records_for_timestamp_pair(
- self, start_ts: datetime, end_ts: datetime, **kwargs
- ):
- # Update `current_timestamp_pair` to keep track of what we are processing.
- self.current_timestamp_pair = (start_ts, end_ts)
+ if self.timestamp_pairs:
+ logger.info(f"{len(self.timestamp_pairs)} timestamp pairs generated.")
+ # Run ingestion for each timestamp pair.
+ return [
+ self.get_timestamp_query_params(start_ts, end_ts)
+ for start_ts, end_ts in self.timestamp_pairs
+ ]
+ def _ingest_records(
+ self, initial_query_params: dict | None, fixed_query_params: dict | None
+ ) -> None:
+ """
+ Override _ingest_records, which is called for each set of timestamp pairs,
+ to reset the counts before each round.
+ """
# Reset counts
self.new_iteration = True
self.fetched_count = 0
- # Run ingestion for the given parameters
- logger.info(f"Ingesting data for start: {start_ts}, end: {end_ts}")
- super().ingest_records(start_ts=start_ts, end_ts=end_ts, **kwargs)
+ super()._ingest_records(initial_query_params, fixed_query_params)
def get_should_continue(self, response_json) -> bool:
"""
diff --git a/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py b/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
index c30e1a5a9..32aa10274 100644
--- a/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
+++ b/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
@@ -183,7 +183,7 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
self.current_props = self.default_props.copy()
self.popularity_cache: dict[str, int] = {}
- def get_next_query_params(self, prev_query_params, **kwargs):
+ def get_next_query_params(self, prev_query_params: dict | None):
# NOTE: If more sub-properties are added here, an additional contingency for
# iterating over that property's "continue" token will need to be added
# to the `adjust_parameters_for_next_iteration` function, otherwise the
diff --git a/catalog/dags/providers/provider_api_scripts/wordpress.py b/catalog/dags/providers/provider_api_scripts/wordpress.py
index 5d001a68d..a275a89a3 100644
--- a/catalog/dags/providers/provider_api_scripts/wordpress.py
+++ b/catalog/dags/providers/provider_api_scripts/wordpress.py
@@ -53,7 +53,7 @@ class WordPressDataIngester(ProviderDataIngester):
self.total_pages = None
self.current_page = 1
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
if self.total_pages is None:
# On the first request, make a HEAD request to get the number of pages of
# results, so we know when to halt ingestion. This prevents errors
diff --git a/catalog/templates/template_provider.py_template b/catalog/templates/template_provider.py_template
index a445b5dde..25a16204d 100644
--- a/catalog/templates/template_provider.py_template
+++ b/catalog/templates/template_provider.py_template
@@ -43,7 +43,7 @@ class {provider}DataIngester(ProviderDataIngester):
batch_limit = 100
headers = {}
- def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, prev_query_params: dict | None) -> dict:
# On the first request, `prev_query_params` will be `None`. We can detect this
# and return our default params.
if not prev_query_params:
diff --git a/catalog/tests/dags/common/test_resources/fake_provider_data_ingester.py b/catalog/tests/dags/common/test_resources/fake_provider_data_ingester.py
index 4b28f687b..0bdeeae38 100644
--- a/catalog/tests/dags/common/test_resources/fake_provider_data_ingester.py
+++ b/catalog/tests/dags/common/test_resources/fake_provider_data_ingester.py
@@ -15,7 +15,7 @@ class FakeDataIngester(ProviderDataIngester):
def endpoint(self):
return ""
- def get_next_query_params(self, old_query_params: dict | None, **kwargs) -> dict:
+ def get_next_query_params(self, old_query_params: dict | None) -> dict:
return old_query_params
def get_batch_data(self, response_json):
diff --git a/catalog/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py b/catalog/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
index e254cd946..c9fd76bfe 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
@@ -36,8 +36,10 @@ class MockProviderDataIngesterMixin:
providers = {"audio": AUDIO_PROVIDER, "image": IMAGE_PROVIDER}
endpoint = ENDPOINT
- def get_next_query_params(self, prev_query_params, **kwargs):
- return DEFAULT_QUERY_PARAMS
+ def get_next_query_params(self, prev_query_params):
+ if prev_query_params is None:
+ return DEFAULT_QUERY_PARAMS
+ return {**prev_query_params, "page": prev_query_params["page"] + 1}
def get_batch_data(self, response_json):
if response_json:
@@ -90,18 +92,17 @@ class MockTimeDelineatedProviderDataIngester(
min_divisions = MIN_DIVISIONS
max_divisions = MAX_DIVISIONS
- def get_next_query_params(self, prev_query_params, **kwargs):
- return {
- **DEFAULT_QUERY_PARAMS,
- "start_ts": kwargs.get("start_ts"),
- "end_ts": kwargs.get("end_ts"),
- }
+ def get_next_query_params(self, prev_query_params):
+ return DEFAULT_QUERY_PARAMS
def get_record_count_from_response(self, response_json):
if response_json:
return response_json.get("count")
return 0
+ def get_timestamp_query_params(self, start, end, **kwargs):
+ return {"start_ts": start, "end_ts": end}
+
# Expected result of calling `get_batch_data` with `response_success.json`
EXPECTED_BATCH_DATA = [
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py b/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
index 72b27d9a0..b4d7c097f 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
@@ -47,19 +47,25 @@ def test_get_record_count(response_json, expected_count):
assert actual_count == expected_count
-def test_build_query_param_default():
- actual_param_made = fm.get_next_query_params(
- None,
+def test_get_timestamp_query_params():
+ actual_fixed_params = fm.get_timestamp_query_params(
+ start=FROZEN_UTC_DATE,
+ end=FROZEN_UTC_DATE + timedelta(days=1),
building="0/Museovirasto/",
- start_ts=FROZEN_UTC_DATE,
- end_ts=FROZEN_UTC_DATE + timedelta(days=1),
)
- expected_param = {
+ expected_fixed_params = {
"filter[]": [
'format:"0/Image/"',
'building:"0/Museovirasto/"',
'last_indexed:"[2020-04-01T00:00:00Z TO 2020-04-02T00:00:00Z]"',
],
+ }
+ assert actual_fixed_params == expected_fixed_params
+
+
+def test_build_query_param_default():
+ actual_param_made = fm.get_next_query_params(None)
+ expected_param = {
"field[]": [
"authors",
"buildings",
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py b/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py
index af7204028..63f6982a0 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py
@@ -25,8 +25,6 @@ _get_resource_json = make_resource_json_func("flickr")
def test_get_next_query_params():
expected_params = {
- "min_upload_date": "1516060900",
- "max_upload_date": "1516060800",
"page": 0,
"api_key": "not_set",
"license": "1,2,3,4,5,6,9,10",
@@ -45,18 +43,25 @@ def test_get_next_query_params():
flickr.api_key = "not_set"
# First request
- first_params = flickr.get_next_query_params(
- None, start_ts="1516060900", end_ts="1516060800"
- )
+ first_params = flickr.get_next_query_params(None)
assert first_params == expected_params
# Updated page on second request
- second_params = flickr.get_next_query_params(
- first_params, start_ts="1516060900", end_ts="1516060800"
- )
+ second_params = flickr.get_next_query_params(first_params)
assert second_params == {**expected_params, "page": 1}
+def test_get_timestamp_query_params():
+ expected_params = {
+ "min_upload_date": "1516060900",
+ "max_upload_date": "1516060800",
+ }
+ actual_params = flickr.get_timestamp_query_params(
+ start="1516060900", end="1516060800"
+ )
+ assert actual_params == expected_params
+
+
def test_get_media_type():
assert flickr.get_media_type({}) == "image"
@@ -369,7 +374,7 @@ def test_ingest_records():
"providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester.ingest_records"
),
mock.patch(
- "providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester.ingest_records_for_timestamp_pair"
+ "providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester._ingest_records"
) as ingest_for_pair_mock,
):
flickr.ingest_records()
@@ -384,7 +389,7 @@ def test_ingest_records_when_large_batches_detected():
"providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester.ingest_records"
),
mock.patch(
- "providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester.ingest_records_for_timestamp_pair"
+ "providers.provider_api_scripts.time_delineated_provider_data_ingester.TimeDelineatedProviderDataIngester._ingest_records"
) as ingest_for_pair_mock,
):
# Set large_batches to include one timestamp pair
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_museum_victoria.py b/catalog/tests/dags/providers/provider_api_scripts/test_museum_victoria.py
index c27708bb0..4f06ecc11 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_museum_victoria.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_museum_victoria.py
@@ -30,17 +30,29 @@ _get_resource_json = make_resource_json_func("museumvictoria")
def test_get_query_param_default():
- actual_param = mv.get_next_query_params(None, **{"license_": mv.LICENSE_LIST[0]})
+ actual_param = mv.get_next_query_params(None)
expected_param = {
"hasimages": "yes",
"perpage": 100,
- "imagelicense": "public domain",
"page": 0,
}
assert actual_param == expected_param
+def test_get_fixed_query_params():
+ actual_param = mv.get_fixed_query_params()
+ expected_param = [
+ {"imagelicense": "public domain"},
+ {"imagelicense": "cc by"},
+ {"imagelicense": "cc by-nc"},
+ {"imagelicense": "cc by-nc-sa"},
+ {"imagelicense": "cc by-nc-nd"},
+ {"imagelicense": "cc by-sa"},
+ ]
+ assert actual_param == expected_param
+
+
def test_get_query_param_offset():
actual_param = mv.get_next_query_params(
{
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py b/catalog/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py
index 65a339f9a..0b9655336 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py
@@ -372,6 +372,49 @@ def test_ingest_records_uses_initial_query_params_from_dagrun_conf():
get_batch_mock.assert_called_with({"has_image": 1, "page": 5})
+def test_ingest_records_starts_from_first_fixed_query_param_in_initial_query_params():
+ """
+ This tests that if a DAG supplies some fixed_query_params, and then
+ initial_query_params are passed in the DagRun conf, that the DAG starts from the
+ first fixed_query_param matching the initial_query_params passed in. E.g., if the
+ DAG's fixed params are [{"fixed_param": 1}, {"fixed_param": 2}, {"fixed_param": 3}]
+ then on a normal run, _ingest_records will be called 3 times, once with each fixed param.
+
+ If the `initial_query_params` are passed in and include {"fixed_param": 2}, then on that
+ DagRun we want _ingest_records to only be called twice (for values 2 and 3 of fixed_param.)
+ """
+ # Initialize the ingester with a conf
+ ingester = MockProviderDataIngester(
+ {"initial_query_params": {"has_image": 1, "page": 5, "fixed_param": 2}}
+ )
+
+ with (
+ patch.object(ingester, "get_batch") as get_batch_mock,
+ patch.object(ingester, "process_batch", return_value=3),
+ patch.object(
+ ingester,
+ "get_fixed_query_params",
+ return_value=[{"fixed_param": 1}, {"fixed_param": 2}, {"fixed_param": 3}],
+ ),
+ ):
+ get_batch_mock.side_effect = [
+ (EXPECTED_BATCH_DATA, True), # First batch of the first round
+ (EXPECTED_BATCH_DATA, False), # Second and final batch of the first round
+ (EXPECTED_BATCH_DATA, False), # First and final batch of the second round
+ ]
+
+ ingester.ingest_records()
+
+ # get_batch was called with the appropriate query_params
+ get_batch_mock.assert_has_calls(
+ [
+ call({"has_image": 1, "page": 5, "fixed_param": 2}),
+ call({"has_image": 1, "page": 6, "fixed_param": 2}),
+ call({"has_image": 1, "page": 1, "fixed_param": 3}),
+ ]
+ )
+
+
def test_ingest_records_uses_query_params_list_from_dagrun_conf():
# Initialize the ingester with a conf
ingester = MockProviderDataIngester(
@@ -428,9 +471,36 @@ def test_ingest_records_uses_additional_query_params_from_dagrun_conf():
get_batch_mock.assert_has_calls(
[
call({"has_image": 1, "page": 1, "extra_param": 310}),
- call({"has_image": 1, "page": 1, "extra_param": 310}),
- call({"has_image": 1, "page": 1, "extra_param": 310}),
- call({"has_image": 1, "page": 1, "extra_param": 310}),
+ call({"has_image": 1, "page": 2, "extra_param": 310}),
+ call({"has_image": 1, "page": 3, "extra_param": 310}),
+ call({"has_image": 1, "page": 4, "extra_param": 310}),
+ ]
+ )
+
+
+def test_ingest_records_merges_fixed_query_params():
+ # Initialize the ingester with a conf
+ ingester = MockProviderDataIngester()
+
+ with (
+ patch.object(ingester, "get_batch") as get_batch_mock,
+ patch.object(ingester, "process_batch", return_value=3),
+ ):
+ get_batch_mock.side_effect = [
+ (EXPECTED_BATCH_DATA, True),
+ (EXPECTED_BATCH_DATA, True),
+ (EXPECTED_BATCH_DATA, True),
+ (EXPECTED_BATCH_DATA, False),
+ ]
+
+ ingester._ingest_records(None, fixed_query_params={"foo": "bar"})
+
+ get_batch_mock.assert_has_calls(
+ [
+ call({"has_image": 1, "page": 1, "foo": "bar"}),
+ call({"has_image": 1, "page": 2, "foo": "bar"}),
+ call({"has_image": 1, "page": 3, "foo": "bar"}),
+ call({"has_image": 1, "page": 4, "foo": "bar"}),
]
)
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_science_museum.py b/catalog/tests/dags/providers/provider_api_scripts/test_science_museum.py
index b4aef9735..52e3b0b45 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_science_museum.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_science_museum.py
@@ -82,11 +82,9 @@ def test_get_year_ranges():
def test_get_query_param_default():
- actual_param = sm.get_next_query_params({}, **{"year_range": (0, 1500)})
+ actual_param = sm.get_next_query_params({})
expected_param = default_params | {
"page[number]": 0,
- "date[from]": 0,
- "date[to]": 1500,
}
assert actual_param == expected_param
@@ -95,13 +93,9 @@ def test_get_query_param_default():
def test_get_query_param_offset_page_number():
sm = ScienceMuseumDataIngester()
sm.page_number = 10
- actual_param = sm.get_next_query_params(
- default_params | {"page[number]": 10}, **{"year_range": (1500, 2000)}
- )
+ actual_param = sm.get_next_query_params(default_params | {"page[number]": 10})
expected_param = default_params | {
"page[number]": 11,
- "date[from]": 1500,
- "date[to]": 2000,
}
assert actual_param == expected_param
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_smithsonian.py b/catalog/tests/dags/providers/provider_api_scripts/test_smithsonian.py
index aa525a83a..08a4c64bf 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_smithsonian.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_smithsonian.py
@@ -101,14 +101,19 @@ def test_get_hash_prefixes_with_other_len(
assert actual_list[-1] == expect_last
-def test_get_next_query_params_first_call():
- hash_prefix = "ff"
- actual_params = ingester.get_next_query_params(
- prev_query_params=None, hash_prefix=hash_prefix
- )
+def test_get_fixed_query_params():
+ with patch.object(ingester, "_get_hash_prefixes", return_value=["aa", "bb"]):
+ actual_fixed_params = ingester.get_fixed_query_params()
+ assert actual_fixed_params == [
+ {"q": "online_media_type:Images AND media_usage:CC0 AND hash:aa*"},
+ {"q": "online_media_type:Images AND media_usage:CC0 AND hash:bb*"},
+ ]
+
+
+def test_get_query_params_first_call():
+ actual_params = ingester.get_next_query_params(None)
actual_params.pop("api_key") # Omitting the API key
expected_params = {
- "q": f"online_media_type:Images AND media_usage:CC0 AND hash:{hash_prefix}*",
"start": 0,
"rows": 1000,
}
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_stocksnap.py b/catalog/tests/dags/providers/provider_api_scripts/test_stocksnap.py
index cd355b38b..d7c8f64bc 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_stocksnap.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_stocksnap.py
@@ -123,9 +123,15 @@ def test_endpoint_increment():
def test_initial_params_respected():
stocksnap = StockSnapDataIngester(conf={"initial_query_params": {"page": 5}})
- query_params = stocksnap._get_query_params(None)
- assert stocksnap._page_counter == 5
- assert query_params == {"page": 5}
+ with patch.object(stocksnap, "_ingest_records") as _ingest_mock:
+ stocksnap.ingest_records()
+ _ingest_mock.assert_called_with({"page": 5}, {})
+
+ # Assert that the next time _get_query_params is called, the page counter
+ # increments appropriately instead of starting back at the beginning
+ query_params = stocksnap._get_query_params({"page": 5})
+ assert query_params == {"page": 6}
+ assert stocksnap._page_counter == 6
def test_get_record_data_returns_none_when_media_data_none():
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py b/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
index f40c3771a..7e441c2b2 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
@@ -154,7 +154,7 @@ def test_get_timestamp_pairs_with_large_record_counts():
def test_ingest_records_calls_super_for_each_ts_pair():
with (
patch(
- "providers.provider_api_scripts.provider_data_ingester.ProviderDataIngester.ingest_records"
+ "providers.provider_api_scripts.provider_data_ingester.ProviderDataIngester._ingest_records"
) as super_mock,
patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
):
@@ -165,44 +165,20 @@ def test_ingest_records_calls_super_for_each_ts_pair():
ts_2 = (start + timedelta(hours=2), start + timedelta(hours=3))
ts_mock.return_value = [ts_0, ts_1, ts_2]
- ingester.ingest_records(test_kwarg="test")
+ ingester.ingest_records()
# There should be a call to the super `ingest_records` for each set of pairs,
# with the timestamps passed through as kwargs along with any other kwargs
assert super_mock.call_count == 3
super_mock.assert_has_calls(
[
- call(start_ts=ts_0[0], end_ts=ts_0[1], test_kwarg="test"),
- call(start_ts=ts_1[0], end_ts=ts_1[1], test_kwarg="test"),
- call(start_ts=ts_2[0], end_ts=ts_2[1], test_kwarg="test"),
+ call(None, {"start_ts": ts_0[0], "end_ts": ts_0[1]}),
+ call(None, {"start_ts": ts_1[0], "end_ts": ts_1[1]}),
+ call(None, {"start_ts": ts_2[0], "end_ts": ts_2[1]}),
]
)
-def test_ts_pairs_and_kwargs_are_available_in_get_next_query_params():
- with (
- patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
- patch.object(ingester, "get_batch", return_value=([], False)),
- ):
- mock_start = datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc)
- mock_end = mock_start + timedelta(hours=1)
- ts_mock.return_value = [(mock_start, mock_end)]
-
- # Spy on get_next_query_params
- ingester.get_next_query_params = MagicMock(
- side_effect=ingester.get_next_query_params
- )
-
- ingester.ingest_records(foo="foo", bar="bar")
-
- # When get_next_query_params is called, the start and end timestamps
- # are passed in as kwargs *in addition to any other kwargs passed to
- # ingest_records*
- ingester.get_next_query_params.assert_called_with(
- None, start_ts=mock_start, end_ts=mock_end, foo="foo", bar="bar"
- )
-
-
def test_ingest_records_raises_error_if_the_total_count_has_been_exceeded():
# Test that `ingest_records` raises an Exception if the external
# API continues returning data in excess of the stated `resultCount`