Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Halt ingestion when WordPress Photo Directory reaches last page (#916)
Staci Cooper5933f712d2d0
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/wordpress.py b/openverse_catalog/dags/providers/provider_api_scripts/wordpress.pyindex 9e56fdde3..cead9bdb6 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/wordpress.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/wordpress.py@@ -45,25 +45,49 @@ class WordPressDataIngester(ProviderDataIngester):super().__init__(*args, **kwargs)self.license_info = get_license_info(license_url=self.license_url)+ # Total pages is determined on the first request+ self.total_pages = None+ self.current_page = 1+def get_media_type(self, record: dict) -> str:return constants.IMAGEdef get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:- if not prev_query_params:- return {- "format": "json",- "page": 1,- "per_page": self.batch_limit,- "_embed": "true",- }- else:- return {**prev_query_params, "page": prev_query_params["page"] + 1}+ 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+ # from attempting to access too large a page number.+ # https://github.com/WordPress/openverse-catalog/issues/853+ response = self.delayed_requester.head(+ self.endpoint, params={"per_page": self.batch_limit, "_embed": "true"}+ )+ self.total_pages = int(response.headers.get("X-WP-TotalPages", 0))+ logger.info(f"{self.total_pages} pages detected.")++ # Increment the page number for subsequent batches+ if prev_query_params:+ self.current_page = prev_query_params["page"] + 1++ return {+ "format": "json",+ "page": self.current_page,+ "per_page": self.batch_limit,+ "_embed": "true",+ }def get_batch_data(self, response_json):if isinstance(response_json, list) and len(response_json):return response_jsonreturn None+ def get_should_continue(self, response_json):+ # Do not continue if we have exceeded the total pages+ if self.current_page >= self.total_pages:+ logger.info("The final page of data has been processed. Halting ingestion.")+ return False++ return True+def get_record_data(self, data):"""Extract data for individual item.diff --git a/tests/dags/providers/provider_api_scripts/test_wordpress.py b/tests/dags/providers/provider_api_scripts/test_wordpress.pyindex 3d561e96d..54311bcbd 100644--- a/tests/dags/providers/provider_api_scripts/test_wordpress.py+++ b/tests/dags/providers/provider_api_scripts/test_wordpress.py@@ -1,5 +1,6 @@import jsonfrom pathlib import Path+from unittest.mock import MagicMock, patchimport pytestfrom providers.provider_api_scripts.wordpress import WordPressDataIngester@@ -7,47 +8,85 @@ from providers.provider_api_scripts.wordpress import WordPressDataIngesterRESOURCES = Path(__file__).parent / "resources/wordpress"SAMPLE_MEDIA_DATA = RESOURCES / "full_item.json"-wp = WordPressDataIngester()-def test_get_query_params_returns_defaults():+def ingester() -> WordPressDataIngester:+ wp = WordPressDataIngester()+ wp.total_pages = 50+ return wp+++def test_get_query_params_returns_defaults_and_sets_total_pages():+ # Create a new WordPressDataIngester which does not have `total_pages` set yet+ wp = WordPressDataIngester()++ mock_head_request = MagicMock()+ mock_head_request.headers = {"X-WP-TotalPages": 5}++ # Mock the head request to get the `total_pages`+ with patch.object(wp.delayed_requester, "head", return_value=mock_head_request):+ actual_result = wp.get_next_query_params({})+expected_result = {"format": "json", "page": 1, "per_page": 100, "_embed": "true"}- actual_result = wp.get_next_query_params({})assert actual_result == expected_result+ assert wp.total_pages == 5-def test_get_query_params_returns_next_page():+def test_get_query_params_increments_current_page(ingester):expected_result = {"format": "json", "page": 3, "per_page": 100, "_embed": "true"}- actual_result = wp.get_next_query_params({**expected_result, "page": 2})+ actual_result = ingester.get_next_query_params({**expected_result, "page": 2})assert actual_result == expected_result+ "current_page, should_continue",+ [+ # Note that total_pages is 50+ # the current page is less than total_pages+ (10, True),+ (49, True),+ # the current page is the last page+ (50, False),+ # the current page is after the last page (Note: this should not arise)+ (51, False),+ ],+)+def test_get_should_continue_checks_total_pages(+ ingester, current_page, should_continue+):+ ingester.current_page = current_page+ assert ingester.get_should_continue({}) == should_continue++@pytest.mark.parametrize("missing_field", ["slug", "link"])-def test_get_record_data_returns_none_when_missing_necessary_data(missing_field):+def test_get_record_data_returns_none_when_missing_necessary_data(+ ingester, missing_field+):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)image_data.pop(missing_field, None)- actual_image_info = wp.get_record_data(image_data)+ actual_image_info = ingester.get_record_data(image_data)assert actual_image_info is None-def test_get_record_data_returns_none_when_no_image_url():+def test_get_record_data_returns_none_when_no_image_url(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)image_data["_embedded"]["wp:featuredmedia"][0]["media_details"].pop("sizes")- actual_image_info = wp.get_record_data(image_data)+ actual_image_info = ingester.get_record_data(image_data)assert actual_image_info is None-def test_get_title():+def test_get_title(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)- actual_result = wp._get_title(image_data)+ actual_result = ingester._get_title(image_data)expected_result = "Coffee Bean with bags"assert actual_result == expected_result-def test_get_file_info():+def test_get_file_info(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_details = (json.load(f)@@ -55,7 +94,7 @@ def test_get_file_info():.get("wp:featuredmedia")[0].get("media_details"))- actual_result = wp._get_file_info(image_details)+ actual_result = ingester._get_file_info(image_details)expected_result = ("https://pd.w.org/2022/05/203627f31f8770f03.61535278-2048x1366.jpg", # image_url1366, # height@@ -65,41 +104,41 @@ def test_get_file_info():assert actual_result == expected_result-def test_get_author_data_when_is_non_empty():+def test_get_author_data_when_is_non_empty(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)- actual_author, actual_author_url = wp._get_author_data(image_data)+ actual_author, actual_author_url = ingester._get_author_data(image_data)expected_author = "Shusei Toda"expected_author_url = "https://shuseitoda.com"assert actual_author == expected_authorassert actual_author_url == expected_author_url-def test_get_author_data_handle_no_author():+def test_get_author_data_handle_no_author(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)image_data["_embedded"].pop("author", None)- actual_author, actual_author_url = wp._get_author_data(image_data)+ actual_author, actual_author_url = ingester._get_author_data(image_data)assert actual_author is Noneassert actual_author_url is None-def test_get_author_data_use_slug_when_name_is_empty():+def test_get_author_data_use_slug_when_name_is_empty(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)image_data["_embedded"]["author"][0].pop("name")- actual_author, _ = wp._get_author_data(image_data)+ actual_author, _ = ingester._get_author_data(image_data)expected_author = "st810amaze"assert actual_author == expected_author-def test_get_metadata():+def test_get_metadata(ingester):with open(SAMPLE_MEDIA_DATA) as f:image_data = json.load(f)image_details = (image_data.get("_embedded").get("wp:featuredmedia")[0].get("media_details"))- actual_metadata, actual_tags = wp._get_metadata(image_data, image_details)+ actual_metadata, actual_tags = ingester._get_metadata(image_data, image_details)expected_metadata = {"aperture": "4","camera": "ILCE-7M4",