Skip to content

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

Finnish DAG: Dynamically generate timeslices depending on the amount of records (#934)

Staci Mullins106e256edb48
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 84759bb90..797f8ca6a 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/finnish_museums.py
@@ -18,6 +18,7 @@ import logging
from datetime import datetime, timedelta, timezone
from itertools import chain
+from airflow.exceptions import AirflowException
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
@@ -33,7 +34,6 @@ LANDING_URL = "https://www.finna.fi/Record/"
PROVIDER = prov.FINNISH_DEFAULT_PROVIDER
SUB_PROVIDERS = prov.FINNISH_SUB_PROVIDERS
-BUILDINGS = ["0/Suomen kansallismuseo/", "0/Museovirasto/", "0/SATMUSEO/", "0/SA-kuva/"]
class FinnishMuseumsDataIngester(ProviderDataIngester):
@@ -42,54 +42,153 @@ class FinnishMuseumsDataIngester(ProviderDataIngester):
batch_limit = 100
delay = 5
format_type = "0/Image/"
+ buildings = [
+ "0/Suomen kansallismuseo/",
+ "0/Museovirasto/",
+ "0/SATMUSEO/",
+ "0/SA-kuva/",
+ ]
def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- # A flag that is turned on each time we start ingestion for a new set of
- # query params. This is useful for logging information on only the first
- # batch of each set.
+ """
+ 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
- # Build the list of timestamp pairs once, so they can be reused for each
- # building queried.
- self.timestamp_pairs = self._get_timestamp_query_params_list(self.date)
+ super().__init__(*args, **kwargs)
+
+ @staticmethod
+ def format_ts(timestamp):
+ return timestamp.isoformat().replace("+00:00", "Z")
@staticmethod
- def _get_timestamp_query_params_list(date):
+ def _get_timestamp_query_params_list(
+ start_date: datetime, end_date: datetime, number_of_divisions: int
+ ) -> list[tuple[datetime, datetime]]:
"""
- The Finnish Museums API behaves 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, we build a list of timestamp pairs that divide
- the ingestion date into equal portions of the 24-hour period, and run
- ingestion separately for each time slice.
+ 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.
"""
- # Get the logical date for the DagRun
- utc_date = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
-
- seconds_in_a_day = 86400
- number_of_divisions = 48 # Half-hour increments
- portion = int(seconds_in_a_day / number_of_divisions)
-
- def _format_timestamp(d):
- return d.isoformat().replace("+00:00", "Z")
+ 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 half-hour 'slice' of the day
- pair_list = [
+ # Generate the start/end timestamps for each 'slice' of the interval
+ return [
(
- _format_timestamp(utc_date + timedelta(seconds=i * portion)),
- _format_timestamp(utc_date + timedelta(seconds=(i + 1) * portion)),
+ start_date + timedelta(seconds=i * portion),
+ start_date + timedelta(seconds=(i + 1) * portion),
)
for i in range(number_of_divisions)
]
- return pair_list
+
+ 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):
+ """
+ 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
def ingest_records(self, **kwargs):
- for building in BUILDINGS:
+ for building in self.buildings:
logger.info(f"Obtaining images of building {building}")
- for start_ts, end_ts in self.timestamp_pairs:
+ # 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(
@@ -99,8 +198,8 @@ class FinnishMuseumsDataIngester(ProviderDataIngester):
def get_next_query_params(self, prev_query_params, **kwargs):
if not prev_query_params:
building = kwargs.get("building")
- start_ts = kwargs.get("start_ts")
- end_ts = kwargs.get("end_ts")
+ start_ts = self.format_ts(kwargs.get("start_ts"))
+ end_ts = self.format_ts(kwargs.get("end_ts"))
return {
"filter[]": [
@@ -125,10 +224,26 @@ 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:
- logger.info(f"Detected {response_json['resultCount']} total records.")
+ # 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/tests/dags/providers/provider_api_scripts/test_finnish_museums.py b/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
index 56acdf5be..bbe8ec5fa 100644
--- a/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
+++ b/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
@@ -1,8 +1,12 @@
import json
import logging
import os
+from datetime import datetime, timedelta, timezone
+from itertools import repeat
+from unittest.mock import MagicMock, 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
@@ -18,6 +22,9 @@ logging.basicConfig(
)
FROZEN_DATE = "2020-04-01"
+FROZEN_UTC_DATE = datetime.strptime(FROZEN_DATE, "%Y-%m-%d").replace(
+ tzinfo=timezone.utc
+)
fm = FinnishMuseumsDataIngester(date=FROZEN_DATE)
image_store = ImageStore(provider=prov.FINNISH_DEFAULT_PROVIDER)
fm.media_stores = {"image": image_store}
@@ -29,74 +36,207 @@ def _get_resource_json(json_name):
return resource_json
-def test_get_timestamp_query_params_list():
- actual_list = fm._get_timestamp_query_params_list(FROZEN_DATE)
- # Expected timestamp list from splitting the FROZEN_DATE into 48 segments
- expected_list = [
- ("2020-04-01T00:00:00Z", "2020-04-01T00:30:00Z"),
- ("2020-04-01T00:30:00Z", "2020-04-01T01:00:00Z"),
- ("2020-04-01T01:00:00Z", "2020-04-01T01:30:00Z"),
- ("2020-04-01T01:30:00Z", "2020-04-01T02:00:00Z"),
- ("2020-04-01T02:00:00Z", "2020-04-01T02:30:00Z"),
- ("2020-04-01T02:30:00Z", "2020-04-01T03:00:00Z"),
- ("2020-04-01T03:00:00Z", "2020-04-01T03:30:00Z"),
- ("2020-04-01T03:30:00Z", "2020-04-01T04:00:00Z"),
- ("2020-04-01T04:00:00Z", "2020-04-01T04:30:00Z"),
- ("2020-04-01T04:30:00Z", "2020-04-01T05:00:00Z"),
- ("2020-04-01T05:00:00Z", "2020-04-01T05:30:00Z"),
- ("2020-04-01T05:30:00Z", "2020-04-01T06:00:00Z"),
- ("2020-04-01T06:00:00Z", "2020-04-01T06:30:00Z"),
- ("2020-04-01T06:30:00Z", "2020-04-01T07:00:00Z"),
- ("2020-04-01T07:00:00Z", "2020-04-01T07:30:00Z"),
- ("2020-04-01T07:30:00Z", "2020-04-01T08:00:00Z"),
- ("2020-04-01T08:00:00Z", "2020-04-01T08:30:00Z"),
- ("2020-04-01T08:30:00Z", "2020-04-01T09:00:00Z"),
- ("2020-04-01T09:00:00Z", "2020-04-01T09:30:00Z"),
- ("2020-04-01T09:30:00Z", "2020-04-01T10:00:00Z"),
- ("2020-04-01T10:00:00Z", "2020-04-01T10:30:00Z"),
- ("2020-04-01T10:30:00Z", "2020-04-01T11:00:00Z"),
- ("2020-04-01T11:00:00Z", "2020-04-01T11:30:00Z"),
- ("2020-04-01T11:30:00Z", "2020-04-01T12:00:00Z"),
- ("2020-04-01T12:00:00Z", "2020-04-01T12:30:00Z"),
- ("2020-04-01T12:30:00Z", "2020-04-01T13:00:00Z"),
- ("2020-04-01T13:00:00Z", "2020-04-01T13:30:00Z"),
- ("2020-04-01T13:30:00Z", "2020-04-01T14:00:00Z"),
- ("2020-04-01T14:00:00Z", "2020-04-01T14:30:00Z"),
- ("2020-04-01T14:30:00Z", "2020-04-01T15:00:00Z"),
- ("2020-04-01T15:00:00Z", "2020-04-01T15:30:00Z"),
- ("2020-04-01T15:30:00Z", "2020-04-01T16:00:00Z"),
- ("2020-04-01T16:00:00Z", "2020-04-01T16:30:00Z"),
- ("2020-04-01T16:30:00Z", "2020-04-01T17:00:00Z"),
- ("2020-04-01T17:00:00Z", "2020-04-01T17:30:00Z"),
- ("2020-04-01T17:30:00Z", "2020-04-01T18:00:00Z"),
- ("2020-04-01T18:00:00Z", "2020-04-01T18:30:00Z"),
- ("2020-04-01T18:30:00Z", "2020-04-01T19:00:00Z"),
- ("2020-04-01T19:00:00Z", "2020-04-01T19:30:00Z"),
- ("2020-04-01T19:30:00Z", "2020-04-01T20:00:00Z"),
- ("2020-04-01T20:00:00Z", "2020-04-01T20:30:00Z"),
- ("2020-04-01T20:30:00Z", "2020-04-01T21:00:00Z"),
- ("2020-04-01T21:00:00Z", "2020-04-01T21:30:00Z"),
- ("2020-04-01T21:30:00Z", "2020-04-01T22:00:00Z"),
- ("2020-04-01T22:00:00Z", "2020-04-01T22:30:00Z"),
- ("2020-04-01T22:30:00Z", "2020-04-01T23:00:00Z"),
- ("2020-04-01T23:00:00Z", "2020-04-01T23:30:00Z"),
- ("2020-04-01T23:30:00Z", "2020-04-02T00:00:00Z"),
+ "response_json, expected_count",
+ [
+ # Happy path
+ ({"resultCount": 20}, 20),
+ # Defaults to 0
+ (None, 0),
+ ({}, 0),
+ ],
+)
+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"
+ )
+ 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),
+ )
]
- assert actual_list == expected_list
+
+ 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,
building="0/Museovirasto/",
- start_ts="2020-04-01T00:30:00Z",
- end_ts="2020-04-01T01:00:00Z",
+ start_ts=FROZEN_UTC_DATE,
+ end_ts=FROZEN_UTC_DATE + timedelta(days=1),
)
expected_param = {
"filter[]": [
'format:"0/Image/"',
'building:"0/Museovirasto/"',
- 'last_indexed:"[2020-04-01T00:30:00Z TO 2020-04-01T01:00:00Z]"',
+ 'last_indexed:"[2020-04-01T00:00:00Z TO 2020-04-02T00:00:00Z]"',
],
"limit": 100,
"page": 1,