Skip to content

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

Generate TSV filenames in separate step (#620)

Madison Swain-Bowden8754cb63c075
diff --git a/openverse_catalog/dags/common/constants.py b/openverse_catalog/dags/common/constants.py
index db3a5e8ef..e4fc08ad4 100644
--- a/openverse_catalog/dags/common/constants.py
+++ b/openverse_catalog/dags/common/constants.py
@@ -1,5 +1,6 @@
import os
from datetime import datetime, timedelta
+from typing import Literal
from common import slack
@@ -8,6 +9,8 @@ AUDIO = "audio"
IMAGE = "image"
MEDIA_TYPES = [AUDIO, IMAGE]
+MediaType = Literal["audio", "image"]
+
DAG_DEFAULT_ARGS = {
"owner": "data-eng-admin",
"depends_on_past": False,
diff --git a/openverse_catalog/dags/providers/factory_utils.py b/openverse_catalog/dags/providers/factory_utils.py
new file mode 100644
index 000000000..6bbf1fb36
--- /dev/null
+++ b/openverse_catalog/dags/providers/factory_utils.py
@@ -0,0 +1,140 @@
+import inspect
+import logging
+import time
+from types import FunctionType
+from typing import Callable, Sequence
+
+from airflow.models import TaskInstance
+from common.constants import MediaType
+from common.storage.media import MediaStore
+
+
+logger = logging.getLogger(__name__)
+
+
+def _load_provider_script_stores(
+ ingestion_callable: Callable,
+ media_types: list[MediaType],
+ **kwargs,
+) -> dict[str, MediaStore]:
+ """
+ Load the stores associated with a provided ingestion callable. This callable is
+ assumed to be a legacy provider script and NOT a provider data ingestion class.
+ """
+ # Stores exist at the module level, so in order to retrieve the output values we
+ # must first pull the stores from the module.
+ module = inspect.getmodule(ingestion_callable)
+ stores = {}
+ for media_type in media_types:
+ store = getattr(module, f"{media_type}_store", None)
+ if not store:
+ continue
+ stores[media_type] = store
+
+ if len(stores) != len(media_types):
+ raise ValueError(
+ f"Expected stores in {module.__name__} were missing: "
+ f"{list(set(media_types) - set(stores))}"
+ )
+ return stores
+
+
+def generate_tsv_filenames(
+ ingestion_callable: Callable,
+ media_types: list[MediaType],
+ ti: TaskInstance,
+ args: Sequence = None,
+) -> None:
+ """
+ Calculate the output directories for each media store to XComs. Output locations
+ are pushed under keys with the format `<media-type>_tsv`. This is a temporary
+ workaround due to the nature of the current provider scripts. Once
+ https://github.com/WordPress/openverse-catalog/issues/229 is addressed and the
+ provider scripts are refactored into classes, we can alter the process by which
+ MediaStores create/set their output directory so that they are always expected
+ to receive it.
+ """
+ args = args or []
+ logger.info("Pushing available store paths to XComs")
+
+ # TODO: This entire branch can be removed when all of the provider scripts have been
+ # TODO: refactored to subclass ProviderDataIngester.
+ if isinstance(ingestion_callable, FunctionType):
+ stores = _load_provider_script_stores(ingestion_callable, media_types)
+
+ else:
+ # A ProviderDataIngester class was passed instead. First we initialize the
+ # class, which will initialize the media stores and DelayedRequester.
+ logger.info(
+ f"Initializing ProviderIngester {ingestion_callable.__name__} in"
+ f"order to generate store filenames."
+ )
+ ingester = ingestion_callable(*args)
+ stores = ingester.media_stores
+
+ # Push the media store output paths to XComs.
+ for store in stores.values():
+ logger.info(
+ f"{store.media_type.capitalize()} store location: {store.output_path}"
+ )
+ ti.xcom_push(key=f"{store.media_type}_tsv", value=store.output_path)
+
+
+def pull_media_wrapper(
+ ingestion_callable: Callable,
+ media_types: list[MediaType],
+ tsv_filenames: list[str],
+ ti: TaskInstance,
+ args: Sequence = None,
+):
+ """
+ Run the provided callable after pushing setting the output directories
+ for each media store using the provided values. This is a temporary workaround
+ due to the nature of the current provider scripts. Once
+ https://github.com/WordPress/openverse-catalog/issues/229 is addressed and the
+ provider scripts are refactored into classes, this wrapper can either be updated
+ or the output filename retrieval/setting process can be altered.
+ """
+ args = args or []
+ if len(media_types) != len(tsv_filenames):
+ raise ValueError(
+ "Provided media types and TSV filenames don't match: "
+ f"{media_types=} {tsv_filenames=}"
+ )
+ logger.info("Setting media stores to the appropriate output filenames")
+
+ # TODO: This entire branch can be removed when all of the provider scripts have been
+ # TODO: refactored to subclass ProviderDataIngester.
+ if isinstance(ingestion_callable, FunctionType):
+ # Stores exist at the module level, so in order to set the output values we
+ # must first pull the stores from the module.
+ stores = _load_provider_script_stores(ingestion_callable, media_types)
+ run_func = ingestion_callable
+ else:
+ # A ProviderDataIngester class was passed instead. First we initialize the
+ # class, which will initialize the media stores and DelayedRequester.
+ logger.info(f"Initializing ProviderIngester {ingestion_callable.__name__}")
+ ingester = ingestion_callable(*args)
+ stores = ingester.media_stores
+ run_func = ingester.ingest_records
+ # args have already been passed into the ingester, we don't need them passed
+ # in again to the ingest_records function, so we clear the list
+ args = []
+
+ for store, tsv_filename in zip(stores.values(), tsv_filenames):
+ logger.info(
+ f"Setting {store.media_type.capitalize()} store location "
+ f"to {tsv_filename}"
+ )
+ store.output_path = tsv_filename
+
+ logger.info("Beginning ingestion")
+ start_time = time.perf_counter()
+ # Not passing kwargs here because Airflow throws a bunch of stuff in there that
+ # none of our provider scripts are expecting.
+ data = run_func(*args)
+ end_time = time.perf_counter()
+ # Report duration
+ duration = end_time - start_time
+ ti.xcom_push(key="duration", value=duration)
+ return data
diff --git a/openverse_catalog/dags/providers/provider_dag_factory.py b/openverse_catalog/dags/providers/provider_dag_factory.py
index 6d4cd2004..ee83c2184 100644
--- a/openverse_catalog/dags/providers/provider_dag_factory.py
+++ b/openverse_catalog/dags/providers/provider_dag_factory.py
@@ -51,16 +51,12 @@ https://github.com/creativecommons/cccatalog/issues/333)
- [DB Loader should take data from S3, rather than EC2 to load into PostgreSQL](
https://github.com/creativecommons/cccatalog/issues/334)
"""
-import inspect
import logging
import os
-import time
from datetime import datetime, timedelta
-from types import FunctionType
-from typing import Callable, Dict, List, Optional, Sequence
+from typing import Callable, Dict, Optional, Sequence
from airflow import DAG
-from airflow.models import TaskInstance
from airflow.models.baseoperator import cross_downstream
from airflow.operators.empty import EmptyOperator
from airflow.operators.python import PythonOperator
@@ -68,6 +64,7 @@ from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
from common.constants import DAG_DEFAULT_ARGS, XCOM_PULL_TEMPLATE
from common.loader import loader, reporting, s3, sql
+from providers.factory_utils import generate_tsv_filenames, pull_media_wrapper
logger = logging.getLogger(__name__)
@@ -80,82 +77,6 @@ OUTPUT_DIR_PATH = os.path.realpath(os.getenv("OUTPUT_DIR", "/tmp/"))
DATE_RANGE_ARG_TEMPLATE = "{{{{ macros.ds_add(ds, -{}) }}}}"
-def _push_output_paths_wrapper(
- ingestion_callable: Callable,
- media_types: List[str],
- ti: TaskInstance,
- args: Sequence = None,
-):
- """
- Run the provided callable after pushing the calculated output directories
- for each media store to XComs. Output locations are pushed under keys with
- the format `<media-type>_tsv`. This is a temporary workaround due to the nature
- of the current provider scripts. Once
- https://github.com/WordPress/openverse-catalog/issues/229 is addressed and the
- provider scripts are refactored into classes, this wrapper can either be updated
- or the XCom pushing can be moved into the provider initialization.
- """
- args = args or []
- logger.info("Pushing available store paths to XComs")
-
- # TODO: This entire branch can be removed when all of the provider scripts have been
- # refactored to subclass ProviderDataIngester.
- if isinstance(ingestion_callable, FunctionType):
- # Stores exist at the module level, so in order to retrieve the output values we
- # must first pull the stores from the module.
- module = inspect.getmodule(ingestion_callable)
- stores = {}
- for media_type in media_types:
- store = getattr(module, f"{media_type}_store", None)
- if not store:
- continue
- stores[media_type] = store
-
- if len(stores) != len(media_types):
- raise ValueError(
- f"Expected stores in {module.__name__} were missing: "
- f"{list(set(media_types) - set(stores))}"
- )
-
- for media_type, store in stores.items():
- logger.info(
- f"{media_type.capitalize()} store location: {store.output_path}"
- )
- ti.xcom_push(key=f"{media_type}_tsv", value=store.output_path)
-
- logger.info("Running provider function")
-
- start_time = time.perf_counter()
- # Not passing kwargs here because Airflow throws a bunch of stuff in there that
- # none of our provider scripts are expecting.
- data = ingestion_callable(*args)
- end_time = time.perf_counter()
-
- else:
- # A ProviderDataIngester class was passed instead. First we initialize the
- # class, which will initialize the media stores and DelayedRequester.
- logger.info(f"Initializing ProviderIngester {ingestion_callable.__name__}")
- ingester = ingestion_callable(*args)
-
- # Push the media store output directories to XComs.
- for store in ingester.media_stores.values():
- logger.info(
- f"{store.media_type.capitalize()} store location: {store.output_path}"
- )
- ti.xcom_push(key=f"{store.media_type}_tsv", value=store.output_path)
-
- # Run the `ingest_records` function to perform ingestion.
- logger.info("Running ingestion function")
- start_time = time.perf_counter()
- data = ingester.ingest_records(*args)
- end_time = time.perf_counter()
-
- # Report duration
- duration = end_time - start_time
- ti.xcom_push(key="duration", value=duration)
- return data
-
-
def create_provider_api_workflow(
dag_id: str,
ingestion_callable: Callable,
@@ -230,17 +151,32 @@ def create_provider_api_workflow(
)
with dag:
- pull_kwargs = {
+ ingestion_kwargs = {
"ingestion_callable": ingestion_callable,
"media_types": media_types,
}
if dated:
- pull_kwargs["args"] = [DATE_RANGE_ARG_TEMPLATE.format(day_shift)]
+ ingestion_kwargs["args"] = [DATE_RANGE_ARG_TEMPLATE.format(day_shift)]
+
+ generate_filenames = PythonOperator(
+ task_id=f"generate_{media_type_name}_filename",
+ python_callable=generate_tsv_filenames,
+ op_kwargs=ingestion_kwargs,
+ )
pull_data = PythonOperator(
task_id=f"pull_{media_type_name}_data",
- python_callable=_push_output_paths_wrapper,
- op_kwargs=pull_kwargs,
+ python_callable=pull_media_wrapper,
+ op_kwargs={
+ **ingestion_kwargs,
+ # Note: this is assumed to match the order of media_types exactly
+ "tsv_filenames": [
+ XCOM_PULL_TEMPLATE.format(
+ generate_filenames.task_id, f"{media_type}_tsv"
+ )
+ for media_type in media_types
+ ],
+ },
depends_on_past=False,
execution_timeout=execution_timeout,
# If the data pull fails, we want to load all data that's been retrieved
@@ -269,7 +205,7 @@ def create_provider_api_workflow(
python_callable=s3.copy_file_to_s3,
op_kwargs={
"tsv_file_path": XCOM_PULL_TEMPLATE.format(
- pull_data.task_id, f"{media_type}_tsv"
+ generate_filenames.task_id, f"{media_type}_tsv"
),
"s3_bucket": OPENVERSE_BUCKET,
"s3_prefix": f"{media_type}/{provider_name}",
@@ -323,7 +259,7 @@ def create_provider_api_workflow(
trigger_rule=TriggerRule.ALL_DONE,
)
- pull_data >> load_tasks >> report_load_completion
+ generate_filenames >> pull_data >> load_tasks >> report_load_completion
return dag
@@ -331,7 +267,7 @@ def create_provider_api_workflow(
def create_day_partitioned_ingestion_dag(
dag_id: str,
main_function: Callable,
- reingestion_day_list_list: List[List[int]],
+ reingestion_day_list_list: list[list[int]],
start_date: datetime = datetime(1970, 1, 1),
max_active_runs: int = 1,
max_active_tasks: int = 1,
diff --git a/tests/dags/common/test_provider_dag_factory.py b/tests/dags/common/test_provider_dag_factory.py
deleted file mode 100644
index 1c1c0310e..000000000
--- a/tests/dags/common/test_provider_dag_factory.py
+++ /dev/null
@@ -1,110 +0,0 @@
-from unittest import mock
-
-import pytest
-import requests
-from airflow.models import TaskInstance
-from providers import provider_dag_factory
-
-from tests.dags.common.test_resources import fake_provider_module
-
-
- "func, media_types, stores",
- [
- # Happy path
- (fake_provider_module.main, ["image"], [fake_provider_module.image_store]),
- # Empty case, no media types provided
- (fake_provider_module.main, [], []),
- # Provided function doesn't have a store at the module level
- pytest.param(
- requests.get,
- ["image"],
- [None],
- marks=pytest.mark.raises(
- exception=ValueError, match="Expected stores in .*? were missing.*"
- ),
- ),
- # Provided function doesn't have all specified stores
- pytest.param(
- fake_provider_module.main,
- ["image", "other"],
- [None, None],
- marks=pytest.mark.raises(
- exception=ValueError, match="Expected stores in .*? were missing.*"
- ),
- ),
- ],
-)
-def test_push_output_paths_wrapper(func, media_types, stores):
- ti_mock = mock.MagicMock(spec=TaskInstance)
- # This mock, along with the value, get handed into the provided function.
- # For fake_provider_module.main, the mock will be called with the provided value.
- func_mock = mock.MagicMock()
- value = 42
- provider_dag_factory._push_output_paths_wrapper(
- func,
- media_types,
- ti_mock,
- args=[func_mock, value],
- )
- # There should be one call to xcom_push for each provided store, plus
- # one final call to report the task duration.
- expected_xcoms = len(media_types) + 1
- actual_xcoms = ti_mock.xcom_push.call_count
- assert (
- actual_xcoms == expected_xcoms
- ), f"Expected {expected_xcoms} XComs but {actual_xcoms} pushed"
- for args, store in zip(ti_mock.xcom_push.mock_calls[:-1], stores):
- assert args.kwargs["value"] == store.output_path
- # Check that the duration was reported
- assert ti_mock.xcom_push.mock_calls[-1].kwargs["key"] == "duration"
-
- # Check that the function itself was called with the provided args
- func_mock.assert_called_once_with(value)
-
-
-def test_create_day_partitioned_ingestion_dag_with_single_layer_dependencies():
- dag = provider_dag_factory.create_day_partitioned_ingestion_dag(
- "test_dag",
- print,
- [[1, 2]],
- )
- today_id = "ingest_0"
- wait0_id = "wait_L0"
- ingest1_id = "ingest_1"
- ingest2_id = "ingest_2"
- today_task = dag.get_task(today_id)
- assert today_task.upstream_task_ids == set()
- assert today_task.downstream_task_ids == {wait0_id}
- ingest1_task = dag.get_task(ingest1_id)
- assert ingest1_task.upstream_task_ids == {wait0_id}
- ingest2_task = dag.get_task(ingest2_id)
- assert ingest2_task.upstream_task_ids == {wait0_id}
-
-
-def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():
- dag = provider_dag_factory.create_day_partitioned_ingestion_dag(
- "test_dag",
- print,
- [[1, 2], [3, 4, 5]],
- )
- today_id = "ingest_0"
- wait0_id = "wait_L0"
- ingest1_id = "ingest_1"
- ingest2_id = "ingest_2"
- wait1_id = "wait_L1"
- ingest3_id = "ingest_3"
- ingest4_id = "ingest_4"
- ingest5_id = "ingest_5"
- today_task = dag.get_task(today_id)
- assert today_task.upstream_task_ids == set()
- ingest1_task = dag.get_task(ingest1_id)
- assert ingest1_task.upstream_task_ids == {wait0_id}
- ingest2_task = dag.get_task(ingest2_id)
- assert ingest2_task.upstream_task_ids == {wait0_id}
- ingest3_task = dag.get_task(ingest3_id)
- assert ingest3_task.upstream_task_ids == {wait1_id}
- ingest4_task = dag.get_task(ingest4_id)
- assert ingest4_task.upstream_task_ids == {wait1_id}
- ingest5_task = dag.get_task(ingest5_id)
- assert ingest5_task.upstream_task_ids == {wait1_id}
diff --git a/tests/dags/common/test_resources/fake_provider_data_ingester.py b/tests/dags/common/test_resources/fake_provider_data_ingester.py
new file mode 100644
index 000000000..44724e76f
--- /dev/null
+++ b/tests/dags/common/test_resources/fake_provider_data_ingester.py
@@ -0,0 +1,29 @@
+"""
+This is a fake provider module used in test_dag_factory.
+It is used to check that the output path acquisition logic is correct.
+"""
+from typing import Dict, List, Optional
+
+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
+
+
+class FakeDataIngester(ProviderDataIngester):
+ @property
+ def providers(self) -> dict[str, str]:
+ return {"image": "fake_image", "audio": "fake_audio"}
+
+ @property
+ def endpoint(self):
+ return ""
+
+ def get_next_query_params(self, old_query_params: Optional[Dict], **kwargs) -> Dict:
+ return old_query_params
+
+ def get_batch_data(self, response_json):
+ return None
+
+ def get_media_type(self, record: dict) -> str:
+ return ""
+
+ def get_record_data(self, data: dict) -> dict | List[dict]:
+ return {}
diff --git a/tests/dags/common/test_resources/fake_provider_module.py b/tests/dags/common/test_resources/fake_provider_module.py
index 761c180b3..811ca852e 100644
--- a/tests/dags/common/test_resources/fake_provider_module.py
+++ b/tests/dags/common/test_resources/fake_provider_module.py
@@ -2,10 +2,12 @@
This is a fake provider module used in test_dag_factory.
It is used to check that the output path acquisition logic is correct.
"""
+from common.storage.audio import AudioStore
from common.storage.image import ImageStore
image_store = ImageStore()
+audio_store = AudioStore()
def main(mock, value):
diff --git a/tests/dags/providers/test_factory_utils.py b/tests/dags/providers/test_factory_utils.py
new file mode 100644
index 000000000..033dca880
--- /dev/null
+++ b/tests/dags/providers/test_factory_utils.py
@@ -0,0 +1,210 @@
+from unittest import mock
+
+import pytest
+import requests
+from airflow.models import TaskInstance
+from providers import factory_utils
+
+from tests.dags.common.test_resources import fake_provider_module
+from tests.dags.common.test_resources.fake_provider_data_ingester import (
+ FakeDataIngester,
+)
+
+
+def ti_mock() -> TaskInstance:
+ return mock.MagicMock(spec=TaskInstance)
+
+
+def internal_func_mock():
+ """
+ This mock, along with the value, get handed into the provided function.
+ For fake_provider_module.main, the mock will be called with the provided value.
+ """
+ return mock.MagicMock()
+
+
+fdi = FakeDataIngester()
+
+
+def _set_up_ingester(mock_func, value):
+ """
+ Set up ingest records as a proxy for calling the mock function, then return
+ the instance. This is necessary because the args are only handed in during
+ instance initialization, *not* while calling ingest_records.
+
+ This also effectively checks that ingest_records does not receive the `*args` passed
+ into pull_media_wrapper, since this lambda doesn't accept any arguments!
+ """
+ fdi.ingest_records = lambda: mock_func(value)
+ return fdi
+
+
+# We have to pass a class down into the various functions, but we want to access
+# entities inside the produced object (e.g. stores) in order to test that they
+# were altered correctly. Best way to do that is to set up a mock that just returns
+# the class when called.
+FakeDataIngesterClass = mock.MagicMock()
+FakeDataIngesterClass.__name__ = "FakeDataIngesterClass"
+FakeDataIngesterClass.side_effect = _set_up_ingester
+
+
+ "func, media_types, stores",
+ [
+ # Happy path
+ (fake_provider_module.main, ["image"], [fake_provider_module.image_store]),
+ # Empty case, no media types provided
+ (fake_provider_module.main, [], []),
+ # Provided function doesn't have a store at the module level
+ pytest.param(
+ requests.get,
+ ["image"],
+ [None],
+ marks=pytest.mark.raises(
+ exception=ValueError, match="Expected stores in .*? were missing.*"
+ ),
+ ),
+ # Provided function doesn't have all specified stores
+ pytest.param(
+ fake_provider_module.main,
+ ["image", "other"],
+ [None, None],
+ marks=pytest.mark.raises(
+ exception=ValueError, match="Expected stores in .*? were missing.*"
+ ),
+ ),
+ ],
+)
+def test_load_provider_script(func, media_types, stores):
+ actual_stores = factory_utils._load_provider_script_stores(
+ func,
+ media_types,
+ )
+ assert actual_stores == dict(zip(media_types, stores))
+
+
+ "func, media_types, stores",
+ [
+ ##################################################
+ # Function-based
+ ##################################################
+ # Happy path
+ (fake_provider_module.main, ["image"], [fake_provider_module.image_store]),
+ # Multiple types
+ (
+ fake_provider_module.main,
+ ["image", "audio"],
+ [fake_provider_module.image_store, fake_provider_module.audio_store],
+ ),
+ # Empty case, no media types provided
+ (fake_provider_module.main, [], []),
+ ##################################################
+ # Class-based
+ ##################################################
+ # Happy path
+ (FakeDataIngesterClass, ["image", "audio"], list(fdi.media_stores.values())),
+ # No media types provided, ingester class still supplies stores
+ (FakeDataIngesterClass, 2, list(fdi.media_stores.values())),
+ ],
+)
+def test_generate_tsv_filenames(func, media_types, stores, ti_mock, internal_func_mock):
+ value = 42
+ factory_utils.generate_tsv_filenames(
+ func,
+ media_types,
+ ti_mock,
+ args=[internal_func_mock, value],
+ )
+ # There should be one call to xcom_push for each provided store
+ # If the media_types value is an int, use that for the expected xcoms test
+ expected_xcoms = len(media_types) if isinstance(media_types, list) else media_types
+ actual_xcoms = ti_mock.xcom_push.call_count
+ assert (
+ actual_xcoms == expected_xcoms
+ ), f"Expected {expected_xcoms} XComs but {actual_xcoms} pushed"
+ for args, store in zip(ti_mock.xcom_push.mock_calls[:-1], stores):
+ assert args.kwargs["value"] == store.output_path
+
+ # Check that the function itself was NOT called with the provided args
+ internal_func_mock.assert_not_called()
+
+
+ "func, media_types, tsv_filenames, stores",
+ [
+ ##################################################
+ # Function-based
+ ##################################################
+ # Happy path
+ (
+ fake_provider_module.main,
+ ["image"],
+ ["image_file_000.tsv"],
+ [fake_provider_module.image_store],
+ ),
+ # Multiple types
+ (
+ fake_provider_module.main,
+ ["image", "audio"],
+ ["image_file_000.tsv", "audio_file_111.tsv"],
+ [fake_provider_module.image_store, fake_provider_module.audio_store],
+ ),
+ # Empty case, no media types provided
+ (fake_provider_module.main, [], [], []),
+ # Fails if a mismatched # of items is provided
+ pytest.param(
+ fake_provider_module.main,
+ ["image", "other"],
+ ["file1.tsv"],
+ [fake_provider_module.image_store, fake_provider_module.audio_store],
+ marks=pytest.mark.raises(
+ exception=ValueError,
+ match="Provided media types and TSV filenames don't match.*",
+ ),
+ ),
+ pytest.param(
+ fake_provider_module.main,
+ ["image"],
+ ["file1.tsv", "file2.tsv"],
+ [fake_provider_module.image_store],
+ marks=pytest.mark.raises(
+ exception=ValueError,
+ match="Provided media types and TSV filenames don't match.*",
+ ),
+ ),
+ ##################################################
+ # Class-based
+ ##################################################
+ # Happy path
+ (
+ FakeDataIngesterClass,
+ ["image", "audio"],
+ ["image_file_000.tsv", "audio_file_111.tsv"],
+ list(fdi.media_stores.values()),
+ ),
+ ],
+)
+def test_pull_media_wrapper(
+ func, media_types, tsv_filenames, stores, ti_mock, internal_func_mock
+):
+ value = 42
+ factory_utils.pull_media_wrapper(
+ func,
+ media_types,
+ tsv_filenames,
+ ti_mock,
+ args=[internal_func_mock, value],
+ )
+ # We should have one XCom push for duration
+ assert ti_mock.xcom_push.call_count == 1
+ # Check that the duration was reported
+ assert ti_mock.xcom_push.mock_calls[0].kwargs["key"] == "duration"
+ # Check that the output paths for the stores were changed to the provided filenames
+ for filename, store in zip(tsv_filenames, stores):
+ assert store.output_path == filename
+
+ # Check that the function itself was called with the provided args
+ internal_func_mock.assert_called_once_with(value)
diff --git a/tests/dags/providers/test_provider_dag_factory.py b/tests/dags/providers/test_provider_dag_factory.py
new file mode 100644
index 000000000..605cceaad
--- /dev/null
+++ b/tests/dags/providers/test_provider_dag_factory.py
@@ -0,0 +1,48 @@
+from providers import provider_dag_factory
+
+
+def test_create_day_partitioned_ingestion_dag_with_single_layer_dependencies():
+ dag = provider_dag_factory.create_day_partitioned_ingestion_dag(
+ "test_dag",
+ print,
+ [[1, 2]],
+ )
+ today_id = "ingest_0"
+ wait0_id = "wait_L0"
+ ingest1_id = "ingest_1"
+ ingest2_id = "ingest_2"
+ today_task = dag.get_task(today_id)
+ assert today_task.upstream_task_ids == set()
+ assert today_task.downstream_task_ids == {wait0_id}
+ ingest1_task = dag.get_task(ingest1_id)
+ assert ingest1_task.upstream_task_ids == {wait0_id}
+ ingest2_task = dag.get_task(ingest2_id)
+ assert ingest2_task.upstream_task_ids == {wait0_id}
+
+
+def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():
+ dag = provider_dag_factory.create_day_partitioned_ingestion_dag(
+ "test_dag",
+ print,
+ [[1, 2], [3, 4, 5]],
+ )
+ today_id = "ingest_0"
+ wait0_id = "wait_L0"
+ ingest1_id = "ingest_1"
+ ingest2_id = "ingest_2"
+ wait1_id = "wait_L1"
+ ingest3_id = "ingest_3"
+ ingest4_id = "ingest_4"
+ ingest5_id = "ingest_5"
+ today_task = dag.get_task(today_id)
+ assert today_task.upstream_task_ids == set()
+ ingest1_task = dag.get_task(ingest1_id)
+ assert ingest1_task.upstream_task_ids == {wait0_id}
+ ingest2_task = dag.get_task(ingest2_id)
+ assert ingest2_task.upstream_task_ids == {wait0_id}
+ ingest3_task = dag.get_task(ingest3_id)
+ assert ingest3_task.upstream_task_ids == {wait1_id}
+ ingest4_task = dag.get_task(ingest4_id)
+ assert ingest4_task.upstream_task_ids == {wait1_id}
+ ingest5_task = dag.get_task(ingest5_id)
+ assert ingest5_task.upstream_task_ids == {wait1_id}