text stringlengths 79 3.72M |
|---|
<vulnerable_code>from __future__ import annotations
import json
from decimal import Decimal
from unittest.mock import MagicMock, patch
import pytest
from airflow.providers.amazon.aws.transfers.dynamodb_to_s3 import (
_DEPRECATION_MSG,
DynamoDBToS3Operator,
JSONEncoder,
)
class TestJSONEncoder:
... |
<vulnerable_code>
from airflow import AirflowException
from airflow.decorators import setup, task, task_group, teardown
from airflow.operators.bash import BashOperator
from airflow.utils.task_group import TaskGroup
def test_setup_taskgroup_with_subgroup_being_the_setup_decorated(self, dag_maker):
"""Here,... |
<vulnerable_code>import string
import time
from functools import partial, wraps
from typing import TYPE_CHECKING, Callable, TypeVar, cast
from airflow.configuration import conf
from airflow.exceptions import AirflowConfigException, InvalidStatsNameException
from airflow.typing_compat import Protocol
log = logging.get... |
<vulnerable_code> "queued_at",
"start_date",
"end_date",
"note",
"external_trigger",
"conf",
]<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
"queued_at",
"start_date",
"end_date",
... |
<vulnerable_code> impersonation_chain=self.impersonation_chain,
)
operations = hook.list_transfer_operations(
request_filter={"project_id": self.project_id, "job_names": [self.job_name]}
)
for operation in operations:<commit_title>[PATCH 001/147] Add gitSync optio... |
<vulnerable_code> @mock.patch(
"airflow.providers.google.cloud.sensors.cloud_storage_transfer_service.CloudDataTransferServiceHook"
)
def test_wait_for_status_success_default_expected_status(self, mock_tool):
op = CloudDataTransferServiceJobStatusSensor(
task_id="task-id",
... |
<vulnerable_code><commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
#
# 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 c... |
<vulnerable_code><commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
#
# 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 c... |
<vulnerable_code><commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
#
# 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 c... |
<vulnerable_code>LOADING_KUBE_CONFIG_FILE_RESOURCE = "Loading Kubernetes configuration file kube_config from {}..."
def _load_body_to_dict(body):
try:
body_dict = yaml.safe_load(body)
except yaml.YAMLError as e:
:param namespace: kubernetes namespace
"""
api: client.CustomObjec... |
<vulnerable_code>
from typing import TYPE_CHECKING, Sequence
from airflow.models import BaseOperator
from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook
if TYPE_CHECKING:
from airflow.utils.context import Context
kubernetes_conn_id: str = "kubernetes_default",
api_group: ... |
<vulnerable_code> args = {"owner": "airflow", "start_date": timezone.datetime(2020, 2, 1)}
self.dag = DAG("test_dag_id", default_args=args)
@patch("kubernetes.client.api.custom_objects_api.CustomObjectsApi.delete_namespaced_custom_object")
@patch("kubernetes.client.api.custom_objects_api.CustomO... |
<vulnerable_code> mock_get_client.assert_called_with(cluster_context="test")
assert kubernetes_hook.get_namespace() == "test"
class TestKubernetesHookIncorrectConfiguration:
@pytest.mark.parametrize(<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_descripti... |
<vulnerable_code># under the License.
from __future__ import annotations
import json
from unittest.mock import patch
from airflow import DAG
from airflow.models import Connection
from airflow.providers.cncf.kubernetes.operators.spark_kubernetes import SparkKubernetesOperator
from airflow.utils import db, timezone
TE... |
<vulnerable_code> else (None, None)
)
key_id = self.connection.extra_dejson.get("key_id")
if not key_id:
key_id = self.connection.login
if self.connection.conn_type == "vault":
conn_protocol = "http"
elif self.connection.conn_type == "vaults":... |
<vulnerable_code> :param result_retry: How to retry the `result` call that retrieves rows
:param result_timeout: The number of seconds to wait for `result` method before using `result_retry`
:param deferrable: Run operator in the deferrable mode
"""
template_fields: Sequence[str] = (
result_... |
<vulnerable_code> )
def _emit_true_scheduling_delay_stats_for_finished_state(self, finished_tis: list[TI]) -> None:
"""
This is a helper method to emit the true scheduling delay stats, which is defined as
the time when the first task in DAG starts minus the expected DAG run datetime.... |
<vulnerable_code> """Generates a URL to the Graph view for a DagRun."""
dag_id = attr.get("dag_id")
run_id = attr.get("run_id")
execution_date = attr.get("dag_run.exectuion_date") or attr.get("execution_date")
url = url_for("Airflow.graph", dag_id=dag_id, run_id=run_id, execution_date=execution_date)... |
<vulnerable_code> ):
"""
Run a job in an Apache Spark pool.
:param payload: Livy compatible payload which represents the spark job that a user wants to submit.
"""
job = self.get_conn().spark_batch.create_spark_batch_job(payload)
) -> None:
"""
Cancel the s... |
<vulnerable_code> :param datadog_conn_id: The connection to datadog, containing metadata for api keys.
"""
def __init__(self, datadog_conn_id: str = "datadog_default") -> None:
super().__init__()
conn = self.get_connection(datadog_conn_id)
interval: int | None = None,
) -> dict[s... |
<vulnerable_code>with contextlib.suppress(ImportError, NameError):
from airflow.kubernetes import kube_client
ALLOWED_SPARK_BINARIES = ["spark-submit", "spark2-submit"]
class SparkSubmitHook(BaseHook, LoggingMixin):
supports yarn and k8s mode too.
:param verbose: Whether to pass the verbose flag to s... |
<vulnerable_code> :param env_vars: Environment variables for spark-submit. It supports yarn and k8s mode too. (templated)
:param verbose: Whether to pass the verbose flag to spark-submit process for debugging
:param spark_binary: The command to use for spark submit.
Some distros may ... |
<vulnerable_code> extra='{"spark-binary": "spark2-submit"}',
)
)
db.merge_conn(
Connection(
conn_id="spark_custom_binary_set",
assert connection == expected_spark_connection
assert cmd[0] == "spark2-submit"
def test_resolve_conn... |
<vulnerable_code>from tempfile import NamedTemporaryFile, TemporaryDirectory, gettempdir
from typing import Sequence
from airflow.sensors.base import BaseSensorOperator
from airflow.utils.context import Context
of inheriting the current process environment, which is the default
behavior. (templated)
... |
<vulnerable_code>
import pytest
from airflow.exceptions import AirflowSensorTimeout
from airflow.models.dag import DAG
from airflow.sensors.bash import BashSensor
)
with pytest.raises(AirflowSensorTimeout):
op.execute(None)<commit_title>[PATCH 001/147] Add gitSync optional env description ... |
<vulnerable_code>import re
import warnings
from itertools import chain
from typing import (
Any,
Callable,
from airflow.typing_compat import ParamSpec, Protocol
from airflow.utils import timezone
from airflow.utils.context import KNOWN_CONTEXT_KEYS, Context
from airflow.utils.helpers import prevent_duplicates
f... |
<vulnerable_code># under the License.
from __future__ import annotations
import inspect
from textwrap import dedent
from typing import Callable, Sequence
from airflow.decorators.base import DecoratedOperator, TaskDecorator, task_decorator_factory
from airflow.operators.python import BranchPythonOperator
from airflow.... |
<vulnerable_code># under the License.
from __future__ import annotations
import inspect
from textwrap import dedent
from typing import Callable, Sequence
from airflow.decorators.base import DecoratedOperator, TaskDecorator, task_decorator_factory
from airflow.operators.python import ExternalPythonOperator
from airflo... |
<vulnerable_code> template_fields: Sequence[str] = ("templates_dict", "op_args", "op_kwargs")
template_fields_renderers = {"templates_dict": "json", "op_args": "py", "op_kwargs": "py"}
# since we won't mutate the arguments, we should just do the shallow copy
# there are some cases we can't deepcopy the ... |
<vulnerable_code># under the License.
from __future__ import annotations
import inspect
from textwrap import dedent
from typing import Callable, Sequence
from airflow.decorators.base import DecoratedOperator, TaskDecorator, task_decorator_factory
from airflow.operators.python import PythonVirtualenvOperator
from airf... |
<vulnerable_code># under the License.
from __future__ import annotations
from typing import Callable, Sequence
from airflow.decorators.base import DecoratedOperator, TaskDecorator, task_decorator_factory
from airflow.operators.python import ShortCircuitOperator
multiple XCom values. Dict will unroll to XCom v... |
<vulnerable_code> **kwargs,
)
def _get_python_source(self):
raw_source = inspect.getsource(self.python_callable)
res = dedent(raw_source)
res = remove_task_decorator(res, "@task.kubernetes")
return res
def _generate_cmds(self) -> list[str]:
with o... |
<vulnerable_code>
template_fields: Sequence[str] = (*DockerOperator.template_fields, "op_args", "op_kwargs")
# since we won't mutate the arguments, we should just do the shallow copy
# there are some cases we can't deepcopy the objects (e.g protobuf).
shallow_copy_attrs: Sequence[str] = ("python_callab... |
<vulnerable_code> console_print("PyPI packages prepared")
def push_packages_to_test_pypi():
if confirm_action("Do you want to push packages to test PyPI?"):
run_command(["twine", "upload", "-r", "pypitest", "dist/*"], dry_run_override=DRY_RUN, check=True)
console_print("Packages pushed to t... |
<vulnerable_code> "2.4.3": "e07f49787c9d",
"2.5.0": "290244fb8b83",
"2.5.1": "290244fb8b83",
}
<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
"2.4.3": "e07f49787c9d",
"2.5.0": "290244fb8b83",
"2.5.1": "290244fb8b83",
"2.5.2": "2902... |
<vulnerable_code>HEADERS = ("Version", "Current Patch/Minor", "State", "First Release", "Limited Support", "EOL/Terminated")
SUPPORTED_VERSIONS = (
("2", "2.5.1", "Supported", "Dec 17, 2020", "TBD", "TBD"),
("1.10", "1.10.15", "EOL", "Aug 27, 2018", "Dec 17, 2020", "June 17, 2021"),
("1.9", "1.9.0", "EOL",... |
<vulnerable_code>
def filter_task_group(group, parent_group):
"""Exclude tasks not included in the subdag from the given TaskGroup."""
copied = copy.copy(group)
copied.used_group_ids = set(copied.used_group_ids)
copied._parent_group = parent_group
cop... |
<vulnerable_code>import pickle
import re
import sys
from contextlib import redirect_stdout
from datetime import timedelta
from pathlib import Path
assert dag.task_dict == {op1.task_id: op1, op3.task_id: op3}
assert dag.task_dict == {op2.task_id: op2, op3.task_id: op3}
def test_sub_dag_updates_all_r... |
<vulnerable_code> )
directory.mkdir(mode=new_folder_permissions, parents=True, exist_ok=True)
if directory.stat().st_mode % 0o1000 != new_folder_permissions % 0o1000:
print(f"Changing dir permission to {new_folder_permissions}")
directory.chmod(new_folder_permissions)
... |
<vulnerable_code> option_additional_extras,
option_additional_pip_install_flags,
option_additional_python_deps,
option_airflow_constraints_mode_ci,
option_airflow_constraints_reference_build,
option_answer,
@option_dev_apt_deps
@option_force_build
@option_python_image
@option_airflow_constraints_... |
<vulnerable_code> "options": [
"--builder",
"--install-providers-from-sources",
"--airflow-constraints-mode",
"--airflow-constraints-reference",
"--python-image",<commit_title>[PATCH 001/147] Add gitSync optional env description ... |
<vulnerable_code> option_additional_runtime_apt_command,
option_additional_runtime_apt_deps,
option_additional_runtime_apt_env,
option_airflow_constraints_mode_prod,
option_airflow_constraints_reference_build,
option_builder,
@option_prepare_buildx_cache
@option_push
@option_empty_image
@option_a... |
<vulnerable_code> "--builder",
"--install-providers-from-sources",
"--airflow-extras",
"--airflow-constraints-mode",
"--airflow-constraints-reference",
"--python-image",<commit_title>[PATCH 001/147] Add gitSync optional env d... |
<vulnerable_code> default=DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH,
envvar="AIRFLOW_CONSTRAINTS_REFERENCE",
)
option_airflow_constraints_reference_build = click.option(
"--airflow-constraints-reference",
default=DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH,<commit_title>[PATCH 001/147] Add gitSync optional env descripti... |
<vulnerable_code> ("NOTICE", "/opt/airflow/NOTICE"),
("RELEASE_NOTES.rst", "/opt/airflow/RELEASE_NOTES.rst"),
("airflow", "/opt/airflow/airflow"),
("provider_packages", "/opt/airflow/provider_packages"),
("dags", "/opt/airflow/dags"),
("dev", "/opt/airflow/dev"),<commit_title>[PATCH 001/147] Add ... |
<vulnerable_code> sync_hook = await self.get_sync_hook()
return sync_hook.project_id
async def get_transfer_run(
self,
config_id: str,
run_id: str,
project_id: str | None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
m... |
<vulnerable_code>
def execute(self, context: Context):
self.log.info("Submitting manual transfer for %s", self.transfer_config_id)
response = self.hook.start_manual_transfer_runs(
transfer_config_id=self.transfer_config_id,
requested_time_range=self.requested_time_range,<comm... |
<vulnerable_code> project_id=self.project_id,
config_id=self.config_id,
run_id=self.run_id,
)
state = transfer_run.state
self.log.info("Current state is %s", state)<commit_title>[PATCH 001/147] Add gitSync optiona... |
<vulnerable_code>
has_kubernetes = True
def _disable_verify_ssl() -> None:
if hasattr(Configuration, "get_default_copy"):
configuration = Configuration.get_default_copy()
else:
configuration = Configuration()
configuration.verify_ssl = False
Configuration... |
<vulnerable_code> @mock.patch("airflow.kubernetes.kube_client.conf")
def test_load_config_disable_ssl(self, conf, config):
conf.getboolean.return_value = False
get_kube_client(in_cluster=False)
conf.getboolean.assert_called_with("kubernetes_executor", "verify_ssl")
# Support wide ... |
<vulnerable_code> until the sensor times out (thus giving you time to retry the external task
without also having to clear the sensor).
It is possible to alter the default behavior by setting states which
cause the sensor to fail, e.g. by setting ``allowed_states=[State.FAILED]``
and ``failed_states... |
<vulnerable_code> dag=self.dag,
)
assert (
str(ctx.value) == "Only one of `external_task_group_id` or `external_task_id` may "
"be provided to ExternalTaskSensor; "
"use external_task_id or external_task_ids or external_task_group_id."
)
... |
<vulnerable_code>"""Plugin to demonstrate timetable registration and accommodate example DAGs."""
from __future__ import annotations
# [START howto_timetable]
from datetime import timedelta
from pendulum import UTC, Date, DateTime, Time
from airflow.plugins_manager import AirflowPlugin
class AfterWorkdayTimetable(... |
<vulnerable_code>START_DATE = pendulum.DateTime(2021, 9, 4, tzinfo=TIMEZONE) # This is a Saturday.
WEEK_1_WEEKDAYS = [
pendulum.DateTime(2021, 9, 6, tzinfo=TIMEZONE),
pendulum.DateTime(2021, 9, 7, tzinfo=TIMEZONE),
pendulum.DateTime(2021, 9, 8, tzinfo=TIMEZONE),
pendulum.DateTime(2021, 9, 9, tzinfo=TI... |
<vulnerable_code> :return: Specific map index or map indexes to pull, or ``None`` if we
want to "whole" return value (i.e. no mapped task groups involved).
"""
# Find the innermost common mapped task group between the current task
# If the current task and the referenced task ... |
<vulnerable_code> assert sorted(tis) == [("t3", -1)]
def test_mapped_task_check_before_expand(dag_maker, session):
with dag_maker(session=session):
<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
assert sorted(tis) == [("t3", -1)]
def test_upstr... |
<vulnerable_code>
from airflow.models.baseoperator import chain
from airflow.models.dag import DAG
from airflow.providers.amazon.aws.hooks.eks import ClusterStates, FargateProfileStates
from airflow.providers.amazon.aws.operators.eks import (
EksCreateClusterOperator,
labels={"demo": "hello_world"},
... |
<vulnerable_code>
from airflow.models.baseoperator import chain
from airflow.models.dag import DAG
from airflow.providers.amazon.aws.hooks.eks import ClusterStates, FargateProfileStates
from airflow.providers.amazon.aws.operators.eks import (
EksCreateClusterOperator,
cmds=["sh", "-c", "echo Test Airflow; d... |
<vulnerable_code>
from airflow.models.baseoperator import chain
from airflow.models.dag import DAG
from airflow.providers.amazon.aws.hooks.eks import ClusterStates, NodegroupStates
from airflow.providers.amazon.aws.operators.eks import (
EksCreateClusterOperator,
cmds=["sh", "-c", "echo Test Airflow; date"]... |
<vulnerable_code>
from airflow.models.baseoperator import chain
from airflow.models.dag import DAG
from airflow.providers.amazon.aws.hooks.eks import ClusterStates, NodegroupStates
from airflow.providers.amazon.aws.operators.eks import (
EksCreateClusterOperator,
)
# [END howto_operator_eks_pod_operator]
... |
<vulnerable_code>
import json
import warnings
import hvac
from hvac.exceptions import VaultError
else (None, None)
)
if self.connection.conn_type == "vault":
conn_protocol = "http"
elif self.connection.conn_type == "vaults":
conn_protocol = "https"
e... |
<vulnerable_code> test_client.is_authenticated.assert_called_with()
assert 2 == test_hook.vault_client.kv_engine_version
@mock.patch("airflow.providers.hashicorp.hooks.vault.VaultHook.get_connection")
@mock.patch("airflow.providers.hashicorp._internal_client.vault_client.hvac")
def test_appr... |
<vulnerable_code> )
@click.command(
name="start-rc-process",
short_help="Start RC process",
# Create issue for testing
os.chdir(airflow_repo_root)
create_issue_for_testing(version, previous_version, github_token)
console_print()
console_print("Done!")<commit_title>[PATCH 001/147... |
<vulnerable_code> template_fields: Sequence[str] = ("op_args", "op_kwargs")
template_fields_renderers: dict[str, str] = {"op_args": "py", "op_kwargs": "py"}
# since we won't mutate the arguments, we should just do the shallow copy
# there are some cases we can't deepcopy the objects (e.g protobuf).
... |
<vulnerable_code> from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_babel import lazy_gettext
from wtforms import BooleanField, IntegerField, StringField
from wtforms.validators import NumberRange, any_of
return {
"auth_type": StringField(lazy_ge... |
<vulnerable_code><commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional inf... |
<vulnerable_code>
import pytest
from airflow.cli import cli_parser
from tests.test_utils.config import conf_vars
# Can not be `--snake_case` or contain uppercase letter
all_command_as_args = [
command_as_args
for top_command in cli_parser.dag_cli_commands
for command_as_ar... |
<vulnerable_code> )
def test_async_create_build_trigger_serialization_should_execute_successfully():
"""
Asserts that the CloudBuildCreateBuildTrigger correctly serializes its arguments
and classpath.
"""
trigger = CloudBuildCreateBuildTrigger(
id_=TEST_BUILD_ID,
project_id=TEST... |
<vulnerable_code>
from airflow.providers.google.cloud.triggers.dataflow import TemplateJobStartTrigger
from airflow.triggers.base import TriggerEvent
if sys.version_info < (3, 8):
from asynctest import mock
else:
from unittest import mock
PROJECT_ID = "test-project-id"
JOB_ID = "test_job_id_2012-12-23-10:00"
... |
<vulnerable_code>TEST_HOOK_PARAMS = {}
def test_gcs_blob_trigger_serialization():
"""
Asserts that the GCSBlobTrigger correctly serializes its arguments
and classpath.
"""
trigger = GCSBlobTrigger(
TEST_BUCKET,
TEST_OBJECT,
TEST_POLLING_INTERVAL,
TEST_GCP_CONN_ID,
... |
<vulnerable_code>
import asyncio
import logging
import sys
import pytest
from airflow.providers.google.cloud.triggers.mlengine import MLEngineStartTrainingJobTrigger
from airflow.triggers.base import TriggerEvent
if sys.version_info < (3, 8):
from asynctest import mock
else:
from unittest import mock
TEST_C... |
<vulnerable_code> if conf.getboolean("database", "LOAD_DEFAULT_CONNECTIONS") and load_connections:
create_default_connections(session=session)
# Add default pool & sync log_template
add_default_pool_if_not_exists()
synchronize_log_template()
def _get_alembic_config():
This checks if the las... |
<vulnerable_code>from flask_appbuilder import SQLA
from flask_caching import Cache
from flask_wtf.csrf import CSRFProtect
from sqlalchemy.engine.url import make_url
from airflow import settings
flask_app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=settings.get_session_lifetime_config())
flask_app... |
<vulnerable_code>from airflow.jobs.base_job import BaseJob
from airflow.utils import timezone
from airflow.utils.session import create_session
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.config import conf_vars
from tests.test_utils.www import check_content_in_response, check_content... |
<vulnerable_code> "PYTHON_MAJOR_MINOR_VERSION": "python",
"SKIP_CONSTRAINTS": "skip_constraints",
"SKIP_ENVIRONMENT_INITIALIZATION": "skip_environment_initialization",
"SKIP_PROVIDER_TESS": "skip_provider_tests",
"SQLITE_URL": "sqlite_url",
"START_AIRFLOW": "start_airflow",
"USE_AIRFLOW_VERSI... |
<vulnerable_code>from airflow.utils.session import NEW_SESSION, create_session, provide_session
from airflow.utils.state import State, TaskInstanceState
from airflow.utils.strings import to_boolean
from airflow.utils.task_group import MappedTaskGroup, task_group_to_dict
from airflow.utils.timezone import td_format, utc... |
<vulnerable_code> "is_mapped": False,
"label": "task1",
"operator": "EmptyOperator",
},
{
"children": [
"is_mapped": True,
"label": "subtask2",
... |
<vulnerable_code> return wrapper
def teardown_task(python_callable: Callable) -> Callable:
# Using FunctionType here since _TaskDecorator is also a callable
if isinstance(python_callable, types.FunctionType):
python_callable = python_task(python_callable)
@functools.wraps(python_callable)
... |
<vulnerable_code> add_suffix_on_collision: bool = False,
setup: bool = False,
teardown: bool = False,
) -> Callable[[Callable[FParams, FReturn]], _TaskGroupFactory[FParams, FReturn]]:
...
<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
add_s... |
<vulnerable_code>
_is_setup = False
_is_teardown = False
def __init__(
self,
def as_teardown(cls, *args, **kwargs):
from airflow.utils.setup_teardown import SetupTeardownContext
with SetupTeardownContext.teardown():
return cls(*args, **kwargs)
def __eq__(self, ... |
<vulnerable_code>
is_setup: bool = False
is_teardown: bool = False
@classmethod
@contextmanager
@classmethod
@contextmanager
def teardown(cls):
if cls.is_setup or cls.is_teardown:
raise AirflowException(
"A teardown task or taskgroup cannot be nested ins... |
<vulnerable_code> add_suffix_on_collision: bool = False,
setup: bool = False,
teardown: bool = False,
):
from airflow.models.dag import DagContext
if setup and teardown:
raise AirflowException("Cannot set both setup and teardown to True")
self.prefix_grou... |
<vulnerable_code> assert setup_task._is_setup
def test_marking_operator_as_setup_task(self, dag_maker):
with dag_maker() as dag:
BashOperator.as_setup(task_id="mytask", bash_command='echo "I am a setup task"')
assert teardown_task._is_teardown
def test_marking_operator_as_t... |
<vulnerable_code>
import airflow
from airflow.datasets import Dataset
from airflow.exceptions import AirflowException, SerializationError
from airflow.hooks.base import BaseHook
from airflow.kubernetes.pod_generator import PodGenerator
from airflow.models.param import Param, ParamsDict
from airflow.models.xcom import X... |
<vulnerable_code> "wheel",
"yamllint",
"aioresponses",
]
<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
"wheel",
"yamllint",
"aioresponses",
# This required for AWS deferrable operators.
# There is conflict between boto3 and ai... |
<vulnerable_code>except ImportError:
pass
pytest.importorskip("aiobotocore")
class TestAwsBaseAsyncHook:
@staticmethod<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
except ImportError:
pass
class TestAwsBaseAsyncHook:
@staticmethod |
<vulnerable_code>from airflow.providers.amazon.aws.hooks.redshift_cluster import RedshiftAsyncHook
from tests.providers.amazon.aws.utils.compat import async_mock
pytest.importorskip("aiobotocore")
class TestRedshiftAsyncHook:
@pytest.mark.asyncio<commit_title>[PATCH 001/147] Add gitSync optional env description ... |
<vulnerable_code># under the License.
from __future__ import annotations
import importlib.util
import pytest
from airflow.providers.amazon.aws.triggers.redshift_cluster import (
POLLING_PERIOD_SECONDS = 1.0
@pytest.mark.skipif(not bool(importlib.util.find_spec("aiobotocore")), reason="aiobotocore require")
class T... |
<vulnerable_code>COMMENT_PATTERN = re.compile(r"\s*#.*")
def might_contain_dag(file_path: str, safe_mode: bool, zip_file: zipfile.ZipFile | None = None):
"""
Heuristic that guesses whether a Python file contains an Airflow DAG definition.
:param file_path: Path to the file to be checked.
:param safe_... |
<vulnerable_code>
import os
import os.path
from pathlib import Path
from unittest import mock
import pytest
from airflow.utils.file import correct_maybe_zipped, find_path_from_directory, open_maybe_zipped
from tests.models import TEST_DAGS_FOLDER
class TestCorrectMaybeZipped:
f"Detected recursive lo... |
<vulnerable_code>"""Task sub-commands."""
from __future__ import annotations
import datetime
import importlib
import json
import logging
from contextlib import contextmanager, redirect_stderr, redirect_stdout, suppress
from typing import Generator, Union
from pendulum.parsing.exceptions import ParserError
from sqlalc... |
<vulnerable_code>
cls.dag = cls.dagbag.get_dag(cls.dag_id)
cls.dagbag.sync_to_db()
cls.dag_run = cls.dag.create_dagrun(
state=State.NONE, run_id=cls.run_id, run_type=DagRunType.MANUAL, execution_date=DEFAULT_DATE
)
@classmethod
dag = dagbag.get_dag("test_dags... |
<vulnerable_code>from airflow.stats import Stats
from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
from airflow.timetables.interval import CronDataIntervalTimetable, DeltaDataIntervalTimetable
from airflow.timetables.simple import DatasetTriggeredTimetable, NullTimetable, OnceTime... |
<vulnerable_code> This should be a list of field names on the DAG run object.
"""
@classmethod
def deserialize(cls, data: dict[str, Any]) -> Timetable:
"""Deserialize a timetable from data.<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>... |
<vulnerable_code>import operator
from typing import TYPE_CHECKING, Any, Collection
from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
if TYPE_CHECKING:
from pendulum import DateTime
from sqlalchemy import Session
from airflow.models.dataset import DatasetEvent
... |
<vulnerable_code>from airflow.security import permissions
from airflow.templates import NativeEnvironment, SandboxedEnvironment
from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
from airflow.timetables.simple import DatasetTriggeredTimetable, NullTimetable, OnceTimetable
from airf... |
<vulnerable_code><commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
# 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 cop... |
<vulnerable_code> == "test_label_value"
)
def test_cleanup_resources_are_configurable(self):
resources = {
"requests": {<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
== "test_label_value"
)
... |
<vulnerable_code> )
assert jmespath.search("spec.template.spec.containers[0].args", docs[0]) == args<commit_title>[PATCH 001/147] Add gitSync optional env description (#29378)<commit_description><fixed_code>
)
assert jmespath.search("spec.template.spec.containers[0].args", docs[0]) == a... |
<vulnerable_code> hello()
my_teardown()
@task_group
def section_2():
# You can also mark task groups as setup and teardown
# and all tasks in them will be setup/teardown tasks
@setup
@task_group
def my_setup_taskgroup():
@task
def f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.