如何模拟 PythonOperator 的 python_callable 和 on_failure_callback?

tls*_*skr 5 python unit-testing mocking airflow

我用 Airflow 模拟什么和在哪里PythonOperator,这样:

  • python_callback引发了异常,引发的通话on_failure_callback,并
  • 我可以测试是否调用了该回调,以及使用什么参数?

我曾尝试PythonOperator.execute在许多地方模拟 {python_callable} 和,但没有成功。

代码文件如下所示:

dags/my_code.py

class CustomException(Exception): pass

def a_callable():
    if OurSqlAlchemyTable.count() == 0:
        raise CustomException("{} is empty".format(OurSqlAlchemyTable.name))
    return True

def a_failure_callable(context):
    SlackWebhookHook(
        http_conn_id=slack_conn_id,
        message= context['exception'].msg,
        channel='#alert-channel'
        ).execute()
Run Code Online (Sandbox Code Playgroud)

dags/a_dag.py

from my_code import a_callable, a_failure_callable

new_task = PythonOperator(
    task_id='new-task', dag=dag-named-sue, conn_id='a_conn_id', timeout=30,
    python_callable=a_callable,
    on_failure_callback=a_failure_callable)
Run Code Online (Sandbox Code Playgroud)

dags/test_a_dag.py

class TestCallback(unittest.TestCase):

    def test_on_failure_callback(self):
        tested_task = DagBag().get_dag('dag-named-sue').get_task('new-task')

        with patch('airflow.operators.python_operator.PythonOperator.execute') as mock_execute:
            with patch('dags.a_dag.a_failure_callable') as mock_callback:
                mock_execute.side_effect = CustomException
                tested_task.execute(context={})

            # does failure of the python_callable trigger the failure callback?
        mock_callback.assert_called()

            # did the exception message make it to the failure callback?
        failure_context = mock_callback.call_args[0]
        self.assertEqual(failure_context['exception'].msg,
                        'OurSqlAlchemyTable is empty')O
Run Code Online (Sandbox Code Playgroud)

测试确实CustomException在线上引发了self.task.execute(context={})- 但是,在测试代码本身中。我想要的是在 Airflow 代码中引发该错误,以便PythonOperator失败并调用on_failure_callback.

我尝试了任意数量的排列,所有排列都在测试中引发而不触发,调用 python_callable,或者找不到要修补的对象:

patch('dags.a_dag.a_callable') as mock_callable
      'a_dag.a_callable'
      'dags.my_code.a_callable'
      'my_code.a_callable'
      'airflow.models.Task.execute'
Run Code Online (Sandbox Code Playgroud)

( Python3, pytest, 和mock.)

我错过了什么/做错了什么?

(更好的是,我想验证传递给 的参数SlackWebhookHook。例如:

with patch('???.SlackWebhookHook.execute') as mock_webhook:
    ... as above ...

kw_dict = mock_webhook.call_args[-1]
assert kw_dict['http_conn_id'] == slack_conn_id
assert kw_dict['message'] == 'OurSqlAlchemyTable is empty'
assert kw_dict['channel'] == '#alert-channel'
Run Code Online (Sandbox Code Playgroud)

(但我首先专注于测试失败回调。)

先感谢您。