You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "phi-friday (via GitHub)" <gi...@apache.org> on 2024/08/28 12:45:49 UTC

[PR] fix: rm `skip_if` and `run_if` in python source [airflow]

phi-friday opened a new pull request, #41832:
URL: https://github.com/apache/airflow/pull/41832

   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   Like `setup` and `teardown`, `skip_if` and `run_if` should also be removed.
   
   ### sample dag code
   ```python
   from __future__ import annotations
   
   from pendulum import datetime
   
   from airflow.decorators import dag, task
   
   
   @dag(start_date=datetime(2024, 1, 1), schedule=None, catchup=False)
   def venv_skip_if() -> None:
       @task.skip_if(lambda context: False)
       @task.virtualenv()
       def echo() -> None:
           print("hello world")
   
       echo()
   
   
   venv_skip_if()
   ```
   
   #### before in venv
   ```log
   1b4bbddb0c17
   *** Found local files:
   ***   * /root/airflow/logs/dag_id=venv_skip_if/run_id=manual__2024-08-28T12:29:04.469903+00:00/task_id=echo/attempt=1.log
   [2024-08-28, 12:29:05 UTC] {local_task_job_runner.py:123} ▶ Pre task execution logs
   [2024-08-28, 12:29:05 UTC] {process_utils.py:186} INFO - Executing cmd: /usr/local/bin/python -m virtualenv /tmp/venv5qst192w --system-site-packages --python=python
   [2024-08-28, 12:29:05 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:29:06 UTC] {process_utils.py:194} INFO - created virtual environment CPython3.8.19.final.0-64 in 276ms
   [2024-08-28, 12:29:06 UTC] {process_utils.py:194} INFO -   creator CPython3Posix(dest=/tmp/venv5qst192w, clear=False, no_vcs_ignore=False, global=True)
   [2024-08-28, 12:29:06 UTC] {process_utils.py:194} INFO -   seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
   [2024-08-28, 12:29:06 UTC] {process_utils.py:194} INFO -     added seed packages: pip==24.1, setuptools==70.1.0, wheel==0.43.0
   [2024-08-28, 12:29:06 UTC] {process_utils.py:194} INFO -   activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
   [2024-08-28, 12:29:06 UTC] {process_utils.py:186} INFO - Executing cmd: /tmp/venv5qst192w/bin/pip install -r /tmp/venv5qst192w/requirements.txt
   [2024-08-28, 12:29:06 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:29:10 UTC] {process_utils.py:194} INFO - 
   [2024-08-28, 12:29:10 UTC] {process_utils.py:194} INFO - [notice] A new release of pip is available: 24.1 -> 24.2
   [2024-08-28, 12:29:10 UTC] {process_utils.py:194} INFO - [notice] To update, run: python -m pip install --upgrade pip
   [2024-08-28, 12:29:10 UTC] {process_utils.py:186} INFO - Executing cmd: /tmp/venv5qst192w/bin/python /tmp/venv-callwp2r9u9t/script.py /tmp/venv-callwp2r9u9t/script.in /tmp/venv-callwp2r9u9t/script.out /tmp/venv-callwp2r9u9t/string_args.txt /tmp/venv-callwp2r9u9t/termination.log /tmp/venv-callwp2r9u9t/***_context.json
   [2024-08-28, 12:29:10 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:29:13 UTC] {process_utils.py:194} INFO - Traceback (most recent call last):
   [2024-08-28, 12:29:13 UTC] {process_utils.py:194} INFO -   File "/tmp/venv-callwp2r9u9t/script.py", line 18, in <module>
   [2024-08-28, 12:29:13 UTC] {process_utils.py:194} INFO -     @task.skip_if(lambda context: False)
   [2024-08-28, 12:29:13 UTC] {process_utils.py:194} INFO - NameError: name 'task' is not defined
   [2024-08-28, 12:29:13 UTC] {taskinstance.py:3167} ERROR - Task failed with exception
   Traceback (most recent call last):
     File "/opt/airflow/airflow/models/taskinstance.py", line 753, in _execute_task
       result = _execute_callable(context=context, **execute_callable_kwargs)
     File "/opt/airflow/airflow/models/taskinstance.py", line 719, in _execute_callable
       return ExecutionCallableRunner(
     File "/opt/airflow/airflow/utils/operator_helpers.py", line 252, in run
       return self.func(*args, **kwargs)
     File "/opt/airflow/airflow/models/baseoperator.py", line 402, in wrapper
       return func(self, *args, **kwargs)
     File "/opt/airflow/airflow/decorators/base.py", line 266, in execute
       return_value = super().execute(context)
     File "/opt/airflow/airflow/models/baseoperator.py", line 402, in wrapper
       return func(self, *args, **kwargs)
     File "/opt/airflow/airflow/operators/python.py", line 509, in execute
       return super().execute(context=serializable_context)
     File "/opt/airflow/airflow/models/baseoperator.py", line 402, in wrapper
       return func(self, *args, **kwargs)
     File "/opt/airflow/airflow/operators/python.py", line 240, in execute
       return_value = self.execute_callable()
     File "/opt/airflow/airflow/operators/python.py", line 900, in execute_callable
       result = self._execute_python_callable_in_subprocess(python_path)
     File "/opt/airflow/airflow/operators/python.py", line 593, in _execute_python_callable_in_subprocess
       execute_in_subprocess(
     File "/opt/airflow/airflow/utils/process_utils.py", line 175, in execute_in_subprocess
       execute_in_subprocess_with_kwargs(cmd, cwd=cwd, env=env)
     File "/opt/airflow/airflow/utils/process_utils.py", line 198, in execute_in_subprocess_with_kwargs
       raise subprocess.CalledProcessError(exit_code, cmd)
   subprocess.CalledProcessError: Command '['/tmp/venv5qst192w/bin/python', '/tmp/venv-callwp2r9u9t/script.py', '/tmp/venv-callwp2r9u9t/script.in', '/tmp/venv-callwp2r9u9t/script.out', '/tmp/venv-callwp2r9u9t/string_args.txt', '/tmp/venv-callwp2r9u9t/termination.log', '/tmp/venv-callwp2r9u9t/airflow_context.json']' returned non-zero exit status 1.
   [2024-08-28, 12:29:13 UTC] {taskinstance.py:1211} INFO - Marking task as FAILED. dag_id=venv_skip_if, task_id=echo, run_id=manual__2024-08-28T12:29:04.469903+00:00, execution_date=20240828T122904, start_date=20240828T122905, end_date=20240828T122913
   [2024-08-28, 12:29:13 UTC] {taskinstance.py:337} ▶ Post task execution logs
   ```
   
   #### after in venv
   ```log
   5dae42dc6e21
   *** Found local files:
   ***   * /root/airflow/logs/dag_id=venv_skip_if/run_id=manual__2024-08-28T12:39:47.502535+00:00/task_id=echo/attempt=1.log
   [2024-08-28, 12:39:48 UTC] {local_task_job_runner.py:123} ▶ Pre task execution logs
   [2024-08-28, 12:39:48 UTC] {process_utils.py:186} INFO - Executing cmd: /usr/local/bin/python -m virtualenv /tmp/venvt7te04zf --system-site-packages --python=python
   [2024-08-28, 12:39:48 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:39:48 UTC] {process_utils.py:194} INFO - created virtual environment CPython3.8.19.final.0-64 in 266ms
   [2024-08-28, 12:39:48 UTC] {process_utils.py:194} INFO -   creator CPython3Posix(dest=/tmp/venvt7te04zf, clear=False, no_vcs_ignore=False, global=True)
   [2024-08-28, 12:39:48 UTC] {process_utils.py:194} INFO -   seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
   [2024-08-28, 12:39:48 UTC] {process_utils.py:194} INFO -     added seed packages: pip==24.1, setuptools==70.1.0, wheel==0.43.0
   [2024-08-28, 12:39:48 UTC] {process_utils.py:194} INFO -   activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
   [2024-08-28, 12:39:48 UTC] {process_utils.py:186} INFO - Executing cmd: /tmp/venvt7te04zf/bin/pip install -r /tmp/venvt7te04zf/requirements.txt
   [2024-08-28, 12:39:48 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:39:52 UTC] {process_utils.py:194} INFO - 
   [2024-08-28, 12:39:52 UTC] {process_utils.py:194} INFO - [notice] A new release of pip is available: 24.1 -> 24.2
   [2024-08-28, 12:39:52 UTC] {process_utils.py:194} INFO - [notice] To update, run: python -m pip install --upgrade pip
   [2024-08-28, 12:39:52 UTC] {process_utils.py:186} INFO - Executing cmd: /tmp/venvt7te04zf/bin/python /tmp/venv-call55vo1yul/script.py /tmp/venv-call55vo1yul/script.in /tmp/venv-call55vo1yul/script.out /tmp/venv-call55vo1yul/string_args.txt /tmp/venv-call55vo1yul/termination.log /tmp/venv-call55vo1yul/***_context.json
   [2024-08-28, 12:39:52 UTC] {process_utils.py:190} INFO - Output:
   [2024-08-28, 12:39:56 UTC] {process_utils.py:194} INFO - hello world
   [2024-08-28, 12:39:56 UTC] {python.py:242} INFO - Done. Returned value was: None
   [2024-08-28, 12:39:56 UTC] {taskinstance.py:337} ▶ Post task execution logs
   ```
   
   <!-- Please keep an empty line above the dashes. -->
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1740122257


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   I've fixed the test, but I'm not satisfied. 
   The function that clears the decorator relies on `custom_operator_name`, which makes it tricky to apply the decorator dynamically.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on PR #41832:
