Skip to content

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

Update Flickr to use new time delineated ingester class (#995)

Staci Mullinse4f39bb60ff4
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py b/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py
index 2dfb84d00..d0694b1dc 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py
@@ -15,13 +15,14 @@ Notes: https://api.finna.fi/swagger-ui/
regular ingestion.
"""
import logging
-from datetime import datetime, timedelta, timezone
from itertools import chain
-from airflow.exceptions import AirflowException
+from common import constants
from common.licenses import get_license_info
from common.loader import provider_details as prov
-from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
+from providers.provider_api_scripts.time_delineated_provider_data_ingester import (
+ TimeDelineatedProviderDataIngester,
+)
logging.basicConfig(
@@ -36,7 +37,7 @@ PROVIDER = prov.FINNISH_DEFAULT_PROVIDER
SUB_PROVIDERS = prov.FINNISH_SUB_PROVIDERS
-class FinnishMuseumsDataIngester(ProviderDataIngester):
+class FinnishMuseumsDataIngester(TimeDelineatedProviderDataIngester):
providers = {"image": PROVIDER}
endpoint = "https://api.finna.fi/api/v1/search"
batch_limit = 100
@@ -48,153 +49,15 @@ class FinnishMuseumsDataIngester(ProviderDataIngester):
"0/SATMUSEO/",
"0/SA-kuva/",
]
-
- def __init__(self, *args, **kwargs):
- """
- Note: this DAG runs ingestion separately for each configured `building`. When a
- building has many records for the ingestion date, the DAG further splits up
- ingestion into time slices. Each run of the `ingest_records` function for
- a particular (building, time slice) pair is an "iteration" of the DAG.
-
- For logging and alerting purposes, we maintain several instance variables
- that help track each iteration.
- """
- # A flag that is True only when we are processing the first batch of data in
- # a new iteration.
- self.new_iteration = True
- # Use to keep track of the number of records we've fetched from the API so far,
- # specifically in this iteration.
- self.fetched_count = 0
-
- super().__init__(*args, **kwargs)
-
- @staticmethod
- def format_ts(timestamp):
- return timestamp.isoformat().replace("+00:00", "Z")
-
- @staticmethod
- def _get_timestamp_query_params_list(
- start_date: datetime, end_date: datetime, number_of_divisions: int
- ) -> list[tuple[datetime, datetime]]:
- """
- Given a start_date and end_date, returns a list of timestamp pairs that
- divides the time interval between them into equal portions, with the
- number of portions determined by `number_of_divisions`.
-
- Required Arguments:
- start_date: datetime to be considered start of the interval
- end_date: datetime to be considered end of the interval
- number_of_divisions: int number of portions to divide the interval into.
- """
- seconds_in_time_slice = (end_date - start_date).total_seconds()
- portion = int(seconds_in_time_slice / number_of_divisions)
- # Double check that the division resulted in even portions
- if seconds_in_time_slice % number_of_divisions:
- raise ValueError(
- f"The time slice from {start_date} to {end_date} cannot be divided "
- f"evenly into {number_of_divisions} parts!"
- )
-
- # Generate the start/end timestamps for each 'slice' of the interval
- return [
- (
- start_date + timedelta(seconds=i * portion),
- start_date + timedelta(seconds=(i + 1) * portion),
- )
- for i in range(number_of_divisions)
- ]
-
- def _get_record_count(self, start: datetime, end: datetime, building: str) -> int:
- """
- Get the number of records returned by the Finnish Museums API for a
- particular building, during a given time interval.
- """
- query_params = self.get_next_query_params(
- prev_query_params=None, building=building, start_ts=start, end_ts=end
- )
- response_json = self.get_response_json(query_params)
-
- if response_json:
- return response_json.get("resultCount", 0)
- return 0
-
- def _get_timestamp_pairs(self, building: str):
- """
- Determine a set of timestamp pairs per building.
- The Finnish Museums API can behave unexpectedly when querying large datasets,
- resulting in large numbers of duplicates and eventual DAG timeouts
- (see https://github.com/WordPress/openverse-catalog/pull/879 for more
- details). To avoid this, when we detect that a time period contains a large
- number of records we split it up into multiple smaller time periods and
- run ingestion separately for each.
-
- Most runs of the DAG will have a very small (or zero) number of records, so in
- order to determine how many time intervals we need we first check the record
- count, and split into the smallest number of intervals possible.
-
- If the building has no/few records, this results in ONE extra request.
- If the building has a large amount of data, this results in TWENTY FIVE extra
- requests (one for the full day, and then one for each hour).
- """
- pairs_list: list[tuple[datetime, datetime]] = []
- # Get UTC timestamps for the start and end of the ingestion date
- start_ts = datetime.strptime(self.date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
- end_ts = start_ts + timedelta(days=1)
-
- record_count = self._get_record_count(start_ts, end_ts, building)
- if record_count == 0:
- logger.info(f"No data for {building}. Continuing.")
- return pairs_list
- if record_count < 10_000:
- # This building only has a small amount of data. We can ingest all of the
- # data for it in a single run.
- return self._get_timestamp_query_params_list(start_ts, end_ts, 1)
-
- # If we got here, this building has a large amount of data. Since data is often
- # not distributed evenly across the day, we'll break down each hour of the day
- # separately. We add timestamp_pairs to the list only for hours that actually
- # contain data. Hours that contain more data get divided into a larger number of
- # portions.
- hour_slices = self._get_timestamp_query_params_list(start_ts, end_ts, 24)
- for (start_hour, end_hour) in hour_slices:
- # Get the number of records in this hour interval
- record_count = self._get_record_count(start_hour, end_hour, building)
- if record_count == 0:
- # No records for this hour, don't bother ingesting for this time period.
- logger.info(f"No data detected for {start_hour}. Continuing.")
- continue
- if record_count < 10_000:
- # This hour doesn't have much data, ingest it in one chunk
- pairs_list.append((start_hour, end_hour))
- continue
- # If we got this far, this hour has a lot of data. It is split into 12 5-min
- # intervals if it has fewer than 100k, or 20 3-min intervals if more.
- num_divisions = 12 if record_count < 100_000 else 20
- minute_slices = self._get_timestamp_query_params_list(
- start_hour, end_hour, num_divisions
- )
- pairs_list.extend(minute_slices)
-
- return pairs_list
+ max_records = 10_000
+ division_threshold = 100_000
+ min_divisions = 12
+ max_divisions = 20
def ingest_records(self, **kwargs):
for building in self.buildings:
logger.info(f"Obtaining images of building {building}")
-
- # Get the timestamp pairs. If there are no records for this building,
- # it will be an empty list.
- timestamp_pairs = self._get_timestamp_pairs(building)
-
- # Run ingestion for each timestamp pair
- for start_ts, end_ts in timestamp_pairs:
- # Reset counts before we start
- self.new_iteration = True
- self.fetched_count = 0
-
- logger.info(f"Ingesting data for start: {start_ts}, end: {end_ts}")
- super().ingest_records(
- building=building, start_ts=start_ts, end_ts=end_ts
- )
+ super().ingest_records(building=building)
def get_next_query_params(self, prev_query_params, **kwargs):
if not prev_query_params:
@@ -222,8 +85,13 @@ class FinnishMuseumsDataIngester(ProviderDataIngester):
}
return {**prev_query_params, "page": prev_query_params["page"] + 1}
+ def get_record_count_from_response(self, response_json):
+ if response_json:
+ return response_json.get("resultCount", 0)
+ return 0
+
def get_media_type(self, record):
- return "image"
+ return constants.IMAGE
def get_batch_data(self, response_json):
if (
@@ -234,26 +102,6 @@ class FinnishMuseumsDataIngester(ProviderDataIngester):
):
return None
- total_count = response_json.get("resultCount")
- # Update the number of records we have pulled for this iteration.
- # Note that this tracks the number of records pulled from the API, not
- # the number actually written to TSV (which may be larger or smaller
- # as some records are discarded or have additional related images.)
- self.fetched_count += len(response_json.get("records"))
-
- if self.new_iteration:
- # This is the first batch of a new iteration.
- logger.info(f"Detected {total_count} total records.")
- self.new_iteration = False
-
- # Detect a bug when the API continues serving pages of data in excess of
- # the stated resultCount.
- if self.fetched_count > total_count:
- raise AirflowException(
- f"Expected {total_count} records, but {self.fetched_count} have"
- " been fetched. Consider reducing the ingestion interval."
- )
-
return response_json["records"]
def get_record_data(self, data):
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/flickr.py b/openverse_catalog/dags/providers/provider_api_scripts/flickr.py
index 47a696a69..6f7f97339 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/flickr.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/flickr.py
@@ -12,15 +12,18 @@ Notes: https://www.flickr.com/help/terms/api
import argparse
import logging
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta
import lxml.html as html
+from airflow.exceptions import AirflowException
from airflow.models import Variable
from common import constants
from common.licenses import get_license_info
from common.loader import provider_details as prov
from common.loader.provider_details import ImageCategory
-from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
+from providers.provider_api_scripts.time_delineated_provider_data_ingester import (
+ TimeDelineatedProviderDataIngester,
+)
logger = logging.getLogger(__name__)
@@ -37,7 +40,7 @@ LICENSE_INFO = {
}
-class FlickrDataIngester(ProviderDataIngester):
+class FlickrDataIngester(TimeDelineatedProviderDataIngester):
provider_string = prov.FLICKR_DEFAULT_PROVIDER
sub_providers = prov.FLICKR_SUB_PROVIDERS
photo_url_base = prov.FLICKR_PHOTO_URL_BASE
@@ -47,6 +50,16 @@ class FlickrDataIngester(ProviderDataIngester):
batch_limit = 500
retries = 5
+ max_records = 4_000
+ division_threshold = 20_000
+ min_divisions = 12
+ max_divisions = 60
+ # When we pull more records than the API reports, we don't want to raise an error
+ # and halt ingestion. Instead, this DAG adds its own separate handling to cut off
+ # ingestion when max_records is reached, and continue to the next time interval. See
+ # https://github.com/WordPress/openverse-catalog/pull/995
+ should_raise_error = False
+
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -60,48 +73,11 @@ class FlickrDataIngester(ProviderDataIngester):
# to hitting rate limits.
self.requests_count = 0
- @staticmethod
- def _derive_timestamp_pair_list(date):
- """
- Create a list of start/end timestamps for equal portions of the day.
-
- Ingestion will be run separately for each of these time divisions.
- This is necessary because requesting data for too long a period may cause
- unexpected behavior from the API:
- https://github.com/WordPress/openverse-catalog/issues/26.
- """
- seconds_in_a_day = 86400
- number_of_divisions = 48 # Half-hour increments
- portion = int(seconds_in_a_day / number_of_divisions)
- utc_date = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
-
- def _ts_string(d):
- return str(int(d.timestamp()))
-
- # Generate the start/end timestamps for each half-hour 'slice' of the day
- pair_list = [
- (
- _ts_string(utc_date + timedelta(seconds=i * portion)),
- _ts_string(utc_date + timedelta(seconds=(i + 1) * portion)),
- )
- for i in range(number_of_divisions)
- ]
- return pair_list
-
- def ingest_records(self, **kwargs):
- # Build a list of start/end timestamps demarcating portions of the day
- # for which to ingest data.
- timestamp_pairs = self._derive_timestamp_pair_list(self.date)
-
- for start_ts, end_ts in timestamp_pairs:
- logger.info(f"Ingesting data for start: {start_ts}, end: {end_ts}")
- super().ingest_records(start_timestamp=start_ts, end_timestamp=end_ts)
-
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_timestamp")
- end_timestamp = kwargs.get("end_timestamp")
+ start_timestamp = kwargs.get("start_ts")
+ end_timestamp = kwargs.get("end_ts")
return {
"min_upload_date": start_timestamp,
@@ -151,6 +127,12 @@ class FlickrDataIngester(ProviderDataIngester):
return None
return response_json.get("photos", {}).get("photo")
+ def get_record_count_from_response(self, response_json) -> int:
+ if response_json:
+ count = response_json.get("photos", {}).get("total", 0)
+ return int(count)
+ return 0
+
def get_record_data(self, data):
if (license_info := self._get_license_info(data)) is None:
return None
@@ -272,6 +254,22 @@ class FlickrDataIngester(ProviderDataIngester):
return ImageCategory.PHOTOGRAPH
return None
+ def get_should_continue(self, response_json):
+ # Call the parent method in order to update the fetched_count
+ should_continue = super().get_should_continue(response_json)
+
+ # Return early if more than the max_records have been ingested.
+ # This could happen if we did not break the ingestion down into
+ # small enough divisions.
+ if self.fetched_count > self.max_records:
+ raise AirflowException(
+ f"{self.fetched_count} records retrieved, but there is a"
+ f" limit of {self.max_records}. Consider increasing the"
+ " number of divisions."
+ )
+
+ return should_continue
+
def main(date):
ingester = FlickrDataIngester(date=date)
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py b/openverse_catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
new file mode 100644
index 000000000..be61e0fb7
--- /dev/null
+++ b/openverse_catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
@@ -0,0 +1,239 @@
+import logging
+from abc import abstractmethod
+from datetime import datetime, timedelta, timezone
+
+from airflow.exceptions import AirflowException
+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
+
+
+logger = logging.getLogger(__name__)
+
+
+class TimeDelineatedProviderDataIngester(ProviderDataIngester):
+ """
+ A subclass of ProviderDataIngester which breaks the ingestion interval into
+ smaller intervals, and runs ingestion separately for each interval.
+
+ Must be used on a dated DAG.
+
+ Class variables of note:
+ max_records: integer giving the maximum number of records to be expected in
+ each interval
+ division_threshold: integer threshold number of records in an hour, used to
+ determine how many divisions to use
+ min_divisions: integer giving the number of divisions to break an hour into if
+ the division_threshold is not exceeded
+ max_divisions: integer giving the number of divisions to break an hour into if
+ the division_threshold is exceeded
+ should_raise_error: whether to raise an exception when more records are retrieved
+ from the API than the API reports to expect
+ """
+
+ min_divisions = 4 # 15-minute default intervals
+ max_divisions = 12 # 5-minute default intervals
+ should_raise_error = True
+
+ @property
+ @abstractmethod
+ def max_records(self) -> int:
+ pass
+
+ @property
+ @abstractmethod
+ def division_threshold(self) -> int:
+ pass
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ # This class is used to generate timestamp intervals over a 24-hour period,
+ # so it should only be used for a dated DAG.
+ if self.date is None:
+ raise ValueError(
+ f"{self.__class__.__name__} should only be used for dated DAGs."
+ )
+
+ # A flag that is True only when we are processing the first batch of data in
+ # a new iteration.
+ self.new_iteration = True
+ # Use to keep track of the number of records we've fetched from the API so far,
+ # specifically in this iteration.
+ self.fetched_count = 0
+
+ @staticmethod
+ def format_ts(timestamp):
+ return timestamp.isoformat().replace("+00:00", "Z")
+
+ @staticmethod
+ def _get_timestamp_query_params_list(
+ start_date: datetime, end_date: datetime, number_of_divisions: int
+ ) -> list[tuple[datetime, datetime]]:
+ """
+ Given a start_date and end_date, returns a list of timestamp pairs that
+ divides the time interval between them into equal portions, with the
+ number of portions determined by `number_of_divisions`.
+
+ Required Arguments:
+ start_date: datetime to be considered start of the interval
+ end_date: datetime to be considered end of the interval
+ number_of_divisions: int number of portions to divide the interval into.
+ """
+ seconds_in_time_slice = (end_date - start_date).total_seconds()
+ portion = int(seconds_in_time_slice / number_of_divisions)
+ # Double check that the division resulted in even portions
+ if seconds_in_time_slice % number_of_divisions:
+ raise ValueError(
+ f"The time slice from {start_date} to {end_date} cannot be divided "
+ f"evenly into {number_of_divisions} parts!"
+ )
+
+ # Generate the start/end timestamps for each 'slice' of the interval
+ return [
+ (
+ start_date + timedelta(seconds=i * portion),
+ start_date + timedelta(seconds=(i + 1) * portion),
+ )
+ for i in range(number_of_divisions)
+ ]
+
+ @abstractmethod
+ def get_record_count_from_response(self, response_json) -> int:
+ # Given a response_json, return the response_count. This should not be the
+ # number of records in the response, but the reported count.
+ pass
+
+ 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
+ )
+ response_json = self.get_response_json(query_params)
+
+ return self.get_record_count_from_response(response_json)
+
+ def _get_timestamp_pairs(self, **kwargs):
+ """
+ Determine a set of timestamp pairs.
+ Some provider APIs can behave unexpectedly when querying large datasets,
+ resulting in large numbers of duplicates and eventual DAG timeouts
+ (see https://github.com/WordPress/openverse-catalog/pull/879 for an
+ example). To avoid this, when we detect that a time period contains a large
+ number of records we split it up into multiple smaller time periods and
+ run ingestion separately for each.
+
+ Some runs of the DAG may have a very small (or zero) number of records, so in
+ order to determine how many time intervals we need we first check the record
+ count, and split into the smallest number of intervals possible.
+
+ If the interval has no/few records, this results in ONE extra request.
+ If the interval has a large amount of data, this results in TWENTY FIVE extra
+ requests (one for the full day, and then one for each hour).
+ """
+ pairs_list: list[tuple[datetime, datetime]] = []
+ # Get UTC timestamps for the start and end of the ingestion date
+ start_ts = datetime.strptime(self.date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
+ end_ts = start_ts + timedelta(days=1)
+
+ record_count = self._get_record_count(start_ts, end_ts, **kwargs)
+ if record_count == 0:
+ logger.info("No data. Continuing.")
+ return pairs_list
+ if record_count < self.max_records:
+ # This interval only has a small amount of data. We can ingest all of the
+ # data for it in a single run.
+ logger.info(
+ f"Record count {record_count} is less than maximum of"
+ f" {self.max_records}. Ingesting data for the full day at once."
+ )
+ return self._get_timestamp_query_params_list(start_ts, end_ts, 1)
+
+ # If we got here, this day has a large amount of data. Since data is often
+ # not distributed evenly across the day, we'll break down each hour of the day
+ # separately. We add timestamp_pairs to the list only for hours that actually
+ # contain data. Hours that contain more data get divided into a larger number of
+ # portions.
+ hour_slices = self._get_timestamp_query_params_list(start_ts, end_ts, 24)
+ for (start_hour, end_hour) in hour_slices:
+ # Get the number of records in this hour interval
+ record_count = self._get_record_count(start_hour, end_hour, **kwargs)
+ if record_count == 0:
+ # No records for this hour, don't bother ingesting for this time period.
+ logger.info(f"No data detected for {start_hour}. Continuing.")
+ continue
+ if record_count < self.max_records:
+ # This hour doesn't have much data, ingest it in one chunk
+ logger.info(
+ f"Record count {record_count} is less than maximum of"
+ f" {self.max_records}. Ingesting data for the full hour starting at"
+ f" {start_hour}."
+ )
+ pairs_list.append((start_hour, end_hour))
+ continue
+ # If we got this far, this hour has a lot of data. Check the count against
+ # the division_threshold; if less than the threshold, we divide into the
+ # smaller number of min_divisions. Otherwise, we use max_divisions
+ num_divisions = (
+ self.min_divisions
+ if record_count < self.division_threshold
+ else self.max_divisions
+ )
+ minute_slices = self._get_timestamp_query_params_list(
+ start_hour, end_hour, num_divisions
+ )
+ pairs_list.extend(minute_slices)
+
+ return pairs_list
+
+ def ingest_records(self, **kwargs) -> None:
+ timestamp_pairs = self._get_timestamp_pairs(**kwargs)
+ if timestamp_pairs:
+ logger.info(f"{len(timestamp_pairs)} timestamp pairs generated.")
+
+ # Run ingestion for each timestamp pair
+ for start_ts, end_ts in timestamp_pairs:
+ # Reset counts before we start
+ self.new_iteration = True
+ self.fetched_count = 0
+
+ logger.info(f"Ingesting data for start: {start_ts}, end: {end_ts}")
+ super().ingest_records(start_ts=start_ts, end_ts=end_ts, **kwargs)
+
+ def get_should_continue(self, response_json) -> bool:
+ """
+ Update the `fetched_count` and `new_iteration` variables. Also adds
+ some default error detection for a common bug where the ingester
+ retrieves more records from the API than the reported total count.
+ """
+
+ # Get the total expected count for this time interval from the API.
+ total_count = self.get_record_count_from_response(response_json)
+
+ # Update the number of records we have pulled for this iteration.
+ # Note that this tracks the number of records fetched from the API, not
+ # the number "ingested", ie actually written to TSV (which may be larger
+ # or smaller as some records are discarded or have additional related
+ # images.)
+ batch = self.get_batch_data(response_json)
+ if batch:
+ self.fetched_count += len(batch)
+
+ if self.new_iteration:
+ # This is the first batch of a new iteration.
+ logger.info(f"Detected {total_count} total records.")
+ self.new_iteration = False
+
+ # Detect a bug when the API continues serving pages of data in excess of
+ # the stated resultCount.
+ if self.fetched_count > total_count:
+ error_message = (
+ f"Expected {total_count} records, but {self.fetched_count} have"
+ " been fetched. Consider reducing the ingestion interval."
+ )
+ if self.should_raise_error:
+ raise AirflowException(error_message)
+ else:
+ logger.error(error_message)
+
+ # If `should_raise_error` was enabled, the error is raised and ingestion
+ # halted. If not, we want to log but continue ingesting.
+ return True
diff --git a/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py b/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
index 9ff37e170..df9480a60 100644
--- a/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
+++ b/tests/dags/providers/provider_api_scripts/resources/provider_data_ingester/mock_provider_data_ingester.py
@@ -1,5 +1,8 @@
from common.licenses import LicenseInfo
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
+from providers.provider_api_scripts.time_delineated_provider_data_ingester import (
+ TimeDelineatedProviderDataIngester,
+)
_license_info = (
@@ -15,6 +18,12 @@ ENDPOINT = "http://mock-api/endpoint"
HEADERS = {"api_key": "mock_api_key"}
DEFAULT_QUERY_PARAMS = {"has_image": 1, "page": 1}
+# Constants used for time delineated ingester
+MAX_RECORDS = 10_000
+DIVISION_THRESHOLD = 100_000
+MIN_DIVISIONS = 12
+MAX_DIVISIONS = 20
+
class MockProviderDataIngesterMixin:
"""
@@ -27,7 +36,7 @@ class MockProviderDataIngesterMixin:
providers = {"audio": AUDIO_PROVIDER, "image": IMAGE_PROVIDER}
endpoint = ENDPOINT
- def get_next_query_params(self, prev_query_params):
+ def get_next_query_params(self, prev_query_params, **kwargs):
return DEFAULT_QUERY_PARAMS
def get_batch_data(self, response_json):
@@ -75,6 +84,28 @@ class IncorrectlyConfiguredMockProviderDataIngester(
# for the default implementation
+class MockTimeDelineatedProviderDataIngester(
+ MockProviderDataIngesterMixin, TimeDelineatedProviderDataIngester
+):
+ providers = {"image": IMAGE_PROVIDER}
+ max_records = MAX_RECORDS
+ division_threshold = DIVISION_THRESHOLD
+ 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_record_count_from_response(self, response_json):
+ if response_json:
+ return response_json.get("count")
+ return 0
+
+
# Expected result of calling `get_batch_data` with `response_success.json`
EXPECTED_BATCH_DATA = [
{
diff --git a/tests/dags/providers/provider_api_scripts/test_finnish_museums.py b/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
index 5e1ed3131..741d0baa3 100644
--- a/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
+++ b/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
@@ -2,11 +2,9 @@ import json
import logging
import os
from datetime import datetime, timedelta, timezone
-from itertools import repeat
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
-from airflow.exceptions import AirflowException
from common.licenses import LicenseInfo
from common.loader import provider_details as prov
from common.storage.image import ImageStore
@@ -49,182 +47,11 @@ def _get_resource_json(json_name):
def test_get_record_count(response_json, expected_count):
with patch.object(fm, "get_response_json", return_value=response_json):
actual_count = fm._get_record_count(
- datetime(2022, 4, 1), datetime(2022, 4, 2), "test_building"
+ datetime(2022, 4, 1), datetime(2022, 4, 2), building="test_building"
)
assert actual_count == expected_count
- "num_divisions, expected_pairs",
- [
- # One division
- (1, [(datetime(2020, 4, 1, 1, 0), datetime(2020, 4, 1, 2, 0))]),
- # Two divisions divides into 30 min increments
- (
- 2,
- [
- (datetime(2020, 4, 1, 1, 0), datetime(2020, 4, 1, 1, 30)),
- (datetime(2020, 4, 1, 1, 30), datetime(2020, 4, 1, 2, 0)),
- ],
- ),
- # 8 divisions divides into 7.5 min increments
- (
- 8,
- [
- (datetime(2020, 4, 1, 1, 0, 0), datetime(2020, 4, 1, 1, 7, 30)),
- (datetime(2020, 4, 1, 1, 7, 30), datetime(2020, 4, 1, 1, 15, 0)),
- (datetime(2020, 4, 1, 1, 15, 0), datetime(2020, 4, 1, 1, 22, 30)),
- (datetime(2020, 4, 1, 1, 22, 30), datetime(2020, 4, 1, 1, 30, 0)),
- (datetime(2020, 4, 1, 1, 30, 0), datetime(2020, 4, 1, 1, 37, 30)),
- (datetime(2020, 4, 1, 1, 37, 30), datetime(2020, 4, 1, 1, 45, 0)),
- (datetime(2020, 4, 1, 1, 45, 0), datetime(2020, 4, 1, 1, 52, 30)),
- (datetime(2020, 4, 1, 1, 52, 30), datetime(2020, 4, 1, 2, 0, 0)),
- ],
- ),
- # 7 does not divide evenly into 60, so error is raised
- pytest.param(7, None, marks=pytest.mark.raises(exception=ValueError)),
- ],
-)
-def test_get_timestamp_query_params_list(num_divisions, expected_pairs):
- # Hour long time slice
- start_date = datetime(2020, 4, 1, 1, 0)
- end_date = datetime(2020, 4, 1, 2, 0)
-
- actual_pairs = fm._get_timestamp_query_params_list(
- start_date, end_date, num_divisions
- )
- assert actual_pairs == expected_pairs
-
-
-def test_get_timestamp_pairs_returns_empty_list_when_no_records_found():
- # mock _get_record_count to return 0 records
- with patch.object(fm, "_get_record_count", return_value=0):
- actual_pairs_list = fm._get_timestamp_pairs("test_building")
-
- assert len(actual_pairs_list) == 0
-
-
-def test_get_timestamp_pairs_returns_full_day_when_few_records_found():
- # When < 10_000 records are found for the day, we should get back a single
- # timestamp pair representing the whole day
- expected_pairs_list = [
- (
- datetime(2020, 4, 1, 0, 0, tzinfo=timezone.utc),
- datetime(2020, 4, 2, 0, 0, tzinfo=timezone.utc),
- )
- ]
-
- with patch.object(fm, "_get_record_count", return_value=9999):
- actual_pairs_list = fm._get_timestamp_pairs("test_building")
- assert actual_pairs_list == expected_pairs_list
-
-
-def test_get_timestamp_pairs_with_large_record_counts():
- with patch.object(fm, "_get_record_count") as mock_count:
- # Mock the calls to _get_record_count in order
- mock_count.side_effect = [
- 150_000, # Getting total count for the entire day
- 0, # Get count for first hour, count == 0
- 10, # Get count for second hour, count < 10_000
- 101_000, # Get count for third hour, count > 100_000
- 49_090, # Get count for fourth hour, 10_000 < count < 100_000
- ] + list(
- repeat(0, 20)
- ) # Fill list with count == 0 for the remaining hours
-
- # We only get timestamp pairs for the hours that had records. For the
- # hour with > 100k records, we get 20 3-min pairs. For the hour with
- # < 100k records, we get 12 5-min pairs.
- expected_pairs_list = [
- # Single intervals for second hour
- ("2020-04-01T01:00:00Z", "2020-04-01T02:00:00Z"),
- # 20 3-min intervals across the third hour
- ("2020-04-01T02:00:00Z", "2020-04-01T02:03:00Z"),
- ("2020-04-01T02:03:00Z", "2020-04-01T02:06:00Z"),
- ("2020-04-01T02:06:00Z", "2020-04-01T02:09:00Z"),
- ("2020-04-01T02:09:00Z", "2020-04-01T02:12:00Z"),
- ("2020-04-01T02:12:00Z", "2020-04-01T02:15:00Z"),
- ("2020-04-01T02:15:00Z", "2020-04-01T02:18:00Z"),
- ("2020-04-01T02:18:00Z", "2020-04-01T02:21:00Z"),
- ("2020-04-01T02:21:00Z", "2020-04-01T02:24:00Z"),
- ("2020-04-01T02:24:00Z", "2020-04-01T02:27:00Z"),
- ("2020-04-01T02:27:00Z", "2020-04-01T02:30:00Z"),
- ("2020-04-01T02:30:00Z", "2020-04-01T02:33:00Z"),
- ("2020-04-01T02:33:00Z", "2020-04-01T02:36:00Z"),
- ("2020-04-01T02:36:00Z", "2020-04-01T02:39:00Z"),
- ("2020-04-01T02:39:00Z", "2020-04-01T02:42:00Z"),
- ("2020-04-01T02:42:00Z", "2020-04-01T02:45:00Z"),
- ("2020-04-01T02:45:00Z", "2020-04-01T02:48:00Z"),
- ("2020-04-01T02:48:00Z", "2020-04-01T02:51:00Z"),
- ("2020-04-01T02:51:00Z", "2020-04-01T02:54:00Z"),
- ("2020-04-01T02:54:00Z", "2020-04-01T02:57:00Z"),
- ("2020-04-01T02:57:00Z", "2020-04-01T03:00:00Z"),
- # 12 5-min intervals across the fourth hour
- ("2020-04-01T03:00:00Z", "2020-04-01T03:05:00Z"),
- ("2020-04-01T03:05:00Z", "2020-04-01T03:10:00Z"),
- ("2020-04-01T03:10:00Z", "2020-04-01T03:15:00Z"),
- ("2020-04-01T03:15:00Z", "2020-04-01T03:20:00Z"),
- ("2020-04-01T03:20:00Z", "2020-04-01T03:25:00Z"),
- ("2020-04-01T03:25:00Z", "2020-04-01T03:30:00Z"),
- ("2020-04-01T03:30:00Z", "2020-04-01T03:35:00Z"),
- ("2020-04-01T03:35:00Z", "2020-04-01T03:40:00Z"),
- ("2020-04-01T03:40:00Z", "2020-04-01T03:45:00Z"),
- ("2020-04-01T03:45:00Z", "2020-04-01T03:50:00Z"),
- ("2020-04-01T03:50:00Z", "2020-04-01T03:55:00Z"),
- ("2020-04-01T03:55:00Z", "2020-04-01T04:00:00Z"),
- ]
-
- actual_pairs_list = fm._get_timestamp_pairs("test_building")
- # Formatting the timestamps so the test will be more readable
- formatted_actual_pairs_list = [
- (fm.format_ts(x), fm.format_ts(y)) for x, y in actual_pairs_list
- ]
- assert formatted_actual_pairs_list == expected_pairs_list
-
-
-def test_ingest_records_raises_error_if_the_total_count_has_been_exceeded():
- # Test that `ingest_records` raises an AirflowException if the external
- # API continues returning data in excess of the stated `resultCount`
- # (https://github.com/WordPress/openverse-catalog/pull/934)
- fm = FinnishMuseumsDataIngester(date=FROZEN_DATE)
- fm.buildings = ["test_building"]
-
- with (
- patch.object(fm, "_get_timestamp_pairs") as ts_mock,
- patch.object(fm, "get_response_json") as get_mock,
- patch.object(fm, "process_batch", return_value=2) as process_mock,
- ):
- ts_mock.return_value = [
- (
- datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc),
- datetime(2020, 4, 1, 12, 0, tzinfo=timezone.utc),
- ),
- ]
-
- # Each time get_response_json is called, it will return json containing
- # 2 records, and a resultCount of 2
- get_mock.return_value = {
- "status": "ok",
- "records": [MagicMock(), MagicMock()], # Two mock records,
- "resultCount": 2, # Claim there are only two records total
- }
-
- expected_error_string = (
- "Expected 2 records, but 4 have been fetched. Consider reducing the ingestion"
- " interval."
- )
- # Assert that attempting to ingest records raises an exception
- with (pytest.raises(AirflowException, match=expected_error_string)):
- fm.ingest_records()
-
- # get_mock should have been called 2 times. Each time, it returned 2 'new' records,
- # even though the resultCount indicated there should only be 2 records total.
- assert get_mock.call_count == 2
- # process_mock should only have been called once. We raise an error when getting the
- # second batch as soon as it is detected that we've processed too many records.
- assert process_mock.call_count == 1
-
-
def test_build_query_param_default():
actual_param_made = fm.get_next_query_params(
None,
diff --git a/tests/dags/providers/provider_api_scripts/test_flickr.py b/tests/dags/providers/provider_api_scripts/test_flickr.py
index cbeaea1e0..3f436d6fe 100644
--- a/tests/dags/providers/provider_api_scripts/test_flickr.py
+++ b/tests/dags/providers/provider_api_scripts/test_flickr.py
@@ -8,7 +8,8 @@ from providers.provider_api_scripts.flickr import FlickrDataIngester
RESOURCES = os.path.join(os.path.abspath(os.path.dirname(__file__)), "resources/flickr")
-flickr = FlickrDataIngester()
+FROZEN_DATE = "2020-04-01"
+flickr = FlickrDataIngester(date=FROZEN_DATE)
test_license_info = LicenseInfo(
"by-nc-sa",
"2.0",
@@ -23,62 +24,6 @@ def _get_resource_json(json_name):
return resource_json
-def test_derive_timestamp_pair_list_with_sub_hourly_day_divisions():
- # Note that the timestamps are derived as if input was in UTC.
- actual_pair_list = flickr._derive_timestamp_pair_list("2018-01-15")
- expect_pair_list = [
- ("1515974400", "1515976200"),
- ("1515976200", "1515978000"),
- ("1515978000", "1515979800"),
- ("1515979800", "1515981600"),
- ("1515981600", "1515983400"),
- ("1515983400", "1515985200"),
- ("1515985200", "1515987000"),
- ("1515987000", "1515988800"),
- ("1515988800", "1515990600"),
- ("1515990600", "1515992400"),
- ("1515992400", "1515994200"),
- ("1515994200", "1515996000"),
- ("1515996000", "1515997800"),
- ("1515997800", "1515999600"),
- ("1515999600", "1516001400"),
- ("1516001400", "1516003200"),
- ("1516003200", "1516005000"),
- ("1516005000", "1516006800"),
- ("1516006800", "1516008600"),
- ("1516008600", "1516010400"),
- ("1516010400", "1516012200"),
- ("1516012200", "1516014000"),
- ("1516014000", "1516015800"),
- ("1516015800", "1516017600"),
- ("1516017600", "1516019400"),
- ("1516019400", "1516021200"),
- ("1516021200", "1516023000"),
- ("1516023000", "1516024800"),
- ("1516024800", "1516026600"),
- ("1516026600", "1516028400"),
- ("1516028400", "1516030200"),
- ("1516030200", "1516032000"),
- ("1516032000", "1516033800"),
- ("1516033800", "1516035600"),
- ("1516035600", "1516037400"),
- ("1516037400", "1516039200"),
- ("1516039200", "1516041000"),
- ("1516041000", "1516042800"),
- ("1516042800", "1516044600"),
- ("1516044600", "1516046400"),
- ("1516046400", "1516048200"),
- ("1516048200", "1516050000"),
- ("1516050000", "1516051800"),
- ("1516051800", "1516053600"),
- ("1516053600", "1516055400"),
- ("1516055400", "1516057200"),
- ("1516057200", "1516059000"),
- ("1516059000", "1516060800"),
- ]
- assert expect_pair_list == actual_pair_list
-
-
def test_get_next_query_params():
expected_params = {
"min_upload_date": "1516060900",
@@ -102,13 +47,13 @@ def test_get_next_query_params():
# First request
first_params = flickr.get_next_query_params(
- None, start_timestamp="1516060900", end_timestamp="1516060800"
+ None, start_ts="1516060900", end_ts="1516060800"
)
assert first_params == expected_params
# Updated page on second request
second_params = flickr.get_next_query_params(
- first_params, start_timestamp="1516060900", end_timestamp="1516060800"
+ first_params, start_ts="1516060900", end_ts="1516060800"
)
assert second_params == {**expected_params, "page": 1}
@@ -117,6 +62,13 @@ def test_get_media_type():
assert flickr.get_media_type({}) == "image"
+def test_get_record_count_from_response():
+ response_json = _get_resource_json("flickr_example_pretty.json")
+ count = flickr.get_record_count_from_response(response_json)
+
+ assert count == 30
+
+
@pytest.mark.parametrize(
"response_json, expected_response",
[
diff --git a/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py b/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
new file mode 100644
index 000000000..a71ee49ae
--- /dev/null
+++ b/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
@@ -0,0 +1,304 @@
+from datetime import datetime, timedelta, timezone
+from itertools import repeat
+from unittest.mock import MagicMock, call, patch
+
+import pytest
+from airflow.exceptions import AirflowException
+
+from tests.dags.providers.provider_api_scripts.resources.provider_data_ingester.mock_provider_data_ingester import (
+ MAX_RECORDS,
+ MockTimeDelineatedProviderDataIngester,
+)
+
+
+FROZEN_DATE = "2020-04-01"
+ingester = MockTimeDelineatedProviderDataIngester(date=FROZEN_DATE)
+
+
+def test_raises_error_when_date_is_undefined():
+ expected_error = (
+ "TimeDelineatedProviderDataIngester should only be used for dated DAGs."
+ )
+ with pytest.raises(ValueError, match=expected_error):
+ # Attempt to initialize without a date
+ MockTimeDelineatedProviderDataIngester()
+
+
+ "num_divisions, expected_pairs",
+ [
+ # One division
+ (1, [(datetime(2020, 4, 1, 1, 0), datetime(2020, 4, 1, 2, 0))]),
+ # Two divisions divides into 30 min increments
+ (
+ 2,
+ [
+ (datetime(2020, 4, 1, 1, 0), datetime(2020, 4, 1, 1, 30)),
+ (datetime(2020, 4, 1, 1, 30), datetime(2020, 4, 1, 2, 0)),
+ ],
+ ),
+ # 8 divisions divides into 7.5 min increments
+ (
+ 8,
+ [
+ (datetime(2020, 4, 1, 1, 0, 0), datetime(2020, 4, 1, 1, 7, 30)),
+ (datetime(2020, 4, 1, 1, 7, 30), datetime(2020, 4, 1, 1, 15, 0)),
+ (datetime(2020, 4, 1, 1, 15, 0), datetime(2020, 4, 1, 1, 22, 30)),
+ (datetime(2020, 4, 1, 1, 22, 30), datetime(2020, 4, 1, 1, 30, 0)),
+ (datetime(2020, 4, 1, 1, 30, 0), datetime(2020, 4, 1, 1, 37, 30)),
+ (datetime(2020, 4, 1, 1, 37, 30), datetime(2020, 4, 1, 1, 45, 0)),
+ (datetime(2020, 4, 1, 1, 45, 0), datetime(2020, 4, 1, 1, 52, 30)),
+ (datetime(2020, 4, 1, 1, 52, 30), datetime(2020, 4, 1, 2, 0, 0)),
+ ],
+ ),
+ # 7 does not divide evenly into 60, so error is raised
+ pytest.param(7, None, marks=pytest.mark.raises(exception=ValueError)),
+ ],
+)
+def test_get_timestamp_query_params_list(num_divisions, expected_pairs):
+ # Hour long time slice
+ start_date = datetime(2020, 4, 1, 1, 0)
+ end_date = datetime(2020, 4, 1, 2, 0)
+
+ actual_pairs = ingester._get_timestamp_query_params_list(
+ start_date, end_date, num_divisions
+ )
+ assert actual_pairs == expected_pairs
+
+
+def test_get_timestamp_pairs_returns_empty_list_when_no_records_found():
+ # mock _get_record_count to return 0 records
+ with patch.object(ingester, "_get_record_count", return_value=0):
+ actual_pairs_list = ingester._get_timestamp_pairs()
+
+ assert len(actual_pairs_list) == 0
+
+
+def test_get_timestamp_pairs_returns_full_day_when_few_records_found():
+ # When < max_records are found for the day, we should get back a single
+ # timestamp pair representing the whole day
+ expected_pairs_list = [
+ (
+ datetime(2020, 4, 1, 0, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 2, 0, 0, tzinfo=timezone.utc),
+ )
+ ]
+
+ with patch.object(ingester, "_get_record_count", return_value=MAX_RECORDS - 1):
+ actual_pairs_list = ingester._get_timestamp_pairs()
+ assert actual_pairs_list == expected_pairs_list
+
+
+def test_get_timestamp_pairs_with_large_record_counts():
+ with patch.object(ingester, "_get_record_count") as mock_count:
+ # Mock the calls to _get_record_count in order
+ mock_count.side_effect = [
+ 150_000, # Getting total count for the entire day
+ 0, # Get count for first hour, count == 0
+ 10, # Get count for second hour, count < max_records
+ 101_000, # Get count for third hour, count > division_threshold
+ 49_090, # Get count for fourth hour, max_records < count < division_threshold
+ ] + list(
+ repeat(0, 20)
+ ) # Fill list with count == 0 for the remaining hours
+
+ # We only get timestamp pairs for the hours that had records. For the
+ # hour with > 100k records, we get 20 3-min pairs. For the hour with
+ # < 100k records, we get 12 5-min pairs.
+ expected_pairs_list = [
+ # Single intervals for second hour
+ ("2020-04-01T01:00:00Z", "2020-04-01T02:00:00Z"),
+ # 20 3-min intervals across the third hour
+ ("2020-04-01T02:00:00Z", "2020-04-01T02:03:00Z"),
+ ("2020-04-01T02:03:00Z", "2020-04-01T02:06:00Z"),
+ ("2020-04-01T02:06:00Z", "2020-04-01T02:09:00Z"),
+ ("2020-04-01T02:09:00Z", "2020-04-01T02:12:00Z"),
+ ("2020-04-01T02:12:00Z", "2020-04-01T02:15:00Z"),
+ ("2020-04-01T02:15:00Z", "2020-04-01T02:18:00Z"),
+ ("2020-04-01T02:18:00Z", "2020-04-01T02:21:00Z"),
+ ("2020-04-01T02:21:00Z", "2020-04-01T02:24:00Z"),
+ ("2020-04-01T02:24:00Z", "2020-04-01T02:27:00Z"),
+ ("2020-04-01T02:27:00Z", "2020-04-01T02:30:00Z"),
+ ("2020-04-01T02:30:00Z", "2020-04-01T02:33:00Z"),
+ ("2020-04-01T02:33:00Z", "2020-04-01T02:36:00Z"),
+ ("2020-04-01T02:36:00Z", "2020-04-01T02:39:00Z"),
+ ("2020-04-01T02:39:00Z", "2020-04-01T02:42:00Z"),
+ ("2020-04-01T02:42:00Z", "2020-04-01T02:45:00Z"),
+ ("2020-04-01T02:45:00Z", "2020-04-01T02:48:00Z"),
+ ("2020-04-01T02:48:00Z", "2020-04-01T02:51:00Z"),
+ ("2020-04-01T02:51:00Z", "2020-04-01T02:54:00Z"),
+ ("2020-04-01T02:54:00Z", "2020-04-01T02:57:00Z"),
+ ("2020-04-01T02:57:00Z", "2020-04-01T03:00:00Z"),
+ # 12 5-min intervals across the fourth hour
+ ("2020-04-01T03:00:00Z", "2020-04-01T03:05:00Z"),
+ ("2020-04-01T03:05:00Z", "2020-04-01T03:10:00Z"),
+ ("2020-04-01T03:10:00Z", "2020-04-01T03:15:00Z"),
+ ("2020-04-01T03:15:00Z", "2020-04-01T03:20:00Z"),
+ ("2020-04-01T03:20:00Z", "2020-04-01T03:25:00Z"),
+ ("2020-04-01T03:25:00Z", "2020-04-01T03:30:00Z"),
+ ("2020-04-01T03:30:00Z", "2020-04-01T03:35:00Z"),
+ ("2020-04-01T03:35:00Z", "2020-04-01T03:40:00Z"),
+ ("2020-04-01T03:40:00Z", "2020-04-01T03:45:00Z"),
+ ("2020-04-01T03:45:00Z", "2020-04-01T03:50:00Z"),
+ ("2020-04-01T03:50:00Z", "2020-04-01T03:55:00Z"),
+ ("2020-04-01T03:55:00Z", "2020-04-01T04:00:00Z"),
+ ]
+
+ actual_pairs_list = ingester._get_timestamp_pairs()
+ # Formatting the timestamps so the test will be more readable
+ formatted_actual_pairs_list = [
+ (ingester.format_ts(x), ingester.format_ts(y)) for x, y in actual_pairs_list
+ ]
+ assert formatted_actual_pairs_list == expected_pairs_list
+
+
+def test_ingest_records_calls_super_for_each_ts_pair():
+ with (
+ patch(
+ "providers.provider_api_scripts.provider_data_ingester.ProviderDataIngester.ingest_records"
+ ) as super_mock,
+ patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
+ ):
+ # Make some mock timestamp pairs
+ start = datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc)
+ ts_0 = (start, start + timedelta(hours=1))
+ ts_1 = (start + timedelta(hours=1), start + timedelta(hours=2))
+ 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")
+
+ # 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"),
+ ]
+ )
+
+
+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*
+ assert ingester.get_next_query_params.called_with(
+ 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 AirflowException if the external
+ # API continues returning data in excess of the stated `resultCount`
+ # (https://github.com/WordPress/openverse-catalog/pull/934)
+ with (
+ patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
+ patch.object(ingester, "get_batch_data") as get_mock,
+ patch.object(ingester, "get_record_count_from_response") as count_mock,
+ patch.object(ingester, "process_batch", return_value=2) as process_mock,
+ patch.object(ingester, "get_response_json", return_value={MagicMock()}),
+ ):
+ ts_mock.return_value = [
+ (
+ datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 1, 12, 0, tzinfo=timezone.utc),
+ ),
+ ]
+
+ # Mock the API response to indicate that the total result count is 2
+ count_mock.return_value = 2
+
+ # Each time get_response_json is called, it will return json containing
+ # 2 records. After two calls, this will exceed the expected total count.
+ get_mock.return_value = {
+ "status": "ok",
+ "records": [MagicMock(), MagicMock()], # Two mock records,
+ }
+
+ expected_error_string = (
+ "Expected 2 records, but 4 have been fetched. Consider reducing the ingestion"
+ " interval."
+ )
+ # Assert that attempting to ingest records raises an exception when
+ # `should_raise_error` is enabled
+ with (pytest.raises(AirflowException, match=expected_error_string)):
+ ingester.ingest_records()
+
+ # get_mock should have been called 4 times, twice for each batch (once in `get_batch`
+ # and a second time in `get_should_continue`). Each time, it returned 2 'new' records,
+ # even though the resultCount indicated there should only be 2 records total.
+ assert get_mock.call_count == 4
+ # process_mock should only have been called once. We raise an error when getting the
+ # second batch as soon as it is detected that we've processed too many records.
+ assert process_mock.call_count == 1
+
+
+def test_ingest_records_does_not_raise_when_should_raise_error_is_false():
+ # Test that no error is raised when we keep receiving data in excess of the
+ # stated resultCount, if `should_raise_error` is explicitly disabled.
+ ingester = MockTimeDelineatedProviderDataIngester(date=FROZEN_DATE)
+ ingester.should_raise_error = False
+
+ with (
+ patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
+ patch.object(ingester, "get_batch_data") as get_mock,
+ patch.object(ingester, "get_record_count_from_response") as count_mock,
+ patch.object(ingester, "process_batch", return_value=2) as process_mock,
+ patch.object(ingester, "get_response_json", return_value={MagicMock()}),
+ ):
+ ts_mock.return_value = [
+ (
+ datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 1, 12, 0, tzinfo=timezone.utc),
+ ),
+ ]
+
+ # Mock the API response to indicate that the total result count is 2
+ count_mock.return_value = 2
+
+ mock_response = {
+ "status": "ok",
+ "records": [MagicMock(), MagicMock()], # Two mock records,
+ }
+ # Mock the calls to get_batch_data in order. For each batch, it is
+ # called once to get the batch data, and a second time in
+ # `get_should_continue`.
+ get_mock.side_effect = [
+ # Two calls for the first batch, which ingests 2 records
+ mock_response,
+ mock_response,
+ # Two calls for the second batch, which ingests 2 more records.
+ # We have now exceeded the count reported by the API
+ mock_response,
+ mock_response,
+ # A third batch is requested even though the count is exceeded.
+ # We make it an empty batch in order to halt ingestion
+ None,
+ None,
+ ]
+
+ ingester.ingest_records()
+
+ # get_mock should have been called 6 times, for each of the calls described
+ # above
+ assert get_mock.call_count == 6
+ # process_mock should only have been called twice, once for each non-empty batch.
+ # We did not raise an error and allowed ingestion to continue.
+ assert process_mock.call_count == 2