This is an automated email from the ASF dual-hosted git repository.
vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 8a6f37308fc Add e2e tests for dag.test with and without the executor
(#77792)
8a6f37308fc is described below
commit 8a6f37308fc7fe11417363573598a1f503962932
Author: SreeCharan Desu <[email protected]>
AuthorDate: Tue Dec 1 21:06:48 2026 +0530
Add e2e tests for dag.test with and without the executor (#77792)
dag.test(use_executor=...) and airflow dags test --use-executor have no
end-to-end coverage, so a change that drops the flag still exits 0.
These cases check which container the task actually ran in.
---
.../basic_tests/test_dag_test_method.py | 148 +++++++++++++++++++++
.../dags/example_dag_test_method.py | 48 +++++++
2 files changed, 196 insertions(+)
diff --git
a/airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py
b/airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py
new file mode 100644
index 00000000000..1de9f8754cf
--- /dev/null
+++
b/airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py
@@ -0,0 +1,148 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import subprocess
+from datetime import datetime
+
+import pytest
+
+from airflow_e2e_tests.e2e_test_utils.clients import AirflowClient
+
+DAG_ID = "example_dag_test_method"
+TASK_ID = "record_hostname"
+DAG_FILE = "/opt/airflow/dags/example_dag_test_method.py"
+# ``dag.test(use_executor=True)`` waits on the worker with no deadline of its
own.
+_RUN_TIMEOUT_SECONDS = "240"
+
+# TaskInstance.hostname is ``airflow.utils.net.get_hostname()``, which follows
+# ``[core] hostname_callable``. The task return value is
``socket.gethostname()``.
+# Those are not always the same string.
+_HOST_PROBE = (
+ "import socket; from airflow.utils.net import get_hostname; "
+ "print(get_hostname()); print(socket.gethostname())"
+)
+
+
+def _decode(stream: str | bytes | None) -> str:
+ if stream is None:
+ return ""
+ if isinstance(stream, bytes):
+ return stream.decode(errors="replace")
+ return stream
+
+
+def _exec(compose_instance, service_name: str, command: list[str]) ->
tuple[str, str, int]:
+ try:
+ stdout, stderr, exit_code = compose_instance.exec_in_container(
+ command=command,
+ service_name=service_name,
+ )
+ except subprocess.CalledProcessError as exc:
+ return _decode(exc.stdout), _decode(exc.stderr), exc.returncode
+ return _decode(stdout), _decode(stderr), exit_code
+
+
+def _container_names(compose_instance, service_name: str) -> tuple[str, str]:
+ stdout, stderr, exit_code = _exec(
+ compose_instance,
+ service_name,
+ ["python", "-c", _HOST_PROBE],
+ )
+ assert exit_code == 0, stderr or stdout
+ hostname, short = stdout.strip().splitlines()
+ return hostname, short
+
+
+def _same_instant(raw: str | None, expected: str) -> bool:
+ if not raw:
+ return False
+ return datetime.fromisoformat(raw.replace("Z", "+00:00")) ==
datetime.fromisoformat(expected)
+
+
+def _command(entry_point: str, use_executor: bool, logical_date: str) ->
list[str]:
+ if entry_point == "cli":
+ command = ["airflow", "dags", "test", DAG_ID, logical_date]
+ else:
+ command = ["python", DAG_FILE, logical_date]
+ if use_executor:
+ command.append("--use-executor")
+ return ["timeout", "-k", "20", _RUN_TIMEOUT_SECONDS, *command]
+
+
[email protected](scope="class")
+def container_hostnames(compose_instance) -> tuple[tuple[str, str], tuple[str,
str]]:
+ scheduler_hostname, scheduler_short = _container_names(compose_instance,
"airflow-scheduler")
+ worker_hostname, worker_short = _container_names(compose_instance,
"airflow-worker")
+ assert scheduler_hostname != worker_hostname
+ assert scheduler_short != worker_short
+ return (scheduler_hostname, scheduler_short), (worker_hostname,
worker_short)
+
+
+class TestDagTestMethod:
+ """``dag.test`` and ``airflow dags test`` with and without
``--use-executor``."""
+
+ client = AirflowClient()
+
+ @pytest.mark.parametrize(
+ ("entry_point", "use_executor", "logical_date"),
+ [
+ ("cli", False, "2024-06-01T00:00:00+00:00"),
+ ("cli", True, "2024-06-01T01:00:00+00:00"),
+ ("python", False, "2024-06-01T02:00:00+00:00"),
+ ("python", True, "2024-06-01T03:00:00+00:00"),
+ ],
+ ids=["cli", "cli-use-executor", "python", "python-use-executor"],
+ )
+ def test_task_runs_on_the_expected_host(
+ self,
+ compose_instance,
+ container_hostnames: tuple[tuple[str, str], tuple[str, str]],
+ entry_point: str,
+ use_executor: bool,
+ logical_date: str,
+ ):
+ dag = self.client.wait_for_dag(DAG_ID)
+ assert dag["is_paused"] is True, dag
+
+ (scheduler_hostname, scheduler_short), (worker_hostname, worker_short)
= container_hostnames
+
+ command = _command(entry_point, use_executor, logical_date)
+ stdout, stderr, exit_code = _exec(compose_instance,
"airflow-scheduler", command)
+ assert exit_code == 0, f"exit
{exit_code}\nstdout:\n{stdout}\nstderr:\n{stderr}"
+
+ runs = self.client.list_dag_runs(DAG_ID).get("dag_runs", [])
+ matching = [run for run in runs if
_same_instant(run.get("logical_date"), logical_date)]
+ assert len(matching) == 1, runs
+ run = matching[0]
+ assert run["state"] == "success", run
+
+ task_instances = self.client.get_task_instances(DAG_ID,
run["dag_run_id"])["task_instances"]
+ task_instance = next(ti for ti in task_instances if ti["task_id"] ==
TASK_ID)
+ assert task_instance["state"] == "success", task_instance
+
+ expected_hostname = worker_hostname if use_executor else
scheduler_hostname
+ expected_short = worker_short if use_executor else scheduler_short
+ assert task_instance["hostname"] == expected_hostname, task_instance
+
+ xcom = self.client.get_xcom_value(
+ dag_id=DAG_ID,
+ task_id=TASK_ID,
+ run_id=run["dag_run_id"],
+ key="return_value",
+ )
+ assert xcom["value"] == expected_short, xcom
diff --git
a/airflow-e2e-tests/tests/airflow_e2e_tests/dags/example_dag_test_method.py
b/airflow-e2e-tests/tests/airflow_e2e_tests/dags/example_dag_test_method.py
new file mode 100644
index 00000000000..5e381d47c02
--- /dev/null
+++ b/airflow-e2e-tests/tests/airflow_e2e_tests/dags/example_dag_test_method.py
@@ -0,0 +1,48 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Paused Dag that records which host ``dag.test`` ran its task on."""
+
+from __future__ import annotations
+
+import socket
+import sys
+from typing import cast
+
+import pendulum
+
+from airflow.sdk import DAG, task
+
+with DAG(
+ dag_id="example_dag_test_method",
+ schedule=None,
+ catchup=False,
+ is_paused_upon_creation=True,
+) as dag:
+
+ @task
+ def record_hostname():
+ return socket.gethostname()
+
+ record_hostname()
+
+
+if __name__ == "__main__":
+ # parse() is typed as a date/time/duration union. The test always passes a
datetime.
+ dag.test(
+ logical_date=cast("pendulum.DateTime", pendulum.parse(sys.argv[1])),
+ use_executor="--use-executor" in sys.argv,
+ )