URL: https://github.com/apache/airflow/pull/41832#issuecomment-2315417743

   I'm getting an error related to the open api, I'm not understanding why it's happening, could you please explain?


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1743370829


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   I think the current suite of tests is fine.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1747207597


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   i fixed it



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1743369866


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,156 @@
+# 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 ast
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+
+
+class TestDecoratorSource:
+    @staticmethod
+    def update_custom_operator_name(operator: Any, custom_operator_name: str):
+        custom_operator_name = (
+            custom_operator_name if custom_operator_name.startswith("@") else f"@{custom_operator_name}"
+        )
+        operator.__dict__["custom_operator_name"] = custom_operator_name
+
+    @staticmethod
+    def init_decorator(decorator_name: str):
+        decorator_factory = getattr(task, decorator_name)
+
+        kwargs = {}
+        if "external" in decorator_name:
+            kwargs["python"] = "python3"
+        return decorator_factory(**kwargs)
+
+    @classmethod
+    def parse_python_source(cls, task: Task, custom_operator_name: str | None = None) -> str:
+        operator = task().operator
+        if not hasattr(operator, "get_python_source"):
+            pytest.skip(f"Operator {operator} does not have get_python_source method")
+        if custom_operator_name:
+            cls.update_custom_operator_name(operator, custom_operator_name)
+        return operator.get_python_source()
+
+    @classmethod
+    def parse_decorator_names(cls, source: Task | str) -> list[str]:
+        if not isinstance(source, str):
+            source = cls.parse_python_source(source)
+        node = ast.parse(source)
+        func: ast.FunctionDef = node.body[0]  # type: ignore[assignment]
+        decorators: list[ast.Name] = func.decorator_list  # type: ignore[assignment]
+        return [decorator.id for decorator in decorators]

