vincbeck commented on code in PR #77792: URL: https://github.com/apache/airflow/pull/77792#discussion_r4743526421
########## airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py: ########## @@ -0,0 +1,137 @@ +# 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.getfqdn()``. The task return value +# is ``socket.gethostname()``. Those are not always the same string. +_HOST_PROBE = ( + "import socket; from airflow.utils.net import getfqdn; print(getfqdn()); 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 + fqdn, short = stdout.strip().splitlines() + return fqdn, 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] + + +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, 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_fqdn, scheduler_short = _container_names(compose_instance, "airflow-scheduler") + worker_fqdn, worker_short = _container_names(compose_instance, "airflow-worker") + assert scheduler_fqdn != worker_fqdn + assert scheduler_short != worker_short + + 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_fqdn = worker_fqdn if use_executor else scheduler_fqdn + expected_short = worker_short if use_executor else scheduler_short + assert task_instance["hostname"] == expected_fqdn, 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 + + assert self.client.get_dag(DAG_ID)["is_paused"] is True Review Comment: Is that needed? You already check it is paused at the start, and `dag.test` does not unpause the Dag. ########## airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py: ########## @@ -0,0 +1,137 @@ +# 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.getfqdn()``. The task return value +# is ``socket.gethostname()``. Those are not always the same string. +_HOST_PROBE = ( + "import socket; from airflow.utils.net import getfqdn; print(getfqdn()); print(socket.gethostname())" Review Comment: `TaskInstance.hostname` comes from `get_hostname()`, which uses `[core] hostname_callable`. Should we use `get_hostname()` here instead of `getfqdn()`? Otherwise the test breaks as soon as the stack sets `hostname_callable`. ########## airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_dag_test_method.py: ########## @@ -0,0 +1,137 @@ +# 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.getfqdn()``. The task return value +# is ``socket.gethostname()``. Those are not always the same string. +_HOST_PROBE = ( + "import socket; from airflow.utils.net import getfqdn; print(getfqdn()); 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 + fqdn, short = stdout.strip().splitlines() + return fqdn, 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] + + +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, 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_fqdn, scheduler_short = _container_names(compose_instance, "airflow-scheduler") + worker_fqdn, worker_short = _container_names(compose_instance, "airflow-worker") Review Comment: nit: the scheduler and worker hostnames don't change between the four cases, maybe compute them once in a class-scoped fixture? ########## 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 datetime import datetime + +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__": + positional = [arg for arg in sys.argv[1:] if not arg.startswith("-")] + logical_date = pendulum.parse(positional[0]) if positional else None + if logical_date is not None and not isinstance(logical_date, datetime): + raise SystemExit(f"Expected a datetime logical date, got {logical_date!r}") + dag.test(logical_date=logical_date, use_executor="--use-executor" in sys.argv) Review Comment: nit: the test always passes the date first, so this can be just `dag.test(logical_date=pendulum.parse(sys.argv[1]), use_executor="--use-executor" in sys.argv)`. The `datetime` import can go too. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
