未在气流测试中呈现的模板

时间:2019-04-04 17:28:44

标签: python unit-testing airflow

我有一个Python模块,其结构如下:

my_module/
  ...
  tests/
    __init__.py
    my_test.py
    ...

其中my_test.py的定义如下:

from __future__ import print_function, unicode_literals

import os
import unittest
from datetime import timedelta, date

from airflow import configuration
from airflow.models import TaskInstance as TI, DAG, DagRun
from airflow.operators.python_operator import PythonOperator
from airflow.settings import Session
from airflow.utils import timezone
from airflow.utils.state import State

DEFAULT_DATE = timezone.datetime(2016, 1, 1)
END_DATE = timezone.datetime(2016, 1, 2)
INTERVAL = timedelta(hours=12)
FROZEN_NOW = timezone.datetime(2016, 1, 2, 12, 1, 1)

TI_CONTEXT_ENV_VARS = ['AIRFLOW_CTX_DAG_ID',
                       'AIRFLOW_CTX_TASK_ID',
                       'AIRFLOW_CTX_EXECUTION_DATE',
                       'AIRFLOW_CTX_DAG_RUN_ID']


class Call:
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs


def build_recording_function(calls_collection):
    """
    We can not use a Mock instance as a PythonOperator callable function or some tests fail with a
    TypeError: Object of type Mock is not JSON serializable
    Then using this custom function recording custom Call objects for further testing
    (replacing Mock.assert_called_with assertion method)
    """
    def recording_function(*args, **kwargs):
        calls_collection.append(Call(*args, **kwargs))
    return recording_function


class PythonOperatorTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        super(PythonOperatorTest, cls).setUpClass()

        session = Session()

        session.query(DagRun).delete()
        session.query(TI).delete()
        session.commit()
        session.close()

    def setUp(self):
        super(PythonOperatorTest, self).setUp()
        configuration.load_test_config()
        self.dag = DAG(
            'test_dag',
            default_args={
                'owner': 'airflow',
                'start_date': DEFAULT_DATE},
            schedule_interval=INTERVAL)
        self.addCleanup(self.dag.clear)
        self.clear_run()
        self.addCleanup(self.clear_run)

    def tearDown(self):
        super(PythonOperatorTest, self).tearDown()

        session = Session()

        session.query(DagRun).delete()
        session.query(TI).delete()
        print(len(session.query(DagRun).all()))
        session.commit()
        session.close()

        for var in TI_CONTEXT_ENV_VARS:
            if var in os.environ:
                del os.environ[var]

    def do_run(self):
        self.run = True

    def clear_run(self):
        self.run = False

    def is_run(self):
        return self.run

    def _assertCallsEqual(self, first, second):
        self.assertIsInstance(first, Call)
        self.assertIsInstance(second, Call)
        self.assertTupleEqual(first.args, second.args)
        self.assertDictEqual(first.kwargs, second.kwargs)

    def test_python_callable_arguments_are_templatized(self):
        """Test PythonOperator op_args are templatized"""
        recorded_calls = []

        task = PythonOperator(
            task_id='python_operator',
            # a Mock instance cannot be used as a callable function or test fails with a
            # TypeError: Object of type Mock is not JSON serializable
            python_callable=(build_recording_function(recorded_calls)),
            op_args=[
                4,
                date(2019, 1, 1),
                "dag {{dag.dag_id}} ran on {{ds}}."
            ],
            dag=self.dag)

        self.dag.create_dagrun(
            run_id='manual__' + DEFAULT_DATE.isoformat(),
            execution_date=DEFAULT_DATE,
            start_date=DEFAULT_DATE,
            state=State.RUNNING
        )
        task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)

        self.assertEqual(1, len(recorded_calls))
        self._assertCallsEqual(
            recorded_calls[0],
            Call(4,
                 date(2019, 1, 1),
                 "dag {} ran on {}.".format(self.dag.dag_id, DEFAULT_DATE.date().isoformat()))
        )

在终端中,当我运行nosetests test/my_test.py时,测试失败,因为Jinja模板未正确呈现。完整的日志如下。

======================================================================
FAIL: Test PythonOperator op_args are templatized
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/my_module/tests/my_test.py", line 120, in test_python_callable_arguments_are_templatized
    "dag {} ran on {}.".format(self.dag.dag_id, DEFAULT_DATE.date().isoformat()))
  File "/home/user/my_module/tests/my_test.py", line 88, in _assertCallsEqual
    self.assertTupleEqual(first.args, second.args)
AssertionError: Tuples differ: (4, datetime.date(2019, 1, 1), 'dag {{dag.dag_id}} ran on {{ds}}.') != (4, datetime.date(2019, 1, 1), 'dag test_dag ran on 2016-01-01.')

First differing element 2:
'dag {{dag.dag_id}} ran on {{ds}}.'
'dag test_dag ran on 2016-01-01.'

- (4, datetime.date(2019, 1, 1), 'dag {{dag.dag_id}} ran on {{ds}}.')
?                                     ^^   ---------        ^^^^^^

+ (4, datetime.date(2019, 1, 1), 'dag test_dag ran on 2016-01-01.')
?                                     ^^^^^           ^^^^^^^^^^

-------------------- >> begin captured logging << --------------------
airflow.utils.log.logging_mixin.LoggingMixin: INFO: Reading the config from /home/user/airflow/airflow.cfg
airflow.settings: INFO: Configured default timezone <Timezone [UTC]>
airflow.logging_config: DEBUG: Unable to load custom logging, using default config instead
--------------------- >> end captured logging << ---------------------

但是,my_test.py中的代码没有任何问题,因为它只是test_python_operator.pyv1-10-stable分支)中文件Airflow github repository的子集。天真地,我希望此测试可以正常运行,但不能运行。

  

我想念什么?

编辑:我正在使用apache-airflow 1.10.2,Python 3.6.8和机头1.3.7。

2 个答案:

答案 0 :(得分:2)

这是因为,在{strong> Airflow 1.10.2 中,'op_args''op_kwargs'字段不是模板字段。问题中的链接是Airflow信息库的master分支。

在发布Airflow 1.10.2之后添加了

PythonOperator'op_args'

将这些字段包括到'op_kwargs'的提交(这仍然在主版本中,没有包含在任何发行版本中):https://github.com/apache/airflow/commit/7ab245b296efc73db3ce4ce0edbae473e357698c

对于Airflow 1.10.2:检查此文件-https://github.com/apache/airflow/blob/1.10.2/tests/operators/test_python_operator.py

此外,请勿使用template_fields分支,因为它包含即将发布的版本 1.10.3 的代码。您应该改用 1.10.2 标记:https://github.com/apache/airflow/tree/1.10.2

PythonOperator (1.10.2): https://github.com/apache/airflow/blob/1.10.2/airflow/operators/python_operator.py#L65

v1-10-stable

PythonOperator (母版-开发分支): https://github.com/apache/airflow/blob/master/airflow/operators/python_operator.py#L72

class PythonOperator(BaseOperator):
    template_fields = ('templates_dict',)
    template_ext = tuple()
    ui_color = '#ffefeb'

    @apply_defaults
    def __init__(
            self,
            python_callable,
            op_args=None,
            op_kwargs=None,
            provide_context=False,
            templates_dict=None,
            templates_exts=None,
            *args, **kwargs):
...

答案 1 :(得分:0)

您很可能使用1.10或更早的版本来运行测试。在该版本中,op_args中的PythonOperator没有被模板化。但是在master中,您很可能正在使用op_args的测试模板,并对其进行了相应的测试。如果您确实要使用气流测试作为示例,则应从与您安装的版本相对应的任何分支中获取它们。