Review Comment:
   These should be implemented with `@pytest.fixture` instead. If you do that, the entire class is unnecessary 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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1746908278


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   Some operators don't inherit from `DecoratedOperator`, so I can't run `get_python_source`, for example `DecoratedSensorOperator`.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1737974202


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   Is it possible for this to test what `source` actually contains, instead of just testing it does _not_ contain `"run_if"`?
   
   Also, since we are creating a test, can we also test other decorators 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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "bitomukesh (via GitHub)" <gi...@apache.org>.
bitomukesh commented on PR #41832:
URL: https://github.com/apache/airflow/pull/41832#issuecomment-2365126392

   <div>
   <h2>Changelist by Bito</h2>
       <p>This pull request implements the following key changes.</p>
   
   <div>
   <table width="100%">
   <tbody>
     <tr>
       <th>Key Change</th>
       <th>Files Impacted</th>
     </tr>
   
   <tr>
   <td width="30%">
       <b>Feature Improvement</b> - Enhanced Task Decorator Handling
   </td>
   <td width="70%">
   
   
   <div>
   
   -&nbsp;[`decorators.py`](https://github.com/apache/airflow/pull/41832/files#diff-31e018f610abfba48efc7703072679ac3a5622c2b526be782001a728ef58e0f1) - Added @task.skip_if and @task.run_if to the list of decorators
   <div>
   
   -&nbsp;[`test_decorators.py`](https://github.com/apache/airflow/pull/41832/files#diff-13168c5cebc41a52056899501834c0f27c31f18f99562f34a33c82114999365d) - Added new tests for skip_if and run_if decorators
   </div>
   </td>
   </tr>
   
   </tbody>
   </table>
   </div>
   </div>


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1746659295


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   When does this happen?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1743671153


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,156 @@
+# 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 ast
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+
+
+class TestDecoratorSource:
+    @staticmethod
+    def update_custom_operator_name(operator: Any, custom_operator_name: str):
+        custom_operator_name = (
+            custom_operator_name if custom_operator_name.startswith("@") else f"@{custom_operator_name}"
+        )
+        operator.__dict__["custom_operator_name"] = custom_operator_name
+
+    @staticmethod
+    def init_decorator(decorator_name: str):
+        decorator_factory = getattr(task, decorator_name)
+
+        kwargs = {}
+        if "external" in decorator_name:
+            kwargs["python"] = "python3"
+        return decorator_factory(**kwargs)
+
+    @classmethod
+    def parse_python_source(cls, task: Task, custom_operator_name: str | None = None) -> str:
+        operator = task().operator
+        if not hasattr(operator, "get_python_source"):
+            pytest.skip(f"Operator {operator} does not have get_python_source method")
+        if custom_operator_name:
+            cls.update_custom_operator_name(operator, custom_operator_name)
+        return operator.get_python_source()
+
+    @classmethod
+    def parse_decorator_names(cls, source: Task | str) -> list[str]:
+        if not isinstance(source, str):
+            source = cls.parse_python_source(source)
+        node = ast.parse(source)
+        func: ast.FunctionDef = node.body[0]  # type: ignore[assignment]
+        decorators: list[ast.Name] = func.decorator_list  # type: ignore[assignment]
+        return [decorator.id for decorator in decorators]

Review Comment:
   I defined `decorator` as `fixture` as you said.
   However, I don't know the right way to remove `parse_python_source`.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1740093604


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   I think it might work with `ast`, but I'm not sure.
   I'll try it and get back to you.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1743369866


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,156 @@
+# 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 ast
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+
+
+class TestDecoratorSource:
+    @staticmethod
+    def update_custom_operator_name(operator: Any, custom_operator_name: str):
+        custom_operator_name = (
+            custom_operator_name if custom_operator_name.startswith("@") else f"@{custom_operator_name}"
+        )
+        operator.__dict__["custom_operator_name"] = custom_operator_name
+
+    @staticmethod
+    def init_decorator(decorator_name: str):
+        decorator_factory = getattr(task, decorator_name)
+
+        kwargs = {}
+        if "external" in decorator_name:
+            kwargs["python"] = "python3"
+        return decorator_factory(**kwargs)
+
+    @classmethod
+    def parse_python_source(cls, task: Task, custom_operator_name: str | None = None) -> str:
+        operator = task().operator
+        if not hasattr(operator, "get_python_source"):
+            pytest.skip(f"Operator {operator} does not have get_python_source method")
+        if custom_operator_name:
+            cls.update_custom_operator_name(operator, custom_operator_name)
+        return operator.get_python_source()
+
+    @classmethod
+    def parse_decorator_names(cls, source: Task | str) -> list[str]:
+        if not isinstance(source, str):
+            source = cls.parse_python_source(source)
+        node = ast.parse(source)
+        func: ast.FunctionDef = node.body[0]  # type: ignore[assignment]
+        decorators: list[ast.Name] = func.decorator_list  # type: ignore[assignment]
+        return [decorator.id for decorator in decorators]

Review Comment:
   These should be implemented with `@pytest.fixture` instead.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1747067353


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   I'll fix it soon.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1747052083


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   But this is a test. Why don’t we just not test those operators instead?



##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from airflow.decorators import task
+
+if TYPE_CHECKING:
+    from airflow.decorators.base import Task, TaskDecorator
+DECORATORS = sorted(set(x for x in dir(task) if not x.startswith("_")) - {"skip_if", "run_if"})
+DECORATORS_USING_SOURCE = ("external_python", "virtualenv", "branch_virtualenv", "branch_external_python")
+
+
+@pytest.fixture
+def decorator(request: pytest.FixtureRequest) -> TaskDecorator:
+    decorator_factory = getattr(task, request.param)
+
+    kwargs = {}
+    if "external" in request.param:
+        kwargs["python"] = "python3"
+    return decorator_factory(**kwargs)
+
+
+@pytest.mark.parametrize("decorator", DECORATORS_USING_SOURCE, indirect=["decorator"])
+def test_task_decorator_using_source(decorator: TaskDecorator):
+    @decorator
+    def f():
+        return ["some_task"]
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return ["some_task"]\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_skip_if(decorator: TaskDecorator):
+    @task.skip_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+@pytest.mark.parametrize("decorator", DECORATORS, indirect=["decorator"])
+def test_run_if(decorator: TaskDecorator):
+    @task.run_if(lambda context: True)
+    @decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f, "decorator") == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_and_run_if():
+    @task.skip_if(lambda context: True)
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_run_if_and_skip_if():
+    @task.run_if(lambda context: True)
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == 'def f():\n    return "hello world"\n'
+
+
+def test_skip_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def test_run_if_allow_decorator():
+    def non_task_decorator(func):
+        return func
+
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    @non_task_decorator
+    def f():
+        return "hello world"
+
+    assert parse_python_source(f) == '@non_task_decorator\ndef f():\n    return "hello world"\n'
+
+
+def parse_python_source(task: Task, custom_operator_name: str | None = None) -> str:
+    operator = task().operator
+    if not hasattr(operator, "get_python_source"):
+        pytest.skip(f"Operator {operator} does not have get_python_source method")

Review Comment:
   But this is only used in tests. Why don’t we just not test those operators instead?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1737974945


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   I also wonder if it’s possible to create some future-proof checks so we don’t have this problem again if new decorators are added in the future.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1741519058


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   I agree, this feels too flimsy. Let’s remove the test file and settle.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: rm `skip_if` and `run_if` in python source [airflow]

Posted by "phi-friday (via GitHub)" <gi...@apache.org>.
phi-friday commented on code in PR #41832:
URL: https://github.com/apache/airflow/pull/41832#discussion_r1741866840


##########
tests/utils/test_decorators.py:
##########
@@ -0,0 +1,41 @@
+# 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
+
+from airflow.decorators import task
+
+
+def test_remove_skip_if_decorator():
+    @task.skip_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "skip_if" not in source
+
+
+def test_remove_run_if_decorator():
+    @task.run_if(lambda context: True)
+    @task.virtualenv()
+    def f(): ...
+
+    xcom_arg = f()
+    source = xcom_arg.operator.get_python_source()
+
+    assert "run_if" not in source

Review Comment:
   Should I keep only the test code for `run_if` and `skip_if`?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org