def execute(self, context): hook = DataflowHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep) hook.start_template_dataflow(job_name=self.job_name, variables=self.dataflow_default_options, parameters=self.parameters, dataflow_template=self.template)
class DataflowTemplatedJobStartOperator(BaseOperator): """ Start a Templated Cloud DataFlow batch job. The parameters of the operation will be passed to the job. :param template: The reference to the DataFlow template. :type template: str :param job_name: The 'jobName' to use when executing the DataFlow template (templated). :param options: Map of job runtime environment options. .. seealso:: For more information on possible configurations, look at the API documentation `https://cloud.google.com/dataflow/pipelines/specifying-exec-params <https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment>`__ :type options: dict :param dataflow_default_options: Map of default job environment options. :type dataflow_default_options: dict :param parameters: Map of job specific parameters for the template. :type parameters: dict :param project_id: Optional, the Google Cloud project ID in which to start a job. If set to None or missing, the default project_id from the Google Cloud connection is used. :type project_id: str :param location: Job location. :type location: str :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :type gcp_conn_id: str :param delegate_to: The account to impersonate using domain-wide delegation of authority, if any. For this to work, the service account making the request must have domain-wide delegation enabled. :type delegate_to: str :param poll_sleep: The time in seconds to sleep between polling Google Cloud Platform for the dataflow job status while the job is in the JOB_STATE_RUNNING state. :type poll_sleep: int :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :type impersonation_chain: Union[str, Sequence[str]] It's a good practice to define dataflow_* parameters in the default_args of the dag like the project, zone and staging location. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3/LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment .. code-block:: python default_args = { 'dataflow_default_options': { 'zone': 'europe-west1-d', 'tempLocation': 'gs://my-staging-bucket/staging/', } } } You need to pass the path to your dataflow template as a file reference with the ``template`` parameter. Use ``parameters`` to pass on parameters to your job. Use ``environment`` to pass on runtime environment variables to your job. .. code-block:: python t1 = DataflowTemplateOperator( task_id='dataflow_example', template='{{var.value.gcp_dataflow_base}}', parameters={ 'inputFile': "gs://bucket/input/my_input.txt", 'outputFile': "gs://bucket/output/my_output.txt" }, gcp_conn_id='airflow-conn-id', dag=my-dag) ``template``, ``dataflow_default_options``, ``parameters``, and ``job_name`` are templated so you can use variables in them. Note that ``dataflow_default_options`` is expected to save high-level options for project information, which apply to all dataflow operators in the DAG. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3 /LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment For more detail on job template execution have a look at the reference: https://cloud.google.com/dataflow/docs/templates/executing-templates """ template_fields = [ 'template', 'job_name', 'options', 'parameters', 'project_id', 'location', 'gcp_conn_id', 'impersonation_chain', ] ui_color = '#0273d4' @apply_defaults def __init__( # pylint: disable=too-many-arguments self, *, template: str, job_name: str = '{{task.task_id}}', options: Optional[Dict[str, Any]] = None, dataflow_default_options: Optional[Dict[str, Any]] = None, parameters: Optional[Dict[str, str]] = None, project_id: Optional[str] = None, location: str = DEFAULT_DATAFLOW_LOCATION, gcp_conn_id: str = 'google_cloud_default', delegate_to: Optional[str] = None, poll_sleep: int = 10, impersonation_chain: Optional[Union[str, Sequence[str]]] = None, **kwargs, ) -> None: super().__init__(**kwargs) self.template = template self.job_name = job_name self.options = options or {} self.dataflow_default_options = dataflow_default_options or {} self.parameters = parameters or {} self.project_id = project_id self.location = location self.gcp_conn_id = gcp_conn_id self.delegate_to = delegate_to self.poll_sleep = poll_sleep self.job_id = None self.hook: Optional[DataflowHook] = None self.impersonation_chain = impersonation_chain def execute(self, context): self.hook = DataflowHook( gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep, impersonation_chain=self.impersonation_chain, ) def set_current_job_id(job_id): self.job_id = job_id options = self.dataflow_default_options options.update(self.options) job = self.hook.start_template_dataflow( job_name=self.job_name, variables=options, parameters=self.parameters, dataflow_template=self.template, on_new_job_id_callback=set_current_job_id, project_id=self.project_id, location=self.location, ) return job def on_kill(self) -> None: self.log.info("On kill.") if self.job_id: self.hook.cancel_job(job_id=self.job_id, project_id=self.project_id)
class DataflowTemplatedJobStartOperator(BaseOperator): """ Start a Templated Cloud Dataflow job. The parameters of the operation will be passed to the job. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataflowTemplatedJobStartOperator` :param template: The reference to the Dataflow template. :param job_name: The 'jobName' to use when executing the Dataflow template (templated). :param options: Map of job runtime environment options. It will update environment argument if passed. .. seealso:: For more information on possible configurations, look at the API documentation `https://cloud.google.com/dataflow/pipelines/specifying-exec-params <https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment>`__ :param dataflow_default_options: Map of default job environment options. :param parameters: Map of job specific parameters for the template. :param project_id: Optional, the Google Cloud project ID in which to start a job. If set to None or missing, the default project_id from the Google Cloud connection is used. :param location: Job location. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param delegate_to: The account to impersonate using domain-wide delegation of authority, if any. For this to work, the service account making the request must have domain-wide delegation enabled. :param poll_sleep: The time in seconds to sleep between polling Google Cloud Platform for the dataflow job status while the job is in the JOB_STATE_RUNNING state. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param environment: Optional, Map of job runtime environment options. .. seealso:: For more information on possible configurations, look at the API documentation `https://cloud.google.com/dataflow/pipelines/specifying-exec-params <https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment>`__ :param cancel_timeout: How long (in seconds) operator should wait for the pipeline to be successfully cancelled when task is being killed. :param wait_until_finished: (Optional) If True, wait for the end of pipeline execution before exiting. If False, only submits job. If None, default behavior. The default behavior depends on the type of pipeline: * for the streaming pipeline, wait for jobs to start, * for the batch pipeline, wait for the jobs to complete. .. warning:: You cannot call ``PipelineResult.wait_until_finish`` method in your pipeline code for the operator to work properly. i. e. you must use asynchronous execution. Otherwise, your pipeline will always wait until finished. For more information, look at: `Asynchronous execution <https://cloud.google.com/dataflow/docs/guides/specifying-exec-params#python_10>`__ The process of starting the Dataflow job in Airflow consists of two steps: * running a subprocess and reading the stderr/stderr log for the job id. * loop waiting for the end of the job ID from the previous step. This loop checks the status of the job. Step two is started just after step one has finished, so if you have wait_until_finished in your pipeline code, step two will not start until the process stops. When this process stops, steps two will run, but it will only execute one iteration as the job will be in a terminal state. If you in your pipeline do not call the wait_for_pipeline method but pass wait_until_finish=True to the operator, the second loop will wait for the job's terminal state. If you in your pipeline do not call the wait_for_pipeline method, and pass wait_until_finish=False to the operator, the second loop will check once is job not in terminal state and exit the loop. It's a good practice to define dataflow_* parameters in the default_args of the dag like the project, zone and staging location. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3/LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment .. code-block:: python default_args = { "dataflow_default_options": { "zone": "europe-west1-d", "tempLocation": "gs://my-staging-bucket/staging/", } } You need to pass the path to your dataflow template as a file reference with the ``template`` parameter. Use ``parameters`` to pass on parameters to your job. Use ``environment`` to pass on runtime environment variables to your job. .. code-block:: python t1 = DataflowTemplatedJobStartOperator( task_id="dataflow_example", template="{{var.value.gcp_dataflow_base}}", parameters={ "inputFile": "gs://bucket/input/my_input.txt", "outputFile": "gs://bucket/output/my_output.txt", }, gcp_conn_id="airflow-conn-id", dag=my - dag, ) ``template``, ``dataflow_default_options``, ``parameters``, and ``job_name`` are templated so you can use variables in them. Note that ``dataflow_default_options`` is expected to save high-level options for project information, which apply to all dataflow operators in the DAG. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3 /LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment For more detail on job template execution have a look at the reference: https://cloud.google.com/dataflow/docs/templates/executing-templates """ template_fields: Sequence[str] = ( "template", "job_name", "options", "parameters", "project_id", "location", "gcp_conn_id", "impersonation_chain", "environment", "dataflow_default_options", ) ui_color = "#0273d4" operator_extra_links = (DataflowJobLink(), ) def __init__( self, *, template: str, job_name: str = "{{task.task_id}}", options: Optional[Dict[str, Any]] = None, dataflow_default_options: Optional[Dict[str, Any]] = None, parameters: Optional[Dict[str, str]] = None, project_id: Optional[str] = None, location: str = DEFAULT_DATAFLOW_LOCATION, gcp_conn_id: str = "google_cloud_default", delegate_to: Optional[str] = None, poll_sleep: int = 10, impersonation_chain: Optional[Union[str, Sequence[str]]] = None, environment: Optional[Dict] = None, cancel_timeout: Optional[int] = 10 * 60, wait_until_finished: Optional[bool] = None, **kwargs, ) -> None: super().__init__(**kwargs) self.template = template self.job_name = job_name self.options = options or {} self.dataflow_default_options = dataflow_default_options or {} self.parameters = parameters or {} self.project_id = project_id self.location = location self.gcp_conn_id = gcp_conn_id self.delegate_to = delegate_to self.poll_sleep = poll_sleep self.job = None self.hook: Optional[DataflowHook] = None self.impersonation_chain = impersonation_chain self.environment = environment self.cancel_timeout = cancel_timeout self.wait_until_finished = wait_until_finished def execute(self, context: 'Context') -> dict: self.hook = DataflowHook( gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep, impersonation_chain=self.impersonation_chain, cancel_timeout=self.cancel_timeout, wait_until_finished=self.wait_until_finished, ) def set_current_job(current_job): self.job = current_job DataflowJobLink.persist(self, context, self.project_id, self.location, self.job.get("id")) options = self.dataflow_default_options options.update(self.options) job = self.hook.start_template_dataflow( job_name=self.job_name, variables=options, parameters=self.parameters, dataflow_template=self.template, on_new_job_callback=set_current_job, project_id=self.project_id, location=self.location, environment=self.environment, ) return job def on_kill(self) -> None: self.log.info("On kill.") if self.job: self.hook.cancel_job( job_id=self.job.get("id"), project_id=self.job.get("projectId"), location=self.job.get("location"), )
class DataflowTemplatedJobStartOperator(BaseOperator): """ Start a Templated Cloud DataFlow batch job. The parameters of the operation will be passed to the job. :param template: The reference to the DataFlow template. :type template: str :param job_name: The 'jobName' to use when executing the DataFlow template (templated). :param dataflow_default_options: Map of default job environment options. :type dataflow_default_options: dict :param parameters: Map of job specific parameters for the template. :type parameters: dict :param project_id: Optional, the GCP project ID in which to start a job. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :param location: Job location. :type location: str :param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform. :type gcp_conn_id: str :param delegate_to: The account to impersonate, if any. For this to work, the service account making the request must have domain-wide delegation enabled. :type delegate_to: str :param poll_sleep: The time in seconds to sleep between polling Google Cloud Platform for the dataflow job status while the job is in the JOB_STATE_RUNNING state. :type poll_sleep: int It's a good practice to define dataflow_* parameters in the default_args of the dag like the project, zone and staging location. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3/LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment .. code-block:: python default_args = { 'dataflow_default_options': { 'zone': 'europe-west1-d', 'tempLocation': 'gs://my-staging-bucket/staging/', } } } You need to pass the path to your dataflow template as a file reference with the ``template`` parameter. Use ``parameters`` to pass on parameters to your job. Use ``environment`` to pass on runtime environment variables to your job. .. code-block:: python t1 = DataflowTemplateOperator( task_id='dataflow_example', template='{{var.value.gcp_dataflow_base}}', parameters={ 'inputFile': "gs://bucket/input/my_input.txt", 'outputFile': "gs://bucket/output/my_output.txt" }, gcp_conn_id='airflow-conn-id', dag=my-dag) ``template``, ``dataflow_default_options``, ``parameters``, and ``job_name`` are templated so you can use variables in them. Note that ``dataflow_default_options`` is expected to save high-level options for project information, which apply to all dataflow operators in the DAG. .. seealso:: https://cloud.google.com/dataflow/docs/reference/rest/v1b3 /LaunchTemplateParameters https://cloud.google.com/dataflow/docs/reference/rest/v1b3/RuntimeEnvironment For more detail on job template execution have a look at the reference: https://cloud.google.com/dataflow/docs/templates/executing-templates """ template_fields = ['parameters', 'dataflow_default_options', 'template', 'job_name'] ui_color = '#0273d4' @apply_defaults def __init__( self, template: str, job_name: str = '{{task.task_id}}', dataflow_default_options: Optional[dict] = None, parameters: Optional[dict] = None, project_id: Optional[str] = None, location: str = DEFAULT_DATAFLOW_LOCATION, gcp_conn_id: str = 'google_cloud_default', delegate_to: Optional[str] = None, poll_sleep: int = 10, *args, **kwargs) -> None: super().__init__(*args, **kwargs) dataflow_default_options = dataflow_default_options or {} parameters = parameters or {} self.template = template self.job_name = job_name self.dataflow_default_options = dataflow_default_options self.parameters = parameters self.project_id = project_id self.location = location self.gcp_conn_id = gcp_conn_id self.delegate_to = delegate_to self.poll_sleep = poll_sleep self.job_id = None self.hook: Optional[DataflowHook] = None def execute(self, context): self.hook = DataflowHook( gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep ) def set_current_job_id(job_id): self.job_id = job_id job = self.hook.start_template_dataflow( job_name=self.job_name, variables=self.dataflow_default_options, parameters=self.parameters, dataflow_template=self.template, on_new_job_id_callback=set_current_job_id, project_id=self.project_id, location=self.location ) return job def on_kill(self) -> None: self.log.info("On kill.") if self.job_id: self.hook.cancel_job(job_id=self.job_id, project_id=self.project_id)
class TestDataflowTemplateHook(unittest.TestCase): def setUp(self): with mock.patch(BASE_STRING.format('CloudBaseHook.__init__'), new=mock_init): self.dataflow_hook = DataflowHook(gcp_conn_id='test') @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow(self, mock_conn, mock_controller, mock_uuid): launch_method = (mock_conn.return_value.projects.return_value. locations.return_value.templates.return_value.launch) launch_method.return_value.execute.return_value = { "job": { "id": TEST_JOB_ID } } self.dataflow_hook.start_template_dataflow( job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_TEMPLATE, parameters=PARAMETERS, dataflow_template=TEMPLATE) options_with_region = {'region': 'us-central1'} options_with_region.update(DATAFLOW_OPTIONS_TEMPLATE) options_with_region_without_project = copy.deepcopy( options_with_region) del options_with_region_without_project['project'] launch_method.assert_called_once_with( body={ 'jobName': 'test-dataflow-pipeline-12345678', 'parameters': PARAMETERS, 'environment': { 'zone': 'us-central1-f', 'tempLocation': 'gs://test/temp' } }, gcsPath='gs://dataflow-templates/wordcount/template_file', location='us-central1', projectId='test') mock_controller.assert_called_once_with( dataflow=mock_conn.return_value, job_id='test-job-id', location='us-central1', name='test-dataflow-pipeline-12345678', num_retries=5, poll_sleep=10, project_number='test') mock_controller.return_value.wait_for_done.assert_called_once() @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow_with_runtime_env(self, mock_conn, mock_dataflowjob, mock_uuid): dataflow_options_template = copy.deepcopy(DATAFLOW_OPTIONS_TEMPLATE) options_with_runtime_env = copy.deepcopy(RUNTIME_ENV) options_with_runtime_env.update(dataflow_options_template) dataflowjob_instance = mock_dataflowjob.return_value dataflowjob_instance.wait_for_done.return_value = None method = (mock_conn.return_value.projects.return_value.locations. return_value.templates.return_value.launch) method.return_value.execute.return_value = {'job': {'id': TEST_JOB_ID}} self.dataflow_hook.start_template_dataflow( job_name=JOB_NAME, variables=options_with_runtime_env, parameters=PARAMETERS, dataflow_template=TEMPLATE) body = { "jobName": mock.ANY, "parameters": PARAMETERS, "environment": RUNTIME_ENV } method.assert_called_once_with( projectId=options_with_runtime_env['project'], location='us-central1', gcsPath=TEMPLATE, body=body, ) mock_dataflowjob.assert_called_once_with( dataflow=mock_conn.return_value, job_id=TEST_JOB_ID, location='us-central1', name='test-dataflow-pipeline-{}'.format(MOCK_UUID), num_retries=5, poll_sleep=10, project_number='test') mock_uuid.assert_called_once_with() @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_cancel_job(self, mock_get_conn, jobs_controller): self.dataflow_hook.cancel_job( job_name=TEST_JOB_NAME, job_id=TEST_JOB_ID, project_id=TEST_PROJECT, ) jobs_controller.assert_called_once_with( dataflow=mock_get_conn.return_value, job_id=TEST_JOB_ID, location='us-central1', name=TEST_JOB_NAME, poll_sleep=10, project_number=TEST_PROJECT) jobs_controller.cancel()
class TestDataflowTemplateHook(unittest.TestCase): def setUp(self): with mock.patch(BASE_STRING.format('CloudBaseHook.__init__'), new=mock_init): self.dataflow_hook = DataflowHook(gcp_conn_id='test') @mock.patch(DATAFLOW_STRING.format('DataflowHook._start_template_dataflow') ) def test_start_template_dataflow(self, internal_dataflow_mock): self.dataflow_hook.start_template_dataflow( job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_TEMPLATE, parameters=PARAMETERS, dataflow_template=TEMPLATE) options_with_region = {'region': 'us-central1'} options_with_region.update(DATAFLOW_OPTIONS_TEMPLATE) options_with_region_without_project = copy.deepcopy( options_with_region) del options_with_region_without_project['project'] internal_dataflow_mock.assert_called_once_with( mock.ANY, options_with_region_without_project, PARAMETERS, TEMPLATE, DATAFLOW_OPTIONS_JAVA['project']) @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow_with_runtime_env(self, mock_conn, mock_dataflowjob, mock_uuid): dataflow_options_template = copy.deepcopy(DATAFLOW_OPTIONS_TEMPLATE) options_with_runtime_env = copy.deepcopy(RUNTIME_ENV) options_with_runtime_env.update(dataflow_options_template) dataflowjob_instance = mock_dataflowjob.return_value dataflowjob_instance.wait_for_done.return_value = None method = (mock_conn.return_value.projects.return_value.locations. return_value.templates.return_value.launch) method.return_value.execute.return_value = {'job': {'id': TEST_JOB_ID}} self.dataflow_hook.start_template_dataflow( job_name=JOB_NAME, variables=options_with_runtime_env, parameters=PARAMETERS, dataflow_template=TEMPLATE) body = { "jobName": mock.ANY, "parameters": PARAMETERS, "environment": RUNTIME_ENV } method.assert_called_once_with( projectId=options_with_runtime_env['project'], location='us-central1', gcsPath=TEMPLATE, body=body, ) mock_dataflowjob.assert_called_once_with( dataflow=mock_conn.return_value, job_id=TEST_JOB_ID, location='us-central1', name='test-dataflow-pipeline-{}'.format(MOCK_UUID), num_retries=5, poll_sleep=10, project_number='test') mock_uuid.assert_called_once_with()
class TestDataflowTemplateHook(unittest.TestCase): def setUp(self): with mock.patch(BASE_STRING.format('GoogleBaseHook.__init__'), new=mock_init): self.dataflow_hook = DataflowHook(gcp_conn_id='test') @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow(self, mock_conn, mock_controller, mock_uuid): launch_method = (mock_conn.return_value.projects.return_value. locations.return_value.templates.return_value.launch) launch_method.return_value.execute.return_value = { "job": { "id": TEST_JOB_ID } } variables = {'zone': 'us-central1-f', 'tempLocation': 'gs://test/temp'} self.dataflow_hook.start_template_dataflow( # pylint: disable=no-value-for-parameter job_name=JOB_NAME, variables=copy.deepcopy(variables), parameters=PARAMETERS, dataflow_template=TEST_TEMPLATE, project_id=TEST_PROJECT, ) launch_method.assert_called_once_with( body={ 'jobName': 'test-dataflow-pipeline-12345678', 'parameters': PARAMETERS, 'environment': variables, }, gcsPath='gs://dataflow-templates/wordcount/template_file', projectId=TEST_PROJECT, location=DEFAULT_DATAFLOW_LOCATION, ) mock_controller.assert_called_once_with( dataflow=mock_conn.return_value, job_id='test-job-id', name='test-dataflow-pipeline-12345678', num_retries=5, poll_sleep=10, project_number=TEST_PROJECT, location=DEFAULT_DATAFLOW_LOCATION, ) mock_controller.return_value.wait_for_done.assert_called_once() @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow_with_custom_region_as_variable( self, mock_conn, mock_controller, mock_uuid): launch_method = (mock_conn.return_value.projects.return_value. locations.return_value.templates.return_value.launch) launch_method.return_value.execute.return_value = { "job": { "id": TEST_JOB_ID } } self.dataflow_hook.start_template_dataflow( # pylint: disable=no-value-for-parameter job_name=JOB_NAME, variables={'region': TEST_LOCATION}, parameters=PARAMETERS, dataflow_template=TEST_TEMPLATE, project_id=TEST_PROJECT, ) launch_method.assert_called_once_with( projectId=TEST_PROJECT, location=TEST_LOCATION, gcsPath=TEST_TEMPLATE, body=mock.ANY, ) mock_controller.assert_called_once_with( dataflow=mock_conn.return_value, job_id=TEST_JOB_ID, name=UNIQUE_JOB_NAME, num_retries=5, poll_sleep=10, project_number=TEST_PROJECT, location=TEST_LOCATION, ) mock_controller.return_value.wait_for_done.assert_called_once() @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow_with_custom_region_as_parameter( self, mock_conn, mock_controller, mock_uuid): launch_method = (mock_conn.return_value.projects.return_value. locations.return_value.templates.return_value.launch) launch_method.return_value.execute.return_value = { "job": { "id": TEST_JOB_ID } } self.dataflow_hook.start_template_dataflow( # pylint: disable=no-value-for-parameter job_name=JOB_NAME, variables={}, parameters=PARAMETERS, dataflow_template=TEST_TEMPLATE, location=TEST_LOCATION, project_id=TEST_PROJECT, ) launch_method.assert_called_once_with( body={ 'jobName': UNIQUE_JOB_NAME, 'parameters': PARAMETERS, 'environment': {} }, gcsPath='gs://dataflow-templates/wordcount/template_file', projectId=TEST_PROJECT, location=TEST_LOCATION, ) mock_controller.assert_called_once_with( dataflow=mock_conn.return_value, job_id=TEST_JOB_ID, name=UNIQUE_JOB_NAME, num_retries=5, poll_sleep=10, project_number=TEST_PROJECT, location=TEST_LOCATION, ) mock_controller.return_value.wait_for_done.assert_called_once() @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'), return_value=MOCK_UUID) @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_start_template_dataflow_with_runtime_env(self, mock_conn, mock_dataflowjob, mock_uuid): options_with_runtime_env = copy.deepcopy(RUNTIME_ENV) dataflowjob_instance = mock_dataflowjob.return_value dataflowjob_instance.wait_for_done.return_value = None # fmt: off method = (mock_conn.return_value.projects.return_value.locations. return_value.templates.return_value.launch) # fmt: on method.return_value.execute.return_value = {'job': {'id': TEST_JOB_ID}} self.dataflow_hook.start_template_dataflow( # pylint: disable=no-value-for-parameter job_name=JOB_NAME, variables=options_with_runtime_env, parameters=PARAMETERS, dataflow_template=TEST_TEMPLATE, project_id=TEST_PROJECT, ) body = { "jobName": mock.ANY, "parameters": PARAMETERS, "environment": RUNTIME_ENV } method.assert_called_once_with( projectId=TEST_PROJECT, location=DEFAULT_DATAFLOW_LOCATION, gcsPath=TEST_TEMPLATE, body=body, ) mock_dataflowjob.assert_called_once_with( dataflow=mock_conn.return_value, job_id=TEST_JOB_ID, location=DEFAULT_DATAFLOW_LOCATION, name='test-dataflow-pipeline-{}'.format(MOCK_UUID), num_retries=5, poll_sleep=10, project_number=TEST_PROJECT, ) mock_uuid.assert_called_once_with() @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController')) @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn')) def test_cancel_job(self, mock_get_conn, jobs_controller): self.dataflow_hook.cancel_job(job_name=UNIQUE_JOB_NAME, job_id=TEST_JOB_ID, project_id=TEST_PROJECT, location=TEST_LOCATION) jobs_controller.assert_called_once_with( dataflow=mock_get_conn.return_value, job_id=TEST_JOB_ID, location=TEST_LOCATION, name=UNIQUE_JOB_NAME, poll_sleep=10, project_number=TEST_PROJECT, ) jobs_controller.cancel()