response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Tests DAG with Tasks created with *Operators and TaskGroup created with taskgroup decorator | def test_build_task_group_with_operators():
"""Tests DAG with Tasks created with *Operators and TaskGroup created with taskgroup decorator"""
from airflow.decorators import task
def task_start():
"""Dummy Task which is First Task of Dag"""
return "[Task_start]"
def task_end():
"""Dummy Task which is Last Task of Dag"""
print("[ Task_End ]")
# Creating Tasks
@task
def task_1(value):
"""Dummy Task1"""
return f"[ Task1 {value} ]"
@task
def task_2(value):
"""Dummy Task2"""
return f"[ Task2 {value} ]"
@task
def task_3(value):
"""Dummy Task3"""
print(f"[ Task3 {value} ]")
# Creating TaskGroups
@task_group_decorator(group_id="section_1")
def section_a(value):
"""TaskGroup for grouping related Tasks"""
return task_3(task_2(task_1(value)))
execution_date = pendulum.parse("20201109")
with DAG(dag_id="example_task_group_decorator_mix", start_date=execution_date, tags=["example"]) as dag:
t_start = PythonOperator(task_id="task_start", python_callable=task_start, dag=dag)
sec_1 = section_a(t_start.output)
t_end = PythonOperator(task_id="task_end", python_callable=task_end, dag=dag)
sec_1.set_downstream(t_end)
# Testing Tasks in DAG
assert set(dag.task_group.children.keys()) == {"section_1", "task_start", "task_end"}
assert set(dag.task_group.children["section_1"].children.keys()) == {
"section_1.task_2",
"section_1.task_3",
"section_1.task_1",
}
# Testing Tasks downstream
assert dag.task_dict["task_start"].downstream_task_ids == {"section_1.task_1"}
assert dag.task_dict["section_1.task_3"].downstream_task_ids == {"task_end"} |
Test cases to check nested TaskGroup context manager with taskgroup decorator | def test_task_group_context_mix():
"""Test cases to check nested TaskGroup context manager with taskgroup decorator"""
from airflow.decorators import task
def task_start():
"""Dummy Task which is First Task of Dag"""
return "[Task_start]"
def task_end():
"""Dummy Task which is Last Task of Dag"""
print("[ Task_End ]")
# Creating Tasks
@task
def task_1(value):
"""Dummy Task1"""
return f"[ Task1 {value} ]"
@task
def task_2(value):
"""Dummy Task2"""
return f"[ Task2 {value} ]"
@task
def task_3(value):
"""Dummy Task3"""
print(f"[ Task3 {value} ]")
# Creating TaskGroups
@task_group_decorator
def section_2(value):
"""TaskGroup for grouping related Tasks"""
return task_3(task_2(task_1(value)))
execution_date = pendulum.parse("20201109")
with DAG(dag_id="example_task_group_decorator_mix", start_date=execution_date, tags=["example"]) as dag:
t_start = PythonOperator(task_id="task_start", python_callable=task_start, dag=dag)
with TaskGroup("section_1", tooltip="section_1") as section_1:
sec_2 = section_2(t_start.output)
task_s1 = EmptyOperator(task_id="task_1")
task_s2 = BashOperator(task_id="task_2", bash_command="echo 1")
task_s3 = EmptyOperator(task_id="task_3")
sec_2.set_downstream(task_s1)
task_s1 >> [task_s2, task_s3]
t_end = PythonOperator(task_id="task_end", python_callable=task_end, dag=dag)
t_start >> section_1 >> t_end
node_ids = {
"id": None,
"children": [
{
"id": "section_1",
"children": [
{
"id": "section_1.section_2",
"children": [
{"id": "section_1.section_2.task_1"},
{"id": "section_1.section_2.task_2"},
{"id": "section_1.section_2.task_3"},
],
},
{"id": "section_1.task_1"},
{"id": "section_1.task_2"},
{"id": "section_1.task_3"},
{"id": "section_1.upstream_join_id"},
{"id": "section_1.downstream_join_id"},
],
},
{"id": "task_end"},
{"id": "task_start"},
],
}
assert extract_node_id(task_group_to_dict(dag.task_group)) == node_ids |
Testing TaskGroup with default_args | def test_default_args():
"""Testing TaskGroup with default_args"""
execution_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_default_args",
start_date=execution_date,
default_args={
"owner": "dag",
},
):
with TaskGroup("group1", default_args={"owner": "group"}):
task_1 = EmptyOperator(task_id="task_1")
task_2 = EmptyOperator(task_id="task_2", owner="task")
task_3 = EmptyOperator(task_id="task_3", default_args={"owner": "task"})
assert task_1.owner == "group"
assert task_2.owner == "task"
assert task_3.owner == "task" |
Testing automatic suffix assignment for duplicate group_id | def test_duplicate_task_group_id():
"""Testing automatic suffix assignment for duplicate group_id"""
from airflow.decorators import task
@task(task_id="start_task")
def task_start():
"""Dummy Task which is First Task of Dag"""
print("[Task_start]")
@task(task_id="end_task")
def task_end():
"""Dummy Task which is Last Task of Dag"""
print("[Task_End]")
# Creating Tasks
@task(task_id="task")
def task_1():
"""Dummy Task1"""
print("[Task1]")
@task(task_id="task")
def task_2():
"""Dummy Task2"""
print("[Task2]")
@task(task_id="task1")
def task_3():
"""Dummy Task3"""
print("[Task3]")
@task_group_decorator("task_group1")
def task_group1():
task_start()
task_1()
task_2()
@task_group_decorator(group_id="task_group1")
def task_group2():
task_3()
@task_group_decorator(group_id="task_group1")
def task_group3():
task_end()
execution_date = pendulum.parse("20201109")
with DAG(dag_id="example_duplicate_task_group_id", start_date=execution_date, tags=["example"]) as dag:
task_group1()
task_group2()
task_group3()
node_ids = {
"id": None,
"children": [
{
"id": "task_group1",
"children": [
{"id": "task_group1.start_task"},
{"id": "task_group1.task"},
{"id": "task_group1.task__1"},
],
},
{"id": "task_group1__1", "children": [{"id": "task_group1__1.task1"}]},
{"id": "task_group1__2", "children": [{"id": "task_group1__2.end_task"}]},
],
}
assert extract_node_id(task_group_to_dict(dag.task_group)) == node_ids |
Test for using same taskgroup decorated function twice | def test_call_taskgroup_twice():
"""Test for using same taskgroup decorated function twice"""
from airflow.decorators import task
@task(task_id="start_task")
def task_start():
"""Dummy Task which is First Task of Dag"""
print("[Task_start]")
@task(task_id="end_task")
def task_end():
"""Dummy Task which is Last Task of Dag"""
print("[Task_End]")
# Creating Tasks
@task(task_id="task")
def task_1():
"""Dummy Task1"""
print("[Task1]")
@task_group_decorator
def task_group1(name: str):
print(f"Starting taskgroup {name}")
task_start()
task_1()
task_end()
execution_date = pendulum.parse("20201109")
with DAG(dag_id="example_multi_call_task_groups", start_date=execution_date, tags=["example"]) as dag:
task_group1("Call1")
task_group1("Call2")
node_ids = {
"id": None,
"children": [
{
"id": "task_group1",
"children": [
{"id": "task_group1.end_task"},
{"id": "task_group1.start_task"},
{"id": "task_group1.task"},
],
},
{
"id": "task_group1__1",
"children": [
{"id": "task_group1__1.end_task"},
{"id": "task_group1__1.start_task"},
{"id": "task_group1__1.task"},
],
},
],
}
assert extract_node_id(task_group_to_dict(dag.task_group)) == node_ids |
Test that the output of a task group can be passed to a task. | def test_pass_taskgroup_output_to_task():
"""Test that the output of a task group can be passed to a task."""
from airflow.decorators import task
@task
def one():
return 1
@task_group_decorator
def addition_task_group(num):
@task
def add_one(i):
return i + 1
return add_one(num)
@task
def increment(num):
return num + 1
@dag(schedule=None, start_date=pendulum.DateTime(2022, 1, 1), default_args={"owner": "airflow"})
def wrap():
total_1 = one()
assert isinstance(total_1, XComArg)
total_2 = addition_task_group(total_1)
assert isinstance(total_2, XComArg)
total_3 = increment(total_2)
assert isinstance(total_3, XComArg)
wrap() |
Test that unknown args passed to the decorator cause an error at parse time | def test_decorator_unknown_args():
"""Test that unknown args passed to the decorator cause an error at parse time"""
with pytest.raises(TypeError):
@task_group_decorator(b=2)
def tg(): ... |
When recursing upstream for a non-teardown leaf, we should ignore setups that
are direct upstream of a teardown. | def test_task_group_arrow_with_setup_group_deeper_setup():
"""
When recursing upstream for a non-teardown leaf, we should ignore setups that
are direct upstream of a teardown.
"""
with DAG(dag_id="setup_group_teardown_group_2", start_date=pendulum.now()):
with TaskGroup("group_1") as g1:
@setup
def setup_1(): ...
@setup
def setup_2(): ...
@teardown
def teardown_0(): ...
s1 = setup_1()
s2 = setup_2()
t0 = teardown_0()
s2 >> t0
with TaskGroup("group_2") as g2:
@teardown
def teardown_1(): ...
@teardown
def teardown_2(): ...
t1 = teardown_1()
t2 = teardown_2()
@task_decorator
def work(): ...
w1 = work()
g1 >> w1 >> g2
t1.as_teardown(setups=s1)
t2.as_teardown(setups=s2)
assert set(s1.operator.downstream_task_ids) == {"work", "group_2.teardown_1"}
assert set(s2.operator.downstream_task_ids) == {"group_1.teardown_0", "group_2.teardown_2"}
assert set(w1.operator.downstream_task_ids) == {"group_2.teardown_1", "group_2.teardown_2"}
assert set(t1.operator.downstream_task_ids) == set()
assert set(t2.operator.downstream_task_ids) == set() |
The default format provides no prefix. | def test_custom_formatter_default_format(task_instance):
"""The default format provides no prefix."""
assert_prefix(task_instance, "") |
Make sure DagRunType.SCHEDULE is converted to string 'scheduled' when
referenced in DB query | def test_runtype_enum_escape():
"""
Make sure DagRunType.SCHEDULE is converted to string 'scheduled' when
referenced in DB query
"""
with create_session() as session:
dag = DAG(dag_id="test_enum_dags", start_date=DEFAULT_DATE)
data_interval = dag.timetable.infer_manual_data_interval(run_after=DEFAULT_DATE)
dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
data_interval=data_interval,
)
query = session.query(
DagRun.dag_id,
DagRun.state,
DagRun.run_type,
).filter(
DagRun.dag_id == dag.dag_id,
# make sure enum value can be used in filter queries
DagRun.run_type == DagRunType.SCHEDULED,
)
assert str(query.statement.compile(compile_kwargs={"literal_binds": True})) == (
"SELECT dag_run.dag_id, dag_run.state, dag_run.run_type \n"
"FROM dag_run \n"
"WHERE dag_run.dag_id = 'test_enum_dags' AND dag_run.run_type = 'scheduled'"
)
rows = query.all()
assert len(rows) == 1
assert rows[0].dag_id == dag.dag_id
assert rows[0].state == State.RUNNING
# make sure value in db is stored as `scheduled`, not `DagRunType.SCHEDULED`
assert rows[0].run_type == "scheduled"
session.rollback() |
Returns the current line number in our program. | def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno |
Test that _mark_task_instance_state() does all three things:
- Marks the given TaskInstance as SUCCESS;
- Clears downstream TaskInstances in FAILED/UPSTREAM_FAILED state;
- Set DagRun to QUEUED. | def test_mark_task_instance_state(test_app):
"""
Test that _mark_task_instance_state() does all three things:
- Marks the given TaskInstance as SUCCESS;
- Clears downstream TaskInstances in FAILED/UPSTREAM_FAILED state;
- Set DagRun to QUEUED.
"""
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.empty import EmptyOperator
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timezone import datetime
from airflow.utils.types import DagRunType
from airflow.www.views import Airflow
from tests.test_utils.db import clear_db_runs
clear_db_runs()
start_date = datetime(2020, 1, 1)
with DAG("test_mark_task_instance_state", start_date=start_date) as dag:
task_1 = EmptyOperator(task_id="task_1")
task_2 = EmptyOperator(task_id="task_2")
task_3 = EmptyOperator(task_id="task_3")
task_4 = EmptyOperator(task_id="task_4")
task_5 = EmptyOperator(task_id="task_5")
task_1 >> [task_2, task_3, task_4, task_5]
dagrun = dag.create_dagrun(
start_date=start_date,
execution_date=start_date,
data_interval=(start_date, start_date),
state=State.FAILED,
run_type=DagRunType.SCHEDULED,
)
def get_task_instance(session, task):
return (
session.query(TaskInstance)
.filter(
TaskInstance.dag_id == dag.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.execution_date == start_date,
)
.one()
)
with create_session() as session:
get_task_instance(session, task_1).state = State.FAILED
get_task_instance(session, task_2).state = State.SUCCESS
get_task_instance(session, task_3).state = State.UPSTREAM_FAILED
get_task_instance(session, task_4).state = State.FAILED
get_task_instance(session, task_5).state = State.SKIPPED
session.commit()
test_app.dag_bag = DagBag(dag_folder="/dev/null", include_examples=False)
test_app.dag_bag.bag_dag(dag=dag, root_dag=dag)
with test_app.test_request_context():
view = Airflow()
view._mark_task_instance_state(
dag_id=dag.dag_id,
run_id=dagrun.run_id,
task_id=task_1.task_id,
map_indexes=None,
origin="",
upstream=False,
downstream=False,
future=False,
past=False,
state=State.SUCCESS,
)
with create_session() as session:
# After _mark_task_instance_state, task_1 is marked as SUCCESS
assert get_task_instance(session, task_1).state == State.SUCCESS
# task_2 remains as SUCCESS
assert get_task_instance(session, task_2).state == State.SUCCESS
# task_3 and task_4 are cleared because they were in FAILED/UPSTREAM_FAILED state
assert get_task_instance(session, task_3).state == State.NONE
assert get_task_instance(session, task_4).state == State.NONE
# task_5 remains as SKIPPED
assert get_task_instance(session, task_5).state == State.SKIPPED
dagrun.refresh_from_db(session=session)
# dagrun should be set to QUEUED
assert dagrun.get_state() == State.QUEUED |
Test that _mark_task_group_state() does all three things:
- Marks the given TaskGroup as SUCCESS;
- Clears downstream TaskInstances in FAILED/UPSTREAM_FAILED state;
- Set DagRun to QUEUED. | def test_mark_task_group_state(test_app):
"""
Test that _mark_task_group_state() does all three things:
- Marks the given TaskGroup as SUCCESS;
- Clears downstream TaskInstances in FAILED/UPSTREAM_FAILED state;
- Set DagRun to QUEUED.
"""
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.empty import EmptyOperator
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timezone import datetime
from airflow.utils.types import DagRunType
from airflow.www.views import Airflow
from tests.test_utils.db import clear_db_runs
clear_db_runs()
start_date = datetime(2020, 1, 1)
with DAG("test_mark_task_group_state", start_date=start_date) as dag:
start = EmptyOperator(task_id="start")
with TaskGroup("section_1", tooltip="Tasks for section_1") as section_1:
task_1 = EmptyOperator(task_id="task_1")
task_2 = EmptyOperator(task_id="task_2")
task_3 = EmptyOperator(task_id="task_3")
task_1 >> [task_2, task_3]
task_4 = EmptyOperator(task_id="task_4")
task_5 = EmptyOperator(task_id="task_5")
task_6 = EmptyOperator(task_id="task_6")
task_7 = EmptyOperator(task_id="task_7")
task_8 = EmptyOperator(task_id="task_8")
start >> section_1 >> [task_4, task_5, task_6, task_7, task_8]
dagrun = dag.create_dagrun(
start_date=start_date,
execution_date=start_date,
data_interval=(start_date, start_date),
state=State.FAILED,
run_type=DagRunType.SCHEDULED,
)
def get_task_instance(session, task):
return (
session.query(TaskInstance)
.filter(
TaskInstance.dag_id == dag.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.execution_date == start_date,
)
.one()
)
with create_session() as session:
get_task_instance(session, task_1).state = State.FAILED
get_task_instance(session, task_2).state = State.SUCCESS
get_task_instance(session, task_3).state = State.UPSTREAM_FAILED
get_task_instance(session, task_4).state = State.SUCCESS
get_task_instance(session, task_5).state = State.UPSTREAM_FAILED
get_task_instance(session, task_6).state = State.FAILED
get_task_instance(session, task_7).state = State.SKIPPED
session.commit()
test_app.dag_bag = DagBag(dag_folder="/dev/null", include_examples=False)
test_app.dag_bag.bag_dag(dag=dag, root_dag=dag)
with test_app.test_request_context():
view = Airflow()
view._mark_task_group_state(
dag_id=dag.dag_id,
run_id=dagrun.run_id,
group_id=section_1.group_id,
origin="",
upstream=False,
downstream=False,
future=False,
past=False,
state=State.SUCCESS,
)
with create_session() as session:
# After _mark_task_group_state, task_1 is marked as SUCCESS
assert get_task_instance(session, task_1).state == State.SUCCESS
# task_2 should remain as SUCCESS
assert get_task_instance(session, task_2).state == State.SUCCESS
# task_3 should be marked as SUCCESS
assert get_task_instance(session, task_3).state == State.SUCCESS
# task_4 should remain as SUCCESS
assert get_task_instance(session, task_4).state == State.SUCCESS
# task_5 and task_6 are cleared because they were in FAILED/UPSTREAM_FAILED state
assert get_task_instance(session, task_5).state == State.NONE
assert get_task_instance(session, task_6).state == State.NONE
# task_7 remains as SKIPPED
assert get_task_instance(session, task_7).state == State.SKIPPED
dagrun.refresh_from_db(session=session)
# dagrun should be set to QUEUED
assert dagrun.get_state() == State.QUEUED |
Test invalid date format doesn't crash page. | def test_invalid_dates(app, admin_client, url, content):
"""Test invalid date format doesn't crash page."""
resp = admin_client.get(url, follow_redirects=True)
assert resp.status_code == 400
assert re.search(content, resp.get_data().decode()) |
Clean up stray garbage from other tests. | def reset_dagruns():
"""Clean up stray garbage from other tests."""
clear_db_runs() |
Pause a DAG so we can test filtering. | def setup_paused_dag():
"""Pause a DAG so we can test filtering."""
dag_to_pause = "example_branch_operator"
with create_session() as session:
session.query(DagModel).filter(DagModel.dag_id == dag_to_pause).update({"is_paused": True})
yield
with create_session() as session:
session.query(DagModel).filter(DagModel.dag_id == dag_to_pause).update({"is_paused": False}) |
Test the /blocked endpoint works when a DAG is deleted.
When a DAG is bagged, it is written to both DagModel and SerializedDagModel,
but its subdags are only written to DagModel (without serialization). Thus,
``DagBag.get_dag(subdag_id)`` would raise ``SerializedDagNotFound`` if the
subdag was not previously bagged in the dagbag (perhaps due to its root DAG
being deleted). ``DagBag.get_dag()`` calls should catch the exception and
properly handle this situation. | def test_blocked_subdag_success(admin_client, running_subdag):
"""Test the /blocked endpoint works when a DAG is deleted.
When a DAG is bagged, it is written to both DagModel and SerializedDagModel,
but its subdags are only written to DagModel (without serialization). Thus,
``DagBag.get_dag(subdag_id)`` would raise ``SerializedDagNotFound`` if the
subdag was not previously bagged in the dagbag (perhaps due to its root DAG
being deleted). ``DagBag.get_dag()`` calls should catch the exception and
properly handle this situation.
"""
resp = admin_client.post("/blocked", data={"dag_ids": [running_subdag.dag_id]})
assert resp.status_code == 200
assert resp.json == [
{
"dag_id": running_subdag.dag_id,
"active_dag_run": 1,
"max_active_runs": 0, # Default value for an unserialized DAG.
},
] |
When populating custom fields in the connection form we should first check for the non-prefixed
value (since prefixes in extra are deprecated) and then fallback to the prefixed value.
Either way, the field is known internally to the model view as the prefixed value. | def test_prefill_form_backcompat(extras, expected):
"""
When populating custom fields in the connection form we should first check for the non-prefixed
value (since prefixes in extra are deprecated) and then fallback to the prefixed value.
Either way, the field is known internally to the model view as the prefixed value.
"""
mock_form = mock.Mock()
mock_form.data = {"conn_id": "test", "extra": json.dumps(extras), "conn_type": "test"}
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(
return_value=[("extra__test__my_param", "my_param", False)]
)
cmv.prefill_form(form=mock_form, pk=1)
assert mock_form.extra__test__my_param.data == expected |
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed. | def test_process_form_extras_both(mock_pm_hooks, mock_import_str, field_name):
"""
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed.
"""
mock_pm_hooks.get.return_value = True # ensure that hook appears registered
# Testing parameters set in both `Extra` and custom fields.
mock_form = mock.Mock()
mock_form.data = {
"conn_type": "test",
"conn_id": "extras_test",
"extra": '{"param1": "param1_val"}',
"extra__test__custom_field": "custom_field_val",
"extra__other_conn_type__custom_field": "another_field_val",
}
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(
return_value=[("extra__test__custom_field", field_name, False)]
)
cmv.process_form(form=mock_form, is_created=True)
assert json.loads(mock_form.extra.data) == {
field_name: "custom_field_val",
"param1": "param1_val",
} |
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed. | def test_process_form_extras_extra_only(mock_pm_hooks, mock_import_str):
"""
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed.
"""
# Testing parameters set in `Extra` field only.
mock_form = mock.Mock()
mock_form.data = {
"conn_type": "test2",
"conn_id": "extras_test2",
"extra": '{"param2": "param2_val"}',
}
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(return_value=())
cmv.process_form(form=mock_form, is_created=True)
assert json.loads(mock_form.extra.data) == {"param2": "param2_val"} |
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed. | def test_process_form_extras_custom_only(mock_pm_hooks, mock_import_str, field_name):
"""
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed.
"""
# Testing parameters set in custom fields only.
mock_form = mock.Mock()
mock_form.data = {
"conn_type": "test3",
"conn_id": "extras_test3",
"extra__test3__custom_field": False,
"extra__other_conn_type__custom_field": "another_field_val",
}
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(
return_value=[
("extra__test3__custom_field", field_name, False),
("extra__test3__custom_bool_field", False, False),
],
)
cmv.process_form(form=mock_form, is_created=True)
assert json.loads(mock_form.extra.data) == {field_name: False} |
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed. | def test_process_form_extras_updates(mock_pm_hooks, mock_import_str, field_name):
"""
Test the handling of connection parameters set with the classic `Extra` field as well as custom fields.
The key used in the field definition returned by `get_connection_form_widgets` is stored in
attr `extra_field_name_mapping`. Whatever is defined there is what should end up in `extra` when
the form is processed.
"""
# Testing parameters set in both extra and custom fields (connection updates).
mock_form = mock.Mock()
mock_form.data = {
"conn_type": "test4",
"conn_id": "extras_test4",
"extra": '{"extra__test4__custom_field": "custom_field_val3"}',
"extra__test4__custom_field": "custom_field_val4",
}
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(
return_value=[("extra__test4__custom_field", field_name, False)]
)
cmv.process_form(form=mock_form, is_created=True)
if field_name == "custom_field":
assert json.loads(mock_form.extra.data) == {
"custom_field": "custom_field_val4",
"extra__test4__custom_field": "custom_field_val3",
}
else:
assert json.loads(mock_form.extra.data) == {"extra__test4__custom_field": "custom_field_val4"} |
Test the handling of sensitive unchanged field (where placeholder has not been modified). | def test_process_form_extras_updates_sensitive_placeholder_unchanged(
mock_base_hook, mock_pm_hooks, mock_import_str
):
"""
Test the handling of sensitive unchanged field (where placeholder has not been modified).
"""
# Testing parameters set in both extra and custom fields (connection updates).
mock_form = mock.Mock()
mock_form.data = {
"conn_type": "test4",
"conn_id": "extras_test4",
"extra": '{"sensitive_extra": "RATHER_LONG_SENSITIVE_FIELD_PLACEHOLDER", "extra__custom": "value"}',
}
mock_base_hook.get_connection.return_value = Connection(extra='{"sensitive_extra": "old_value"}')
cmv = ConnectionModelView()
cmv._iter_extra_field_names_and_sensitivity = mock.Mock(
return_value=[("sensitive_extra_key", "sensitive_extra", True)]
)
cmv.process_form(form=mock_form, is_created=True)
assert json.loads(mock_form.extra.data) == {
"extra__custom": "value",
"sensitive_extra": "old_value",
} |
Test Duplicate multiple connection with suffix | def test_duplicate_connection(admin_client):
"""Test Duplicate multiple connection with suffix"""
conn1 = Connection(
conn_id="test_duplicate_gcp_connection",
conn_type="Google Cloud",
description="Google Cloud Connection",
)
conn2 = Connection(
conn_id="test_duplicate_mysql_connection",
conn_type="FTP",
description="MongoDB2",
host="localhost",
schema="airflow",
port=3306,
)
conn3 = Connection(
conn_id="test_duplicate_postgres_connection_copy1",
conn_type="FTP",
description="Postgres",
host="localhost",
schema="airflow",
port=3306,
)
with create_session() as session:
session.query(Connection).delete()
session.add_all([conn1, conn2, conn3])
session.commit()
data = {"action": "mulduplicate", "rowid": [conn1.id, conn3.id]}
resp = admin_client.post("/connection/action_post", data=data, follow_redirects=True)
assert resp.status_code == 200
expected_connections_ids = {
"test_duplicate_gcp_connection",
"test_duplicate_gcp_connection_copy1",
"test_duplicate_mysql_connection",
"test_duplicate_postgres_connection_copy1",
"test_duplicate_postgres_connection_copy2",
}
connections_ids = {conn.conn_id for conn in session.query(Connection.conn_id)}
assert expected_connections_ids == connections_ids |
Test Duplicate multiple connection with suffix
when there are already 10 copies, no new copy
should be created | def test_duplicate_connection_error(admin_client):
"""Test Duplicate multiple connection with suffix
when there are already 10 copies, no new copy
should be created"""
connection_ids = [f"test_duplicate_postgres_connection_copy{i}" for i in range(1, 11)]
connections = [
Connection(
conn_id=connection_id,
conn_type="FTP",
description="Postgres",
host="localhost",
schema="airflow",
port=3306,
)
for connection_id in connection_ids
]
with create_session() as session:
session.query(Connection).delete()
session.add_all(connections)
data = {"action": "mulduplicate", "rowid": [connections[0].id]}
resp = admin_client.post("/connection/action_post", data=data, follow_redirects=True)
assert resp.status_code == 200
expected_connections_ids = {f"test_duplicate_postgres_connection_copy{i}" for i in range(1, 11)}
connections_ids = {conn.conn_id for conn in session.query(Connection.conn_id)}
assert expected_connections_ids == connections_ids |
Test that when an invalid json `extra` is passed in the form, it is removed and _not_
saved over the existing extras. | def test_process_form_invalid_extra_removed(admin_client):
"""
Test that when an invalid json `extra` is passed in the form, it is removed and _not_
saved over the existing extras.
"""
conn_details = {"conn_id": "test_conn", "conn_type": "http"}
conn = Connection(**conn_details, extra='{"foo": "bar"}')
conn.id = 1
with create_session() as session:
session.add(conn)
data = {**conn_details, "extra": "Invalid"}
resp = admin_client.post("/connection/edit/1", data=data, follow_redirects=True)
assert resp.status_code == 200
with create_session() as session:
conn = session.get(Connection, 1)
assert conn.extra == '{"foo": "bar"}' |
Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty. | def init_blank_dagrun():
"""Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty.
"""
with create_session() as session:
session.query(DagRun).delete()
session.query(TaskInstance).delete() |
Test that a user without dag_edit but with dag_read permission can view the records | def test_get_dagrun_can_view_dags_without_edit_perms(session, running_dag_run, client_dr_without_dag_edit):
"""Test that a user without dag_edit but with dag_read permission can view the records"""
assert session.query(DagRun).filter(DagRun.dag_id == running_dag_run.dag_id).count() == 1
resp = client_dr_without_dag_edit.get("/dagrun/list/", follow_redirects=True)
check_content_in_response(running_dag_run.dag_id, resp) |
Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty. | def init_blank_task_instances():
"""Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty.
"""
clear_db_runs() |
This tests checks if Operator Link (AirflowLink) defined in the Dummy2TestOperator
is overridden by Airflow Plugin (AirflowLink2).
AirflowLink returns 'https://airflow.apache.org/' link
AirflowLink2 returns 'https://airflow.apache.org/1.10.5/' link | def test_operator_extra_link_override_plugin(dag_run, task_2, viewer_client):
"""
This tests checks if Operator Link (AirflowLink) defined in the Dummy2TestOperator
is overridden by Airflow Plugin (AirflowLink2).
AirflowLink returns 'https://airflow.apache.org/' link
AirflowLink2 returns 'https://airflow.apache.org/1.10.5/' link
"""
response = viewer_client.get(
f"{ENDPOINT}?dag_id={task_2.dag_id}&task_id={task_2.task_id}"
f"&execution_date={STR_DEFAULT_DATE}&link_name=airflow",
follow_redirects=True,
)
assert response.status_code == 200
response_str = response.data
if isinstance(response.data, bytes):
response_str = response_str.decode()
assert json.loads(response_str) == {"url": "https://airflow.apache.org/1.10.5/", "error": None} |
This tests checks if Operator Link (AirflowLink2) defined in
Airflow Plugin (AirflowLink2) is attached to all the list of
operators defined in the AirflowLink2().operators property
AirflowLink2 returns 'https://airflow.apache.org/1.10.5/' link
GoogleLink returns 'https://www.google.com' | def test_operator_extra_link_multiple_operators(dag_run, task_2, task_3, viewer_client):
"""
This tests checks if Operator Link (AirflowLink2) defined in
Airflow Plugin (AirflowLink2) is attached to all the list of
operators defined in the AirflowLink2().operators property
AirflowLink2 returns 'https://airflow.apache.org/1.10.5/' link
GoogleLink returns 'https://www.google.com'
"""
response = viewer_client.get(
f"{ENDPOINT}?dag_id={task_2.dag_id}&task_id={task_2.task_id}"
f"&execution_date={STR_DEFAULT_DATE}&link_name=airflow",
follow_redirects=True,
)
assert response.status_code == 200
response_str = response.data
if isinstance(response.data, bytes):
response_str = response_str.decode()
assert json.loads(response_str) == {"url": "https://airflow.apache.org/1.10.5/", "error": None}
response = viewer_client.get(
f"{ENDPOINT}?dag_id={task_3.dag_id}&task_id={task_3.task_id}"
f"&execution_date={STR_DEFAULT_DATE}&link_name=airflow",
follow_redirects=True,
)
assert response.status_code == 200
response_str = response.data
if isinstance(response.data, bytes):
response_str = response_str.decode()
assert json.loads(response_str) == {"url": "https://airflow.apache.org/1.10.5/", "error": None}
# Also check that the other Operator Link defined for this operator exists
response = viewer_client.get(
f"{ENDPOINT}?dag_id={task_3.dag_id}&task_id={task_3.task_id}"
f"&execution_date={STR_DEFAULT_DATE}&link_name=google",
follow_redirects=True,
)
assert response.status_code == 200
response_str = response.data
if isinstance(response.data, bytes):
response_str = response_str.decode()
assert json.loads(response_str) == {"url": "https://www.google.com", "error": None} |
Test a DAG with complex interaction of states:
- One run successful
- One run partly success, partly running
- One TI not yet finished | def test_one_run(admin_client, dag_with_runs: list[DagRun], session):
"""
Test a DAG with complex interaction of states:
- One run successful
- One run partly success, partly running
- One TI not yet finished
"""
run1, run2 = dag_with_runs
for ti in run1.task_instances:
ti.state = TaskInstanceState.SUCCESS
for ti in sorted(run2.task_instances, key=lambda ti: (ti.task_id, ti.map_index)):
if ti.task_id == "task1":
ti.state = TaskInstanceState.SUCCESS
elif ti.task_id == "group.mapped":
if ti.map_index == 0:
ti.state = TaskInstanceState.SUCCESS
ti.start_date = pendulum.DateTime(2021, 7, 1, 1, 0, 0, tzinfo=pendulum.UTC)
ti.end_date = pendulum.DateTime(2021, 7, 1, 1, 2, 3, tzinfo=pendulum.UTC)
elif ti.map_index == 1:
ti.state = TaskInstanceState.RUNNING
ti.start_date = pendulum.DateTime(2021, 7, 1, 2, 3, 4, tzinfo=pendulum.UTC)
ti.end_date = None
session.flush()
resp = admin_client.get(f"/object/grid_data?dag_id={DAG_ID}", follow_redirects=True)
assert resp.status_code == 200, resp.json
assert resp.json == {
"dag_runs": [
{
"conf": None,
"conf_is_json": False,
"data_interval_end": "2016-01-02T00:00:00+00:00",
"data_interval_start": "2016-01-01T00:00:00+00:00",
"end_date": timezone.utcnow().isoformat(),
"execution_date": "2016-01-01T00:00:00+00:00",
"external_trigger": False,
"last_scheduling_decision": None,
"note": None,
"queued_at": None,
"run_id": "run_1",
"run_type": "scheduled",
"start_date": "2016-01-01T00:00:00+00:00",
"state": "success",
},
{
"conf": None,
"conf_is_json": False,
"data_interval_end": "2016-01-03T00:00:00+00:00",
"data_interval_start": "2016-01-02T00:00:00+00:00",
"end_date": None,
"execution_date": "2016-01-02T00:00:00+00:00",
"external_trigger": False,
"last_scheduling_decision": None,
"note": None,
"queued_at": None,
"run_id": "run_2",
"run_type": "scheduled",
"start_date": "2016-01-01T00:00:00+00:00",
"state": "running",
},
],
"groups": {
"children": [
{
"extra_links": [],
"has_outlet_datasets": False,
"id": "task1",
"instances": [
{
"run_id": "run_1",
"queued_dttm": None,
"start_date": None,
"end_date": None,
"note": None,
"state": "success",
"task_id": "task1",
"try_number": 0,
},
{
"run_id": "run_2",
"queued_dttm": None,
"start_date": None,
"end_date": None,
"note": None,
"state": "success",
"task_id": "task1",
"try_number": 0,
},
],
"is_mapped": False,
"label": "task1",
"operator": "EmptyOperator",
"trigger_rule": "all_success",
},
{
"children": [
{
"extra_links": [],
"has_outlet_datasets": False,
"id": "mapped_task_group.subtask2",
"instances": [
{
"run_id": "run_1",
"mapped_states": {"success": 3},
"queued_dttm": None,
"start_date": None,
"end_date": None,
"state": "success",
"task_id": "mapped_task_group.subtask2",
},
{
"run_id": "run_2",
"mapped_states": {"no_status": 3},
"queued_dttm": None,
"start_date": None,
"end_date": None,
"state": None,
"task_id": "mapped_task_group.subtask2",
},
],
"is_mapped": True,
"label": "subtask2",
"operator": "MockOperator",
"trigger_rule": "all_success",
}
],
"is_mapped": True,
"id": "mapped_task_group",
"instances": [
{
"end_date": None,
"run_id": "run_1",
"mapped_states": {"success": 3},
"queued_dttm": None,
"start_date": None,
"state": "success",
"task_id": "mapped_task_group",
},
{
"run_id": "run_2",
"queued_dttm": None,
"start_date": None,
"end_date": None,
"state": None,
"mapped_states": {"no_status": 3},
"task_id": "mapped_task_group",
},
],
"label": "mapped_task_group",
"tooltip": "",
},
{
"children": [
{
"extra_links": [],
"has_outlet_datasets": False,
"id": "group.mapped",
"instances": [
{
"run_id": "run_1",
"mapped_states": {"success": 4},
"queued_dttm": None,
"start_date": None,
"end_date": None,
"state": "success",
"task_id": "group.mapped",
},
{
"run_id": "run_2",
"mapped_states": {"no_status": 2, "running": 1, "success": 1},
"queued_dttm": None,
"start_date": "2021-07-01T01:00:00+00:00",
"end_date": "2021-07-01T01:02:03+00:00",
"state": "running",
"task_id": "group.mapped",
},
],
"is_mapped": True,
"label": "mapped",
"operator": "MockOperator",
"trigger_rule": "all_success",
},
],
"id": "group",
"instances": [
{
"end_date": None,
"run_id": "run_1",
"queued_dttm": None,
"start_date": None,
"state": "success",
"task_id": "group",
},
{
"run_id": "run_2",
"queued_dttm": None,
"start_date": "2021-07-01T01:00:00+00:00",
"end_date": "2021-07-01T01:02:03+00:00",
"state": "running",
"task_id": "group",
},
],
"label": "group",
"tooltip": "",
},
],
"id": None,
"instances": [],
"label": None,
},
"ordering": ["data_interval_end", "execution_date"],
} |
Create User that cannot access Import Errors | def user_no_importerror(app):
"""Create User that cannot access Import Errors"""
return create_user(
app,
username="user_no_importerrors",
role_name="role_no_importerrors",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
],
) |
Client for User that cannot access Import Errors | def client_no_importerror(app, user_no_importerror):
"""Client for User that cannot access Import Errors"""
return client_with_login(
app,
username="user_no_importerrors",
password="user_no_importerrors",
) |
Create User that can only access the first DAG from TEST_FILTER_DAG_IDS | def user_single_dag(app):
"""Create User that can only access the first DAG from TEST_FILTER_DAG_IDS"""
return create_user(
app,
username="user_single_dag",
role_name="role_single_dag",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR),
(permissions.ACTION_CAN_READ, permissions.resource_name_for_dag(TEST_FILTER_DAG_IDS[0])),
],
) |
Client for User that can only access the first DAG from TEST_FILTER_DAG_IDS | def client_single_dag(app, user_single_dag):
"""Client for User that can only access the first DAG from TEST_FILTER_DAG_IDS"""
return client_with_login(
app,
username="user_single_dag",
password="user_single_dag",
) |
Create User that can edit DAG resource only a single DAG | def user_single_dag_edit(app):
"""Create User that can edit DAG resource only a single DAG"""
return create_user(
app,
username="user_single_dag_edit",
role_name="role_single_dag",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_EDIT, permissions.resource_name_for_dag("filter_test_1")),
],
) |
Client for User that can only edit the first DAG from TEST_FILTER_DAG_IDS | def client_single_dag_edit(app, user_single_dag_edit):
"""Client for User that can only edit the first DAG from TEST_FILTER_DAG_IDS"""
return client_with_login(
app,
username="user_single_dag_edit",
password="user_single_dag_edit",
) |
Make sure that the configure_logging is not cached. | def backup_modules():
"""Make sure that the configure_logging is not cached."""
return dict(sys.modules) |
Test invalid metadata JSON returns error message | def test_get_logs_with_invalid_metadata(log_admin_client):
"""Test invalid metadata JSON returns error message"""
metadata = "invalid"
url_template = "get_logs_with_metadata?dag_id={}&task_id={}&execution_date={}&try_number={}&metadata={}"
response = log_admin_client.get(
url_template.format(
DAG_ID,
TASK_ID,
urllib.parse.quote_plus(DEFAULT_DATE.isoformat()),
1,
metadata,
),
data={"username": "test", "password": "test"},
follow_redirects=True,
)
assert response.status_code == 400
assert response.json == {"error": "Invalid JSON metadata"} |
Redirect to home if TI does not exist or if log handler is local | def test_redirect_to_external_log_with_local_log_handler(log_admin_client, task_id):
"""Redirect to home if TI does not exist or if log handler is local"""
url_template = "redirect_to_external_log?dag_id={}&task_id={}&execution_date={}&try_number={}"
try_number = 1
url = url_template.format(
DAG_ID,
task_id,
urllib.parse.quote_plus(DEFAULT_DATE.isoformat()),
try_number,
)
response = log_admin_client.get(url)
assert 302 == response.status_code
assert "/home" == response.headers["Location"] |
Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty. | def init_blank_db():
"""Make sure there are no runs before we test anything.
This really shouldn't be needed, but tests elsewhere leave the db dirty.
"""
clear_db_dags()
clear_db_runs()
clear_rendered_ti_fields() |
Test that the Rendered View contains the values from RenderedTaskInstanceFields | def test_rendered_template_view(admin_client, create_dag_run, task1):
"""
Test that the Rendered View contains the values from RenderedTaskInstanceFields
"""
assert task1.bash_command == "{{ task_instance_key_str }}"
with create_session() as session:
dag_run = create_dag_run(execution_date=DEFAULT_DATE, session=session)
ti = dag_run.get_task_instance(task1.task_id, session=session)
assert ti is not None, "task instance not found"
ti.refresh_from_task(task1)
session.add(RenderedTaskInstanceFields(ti))
url = f"rendered-templates?task_id=task1&dag_id=testdag&execution_date={quote_plus(str(DEFAULT_DATE))}"
resp = admin_client.get(url, follow_redirects=True)
check_content_in_response("testdag__task1__20200301", resp) |
Test that the Rendered View is able to show rendered values
even for TIs that have not yet executed | def test_rendered_template_view_for_unexecuted_tis(admin_client, create_dag_run, task1):
"""
Test that the Rendered View is able to show rendered values
even for TIs that have not yet executed
"""
assert task1.bash_command == "{{ task_instance_key_str }}"
with create_session() as session:
create_dag_run(execution_date=DEFAULT_DATE, session=session)
url = f"rendered-templates?task_id=task1&dag_id=testdag&execution_date={quote_plus(str(DEFAULT_DATE))}"
resp = admin_client.get(url, follow_redirects=True)
check_content_in_response("testdag__task1__20200301", resp) |
Test that the Rendered View masks values retrieved from secret variables. | def test_rendered_template_secret(admin_client, create_dag_run, task_secret):
"""Test that the Rendered View masks values retrieved from secret variables."""
Variable.set("my_secret", "secret_unlikely_to_happen_accidentally")
Variable.set("spam", "egg")
assert task_secret.bash_command == "echo {{ var.value.my_secret }} && echo {{ var.value.spam }}"
with create_session() as session:
dag_run = create_dag_run(execution_date=DEFAULT_DATE, session=session)
ti = dag_run.get_task_instance(task_secret.task_id, session=session)
assert ti is not None, "task instance not found"
ti.refresh_from_task(task_secret)
assert ti.state == TaskInstanceState.QUEUED
date = quote_plus(str(DEFAULT_DATE))
url = f"rendered-templates?task_id=task_secret&dag_id=testdag&execution_date={date}"
resp = admin_client.get(url, follow_redirects=True)
check_content_in_response("***", resp)
check_content_not_in_response("secret_unlikely_to_happen_accidentally", resp)
ti.refresh_from_task(task_secret)
assert ti.state == TaskInstanceState.QUEUED |
Test that the Rendered View can show a list of syntax-highlighted SQL statements | def test_rendered_template_view_for_list_template_field_args(admin_client, create_dag_run, task3):
"""
Test that the Rendered View can show a list of syntax-highlighted SQL statements
"""
assert task3.sql == ["SELECT 1;", "SELECT 2;"]
with create_session() as session:
create_dag_run(execution_date=DEFAULT_DATE, session=session)
url = f"rendered-templates?task_id=task3&dag_id=testdag&execution_date={quote_plus(str(DEFAULT_DATE))}"
resp = admin_client.get(url, follow_redirects=True)
check_content_in_response("List item #0", resp)
check_content_in_response("List item #1", resp) |
Test that the Rendered View can show rendered values in op_args and op_kwargs | def test_rendered_template_view_for_op_args(admin_client, create_dag_run, task4):
"""
Test that the Rendered View can show rendered values in op_args and op_kwargs
"""
assert task4.op_args == ["{{ task_instance_key_str }}_args"]
assert list(task4.op_kwargs.values()) == ["{{ task_instance_key_str }}_kwargs"]
with create_session() as session:
create_dag_run(execution_date=DEFAULT_DATE, session=session)
url = f"rendered-templates?task_id=task4&dag_id=testdag&execution_date={quote_plus(str(DEFAULT_DATE))}"
resp = admin_client.get(url, follow_redirects=True)
check_content_in_response("testdag__task4__20200301_args", resp)
check_content_in_response("testdag__task4__20200301_kwargs", resp) |
Clean up stray garbage from other tests. | def reset_dagruns():
"""Clean up stray garbage from other tests."""
clear_db_runs() |
Do not show external links if log handler is local. | def test_show_external_log_redirect_link_with_local_log_handler(capture_templates, admin_client, endpoint):
"""Do not show external links if log handler is local."""
url = f"{endpoint}?dag_id=example_bash_operator"
with capture_templates() as templates:
admin_client.get(url, follow_redirects=True)
ctx = templates[0].local_context
assert not ctx["show_external_log_redirect"]
assert ctx["external_log_name"] is None |
Show external links if log handler is external. | def test_show_external_log_redirect_link_with_external_log_handler(
_, capture_templates, admin_client, endpoint
):
"""Show external links if log handler is external."""
url = f"{endpoint}?dag_id=example_bash_operator"
with capture_templates() as templates:
admin_client.get(url, follow_redirects=True)
ctx = templates[0].local_context
assert ctx["show_external_log_redirect"]
assert ctx["external_log_name"] == _ExternalHandler.LOG_NAME |
Show external links if log handler is external. | def test_external_log_redirect_link_with_external_log_handler_not_shown(
_external_handler, capture_templates, admin_client, endpoint
):
"""Show external links if log handler is external."""
_external_handler.return_value._supports_external_link = False
url = f"{endpoint}?dag_id=example_bash_operator"
with capture_templates() as templates:
admin_client.get(url, follow_redirects=True)
ctx = templates[0].local_context
assert not ctx["show_external_log_redirect"]
assert ctx["external_log_name"] is None |
Utility to get Flask-Appbuilder's string format "pk" for an object.
Used to generate requests to FAB action views without *too* much difficulty.
The implementation relies on FAB internals, but unfortunately I don't see
a better way around it.
Example usage::
from airflow.www.views import TaskInstanceModelView
ti = session.Query(TaskInstance).filter(...).one()
pk = _get_appbuilder_pk_string(TaskInstanceModelView, ti)
client.post("...", data={"action": "...", "rowid": pk}) | def _get_appbuilder_pk_string(model_view_cls, instance) -> str:
"""Utility to get Flask-Appbuilder's string format "pk" for an object.
Used to generate requests to FAB action views without *too* much difficulty.
The implementation relies on FAB internals, but unfortunately I don't see
a better way around it.
Example usage::
from airflow.www.views import TaskInstanceModelView
ti = session.Query(TaskInstance).filter(...).one()
pk = _get_appbuilder_pk_string(TaskInstanceModelView, ti)
client.post("...", data={"action": "...", "rowid": pk})
"""
pk_value = model_view_cls.datamodel.get_pk_value(instance)
return model_view_cls._serialize_pk_if_composite(model_view_cls, pk_value) |
Ensures clearing a task instance clears its downstream dependencies exclusively | def test_task_instance_clear_downstream(session, admin_client, dag_maker):
"""Ensures clearing a task instance clears its downstream dependencies exclusively"""
with dag_maker(
dag_id="test_dag_id",
serialized=True,
session=session,
start_date=pendulum.DateTime(2023, 1, 1, 0, 0, 0, tzinfo=pendulum.UTC),
):
EmptyOperator(task_id="task_1") >> EmptyOperator(task_id="task_2")
EmptyOperator(task_id="task_3")
run1 = dag_maker.create_dagrun(
run_id="run_1",
state=DagRunState.SUCCESS,
run_type=DagRunType.SCHEDULED,
execution_date=dag_maker.dag.start_date,
start_date=dag_maker.dag.start_date,
session=session,
)
run2 = dag_maker.create_dagrun(
run_id="run_2",
state=DagRunState.SUCCESS,
run_type=DagRunType.SCHEDULED,
execution_date=dag_maker.dag.start_date.add(days=1),
start_date=dag_maker.dag.start_date.add(days=1),
session=session,
)
for run in (run1, run2):
for ti in run.task_instances:
ti.state = State.SUCCESS
# Clear task_1 from dag run 1
run1_ti1 = run1.get_task_instance(task_id="task_1")
rowid = _get_appbuilder_pk_string(TaskInstanceModelView, run1_ti1)
resp = admin_client.post(
"/taskinstance/action_post",
data={"action": "clear_downstream", "rowid": rowid},
follow_redirects=True,
)
assert resp.status_code == 200
# Assert that task_1 and task_2 of dag run 1 are cleared, but task_3 is left untouched
run1_ti1.refresh_from_db(session=session)
run1_ti2 = run1.get_task_instance(task_id="task_2")
run1_ti3 = run1.get_task_instance(task_id="task_3")
assert run1_ti1.state == State.NONE
assert run1_ti2.state == State.NONE
assert run1_ti3.state == State.SUCCESS
# Assert that task_1 of dag run 2 is left untouched
run2_ti1 = run2.get_task_instance(task_id="task_1")
assert run2_ti1.state == State.SUCCESS |
Test that the graph view doesn't fail on a recursion error. | def test_graph_view_doesnt_fail_on_recursion_error(app, dag_maker, admin_client):
"""Test that the graph view doesn't fail on a recursion error."""
from airflow.models.baseoperator import chain
with dag_maker("test_fails_with_recursion") as dag:
tasks = [
BashOperator(
task_id=f"task_{i}",
bash_command="echo test",
)
for i in range(1, 1000 + 1)
]
chain(*tasks)
with unittest.mock.patch.object(app, "dag_bag") as mocked_dag_bag:
mocked_dag_bag.get_dag.return_value = dag
url = f"/dags/{dag.dag_id}/graph"
resp = admin_client.get(url, follow_redirects=True)
assert resp.status_code == 200 |
Test task_instances view. | def test_task_instances(admin_client):
"""Test task_instances view."""
resp = admin_client.get(
f"/object/task_instances?dag_id=example_bash_operator&execution_date={STR_DEFAULT_DATE}",
follow_redirects=True,
)
assert resp.status_code == 200
assert resp.json == {
"also_run_this": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 2,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "also_run_this",
"task_id": "also_run_this",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"run_after_loop": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 2,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "run_after_loop",
"task_id": "run_after_loop",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"run_this_last": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "EmptyOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 1,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "run_this_last",
"task_id": "run_this_last",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"runme_0": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 3,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "runme_0",
"task_id": "runme_0",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"runme_1": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 3,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "runme_1",
"task_id": "runme_1",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"runme_2": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 3,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "runme_2",
"task_id": "runme_2",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
"this_will_skip": {
"custom_operator_name": None,
"dag_id": "example_bash_operator",
"duration": None,
"end_date": None,
"execution_date": DEFAULT_DATE.isoformat(),
"executor": None,
"executor_config": {},
"external_executor_id": None,
"hostname": "",
"job_id": None,
"map_index": -1,
"max_tries": 0,
"next_kwargs": None,
"next_method": None,
"operator": "BashOperator",
"pid": None,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 2,
"queue": "default",
"queued_by_job_id": None,
"queued_dttm": None,
"rendered_map_index": None,
"run_id": "TEST_DAGRUN",
"start_date": None,
"state": None,
"task_display_name": "this_will_skip",
"task_id": "this_will_skip",
"trigger_id": None,
"trigger_timeout": None,
"try_number": 1,
"unixname": getuser(),
"updated_at": DEFAULT_DATE.isoformat(),
},
} |
Clean up stray garbage from other tests. | def reset_dagruns():
"""Clean up stray garbage from other tests."""
clear_db_runs() |
Test that textarea in Trigger DAG UI is pre-populated
with json config when the conf URL parameter is passed,
or if a params dict is passed in the DAG
1. Conf is not included in URL parameters -> DAG.conf is in textarea
2. Conf is passed as a URL parameter -> passed conf json is in textarea | def test_trigger_dag_params_conf(admin_client, request_conf, expected_conf):
"""
Test that textarea in Trigger DAG UI is pre-populated
with json config when the conf URL parameter is passed,
or if a params dict is passed in the DAG
1. Conf is not included in URL parameters -> DAG.conf is in textarea
2. Conf is passed as a URL parameter -> passed conf json is in textarea
"""
test_dag_id = "example_bash_operator"
doc_md = "Example Bash Operator"
if not request_conf:
resp = admin_client.get(f"dags/{test_dag_id}/trigger")
else:
test_request_conf = json.dumps(request_conf, indent=4)
resp = admin_client.get(f"dags/{test_dag_id}/trigger?conf={test_request_conf}&doc_md={doc_md}")
for key in expected_conf.keys():
check_content_in_response(key, resp)
check_content_in_response(str(expected_conf[key]), resp) |
Test that textarea in Trigger DAG UI is pre-populated
with param value set in DAG. | def test_trigger_dag_params_render(admin_client, dag_maker, session, app, monkeypatch):
"""
Test that textarea in Trigger DAG UI is pre-populated
with param value set in DAG.
"""
account = {"name": "account_name_1", "country": "usa"}
expected_conf = {"accounts": [account]}
expected_dag_conf = json.dumps(expected_conf, indent=4).replace('"', """)
DAG_ID = "params_dag"
param = Param(
[account],
schema={
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"default": account,
"properties": {"name": {"type": "string"}, "country": {"type": "string"}},
"required": ["name", "country"],
},
},
)
with monkeypatch.context() as m:
with dag_maker(dag_id=DAG_ID, serialized=True, session=session, params={"accounts": param}):
EmptyOperator(task_id="task1")
m.setattr(app, "dag_bag", dag_maker.dagbag)
resp = admin_client.get(f"dags/{DAG_ID}/trigger")
check_content_in_response(
f'<textarea style="display: none;" id="json_start" name="json_start">{expected_dag_conf}</textarea>',
resp,
) |
Test that HTML is escaped per default in description. | def test_trigger_dag_html_allow(admin_client, dag_maker, session, app, monkeypatch, allow_html):
"""
Test that HTML is escaped per default in description.
"""
from markupsafe import escape
DAG_ID = "params_dag"
HTML_DESCRIPTION1 = "HTML <code>raw code</code>."
HTML_DESCRIPTION2 = "HTML <code>in md text</code>."
expect_escape = not allow_html
with conf_vars({("webserver", "allow_raw_html_descriptions"): str(allow_html)}):
param1 = Param(
42,
description_html=HTML_DESCRIPTION1,
type="integer",
minimum=1,
maximum=100,
)
param2 = Param(
42,
description_md=HTML_DESCRIPTION2,
type="integer",
minimum=1,
maximum=100,
)
with monkeypatch.context() as m:
with dag_maker(
dag_id=DAG_ID, serialized=True, session=session, params={"param1": param1, "param2": param2}
):
EmptyOperator(task_id="task1")
m.setattr(app, "dag_bag", dag_maker.dagbag)
resp = admin_client.get(f"dags/{DAG_ID}/trigger")
if expect_escape:
check_content_in_response(escape(HTML_DESCRIPTION1), resp)
check_content_in_response(escape(HTML_DESCRIPTION2), resp)
check_content_in_response(
"At least one field in the trigger form uses a raw HTML form definition.", resp
)
else:
check_content_in_response(HTML_DESCRIPTION1, resp)
check_content_in_response(HTML_DESCRIPTION2, resp)
check_content_not_in_response(
"At least one field in the trigger form uses a raw HTML form definition.", resp
) |
Test that Trigger Endpoint uses the DagBag already created in views.py
instead of creating a new one. | def test_trigger_endpoint_uses_existing_dagbag(admin_client):
"""
Test that Trigger Endpoint uses the DagBag already created in views.py
instead of creating a new one.
"""
url = "dags/example_bash_operator/trigger"
resp = admin_client.post(url, data={}, follow_redirects=True)
check_content_in_response("example_bash_operator", resp) |
Test that the test_viewer user can't trigger DAGs. | def test_viewer_cant_trigger_dag(app):
"""
Test that the test_viewer user can't trigger DAGs.
"""
with create_test_client(
app,
user_name="test_user",
role_name="test_role",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN),
],
) as client:
url = "dags/example_bash_operator/trigger"
resp = client.get(url, follow_redirects=True)
response_data = resp.data.decode()
assert "Access is Denied" in response_data |
Test that textarea in Trigger DAG UI is pre-populated
with param value None and type ["null", "array"] set in DAG. | def test_trigger_dag_params_array_value_none_render(admin_client, dag_maker, session, app, monkeypatch):
"""
Test that textarea in Trigger DAG UI is pre-populated
with param value None and type ["null", "array"] set in DAG.
"""
expected_conf = {"dag_param": None}
expected_dag_conf = json.dumps(expected_conf, indent=4).replace('"', """)
DAG_ID = "params_dag"
param = Param(
None,
type=["null", "array"],
minItems=0,
)
with monkeypatch.context() as m:
with dag_maker(dag_id=DAG_ID, serialized=True, session=session, params={"dag_param": param}):
EmptyOperator(task_id="task1")
m.setattr(app, "dag_bag", dag_maker.dagbag)
resp = admin_client.get(f"dags/{DAG_ID}/trigger")
check_content_in_response(
f'<textarea style="display: none;" id="json_start" name="json_start">{expected_dag_conf}</textarea>',
resp,
) |
Create User that can only read variables | def user_variable_reader(app):
"""Create User that can only read variables"""
return create_user(
app,
username="user_variable_reader",
role_name="role_variable_reader",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
],
) |
Client for User that can only access the first DAG from TEST_FILTER_DAG_IDS | def client_variable_reader(app, user_variable_reader):
"""Client for User that can only access the first DAG from TEST_FILTER_DAG_IDS"""
return client_with_login(
app,
username="user_variable_reader",
password="user_variable_reader",
) |
List available templates.
:param config: a :class:`.Config` object. | def list_templates(config: Config) -> None:
"""List available templates.
:param config: a :class:`.Config` object.
"""
config.print_stdout("Available templates:\n")
for tempname in os.listdir(config.get_template_directory()):
with open(
os.path.join(config.get_template_directory(), tempname, "README")
) as readme:
synopsis = next(readme).rstrip()
config.print_stdout("%s - %s", tempname, synopsis)
config.print_stdout("\nTemplates are used via the 'init' command, e.g.:")
config.print_stdout("\n alembic init --template generic ./scripts") |
Initialize a new scripts directory.
:param config: a :class:`.Config` object.
:param directory: string path of the target directory.
:param template: string name of the migration environment template to
use.
:param package: when True, write ``__init__.py`` files into the
environment location as well as the versions/ location. | def init(
config: Config,
directory: str,
template: str = "generic",
package: bool = False,
) -> None:
"""Initialize a new scripts directory.
:param config: a :class:`.Config` object.
:param directory: string path of the target directory.
:param template: string name of the migration environment template to
use.
:param package: when True, write ``__init__.py`` files into the
environment location as well as the versions/ location.
"""
if os.access(directory, os.F_OK) and os.listdir(directory):
raise util.CommandError(
"Directory %s already exists and is not empty" % directory
)
template_dir = os.path.join(config.get_template_directory(), template)
if not os.access(template_dir, os.F_OK):
raise util.CommandError("No such template %r" % template)
if not os.access(directory, os.F_OK):
with util.status(
f"Creating directory {os.path.abspath(directory)!r}",
**config.messaging_opts,
):
os.makedirs(directory)
versions = os.path.join(directory, "versions")
with util.status(
f"Creating directory {os.path.abspath(versions)!r}",
**config.messaging_opts,
):
os.makedirs(versions)
script = ScriptDirectory(directory)
config_file: str | None = None
for file_ in os.listdir(template_dir):
file_path = os.path.join(template_dir, file_)
if file_ == "alembic.ini.mako":
assert config.config_file_name is not None
config_file = os.path.abspath(config.config_file_name)
if os.access(config_file, os.F_OK):
util.msg(
f"File {config_file!r} already exists, skipping",
**config.messaging_opts,
)
else:
script._generate_template(
file_path, config_file, script_location=directory
)
elif os.path.isfile(file_path):
output_file = os.path.join(directory, file_)
script._copy_file(file_path, output_file)
if package:
for path in [
os.path.join(os.path.abspath(directory), "__init__.py"),
os.path.join(os.path.abspath(versions), "__init__.py"),
]:
with util.status(f"Adding {path!r}", **config.messaging_opts):
with open(path, "w"):
pass
assert config_file is not None
util.msg(
"Please edit configuration/connection/logging "
f"settings in {config_file!r} before proceeding.",
**config.messaging_opts,
) |
Create a new revision file.
:param config: a :class:`.Config` object.
:param message: string message to apply to the revision; this is the
``-m`` option to ``alembic revision``.
:param autogenerate: whether or not to autogenerate the script from
the database; this is the ``--autogenerate`` option to
``alembic revision``.
:param sql: whether to dump the script out as a SQL string; when specified,
the script is dumped to stdout. This is the ``--sql`` option to
``alembic revision``.
:param head: head revision to build the new revision upon as a parent;
this is the ``--head`` option to ``alembic revision``.
:param splice: whether or not the new revision should be made into a
new head of its own; is required when the given ``head`` is not itself
a head. This is the ``--splice`` option to ``alembic revision``.
:param branch_label: string label to apply to the branch; this is the
``--branch-label`` option to ``alembic revision``.
:param version_path: string symbol identifying a specific version path
from the configuration; this is the ``--version-path`` option to
``alembic revision``.
:param rev_id: optional revision identifier to use instead of having
one generated; this is the ``--rev-id`` option to ``alembic revision``.
:param depends_on: optional list of "depends on" identifiers; this is the
``--depends-on`` option to ``alembic revision``.
:param process_revision_directives: this is a callable that takes the
same form as the callable described at
:paramref:`.EnvironmentContext.configure.process_revision_directives`;
will be applied to the structure generated by the revision process
where it can be altered programmatically. Note that unlike all
the other parameters, this option is only available via programmatic
use of :func:`.command.revision`. | def revision(
config: Config,
message: Optional[str] = None,
autogenerate: bool = False,
sql: bool = False,
head: str = "head",
splice: bool = False,
branch_label: Optional[_RevIdType] = None,
version_path: Optional[str] = None,
rev_id: Optional[str] = None,
depends_on: Optional[str] = None,
process_revision_directives: Optional[ProcessRevisionDirectiveFn] = None,
) -> Union[Optional[Script], List[Optional[Script]]]:
"""Create a new revision file.
:param config: a :class:`.Config` object.
:param message: string message to apply to the revision; this is the
``-m`` option to ``alembic revision``.
:param autogenerate: whether or not to autogenerate the script from
the database; this is the ``--autogenerate`` option to
``alembic revision``.
:param sql: whether to dump the script out as a SQL string; when specified,
the script is dumped to stdout. This is the ``--sql`` option to
``alembic revision``.
:param head: head revision to build the new revision upon as a parent;
this is the ``--head`` option to ``alembic revision``.
:param splice: whether or not the new revision should be made into a
new head of its own; is required when the given ``head`` is not itself
a head. This is the ``--splice`` option to ``alembic revision``.
:param branch_label: string label to apply to the branch; this is the
``--branch-label`` option to ``alembic revision``.
:param version_path: string symbol identifying a specific version path
from the configuration; this is the ``--version-path`` option to
``alembic revision``.
:param rev_id: optional revision identifier to use instead of having
one generated; this is the ``--rev-id`` option to ``alembic revision``.
:param depends_on: optional list of "depends on" identifiers; this is the
``--depends-on`` option to ``alembic revision``.
:param process_revision_directives: this is a callable that takes the
same form as the callable described at
:paramref:`.EnvironmentContext.configure.process_revision_directives`;
will be applied to the structure generated by the revision process
where it can be altered programmatically. Note that unlike all
the other parameters, this option is only available via programmatic
use of :func:`.command.revision`.
"""
script_directory = ScriptDirectory.from_config(config)
command_args = dict(
message=message,
autogenerate=autogenerate,
sql=sql,
head=head,
splice=splice,
branch_label=branch_label,
version_path=version_path,
rev_id=rev_id,
depends_on=depends_on,
)
revision_context = autogen.RevisionContext(
config,
script_directory,
command_args,
process_revision_directives=process_revision_directives,
)
environment = util.asbool(config.get_main_option("revision_environment"))
if autogenerate:
environment = True
if sql:
raise util.CommandError(
"Using --sql with --autogenerate does not make any sense"
)
def retrieve_migrations(rev, context):
revision_context.run_autogenerate(rev, context)
return []
elif environment:
def retrieve_migrations(rev, context):
revision_context.run_no_autogenerate(rev, context)
return []
elif sql:
raise util.CommandError(
"Using --sql with the revision command when "
"revision_environment is not configured does not make any sense"
)
if environment:
with EnvironmentContext(
config,
script_directory,
fn=retrieve_migrations,
as_sql=sql,
template_args=revision_context.template_args,
revision_context=revision_context,
):
script_directory.run_env()
# the revision_context now has MigrationScript structure(s) present.
# these could theoretically be further processed / rewritten *here*,
# in addition to the hooks present within each run_migrations() call,
# or at the end of env.py run_migrations_online().
scripts = [script for script in revision_context.generate_scripts()]
if len(scripts) == 1:
return scripts[0]
else:
return scripts |
Check if revision command with autogenerate has pending upgrade ops.
:param config: a :class:`.Config` object.
.. versionadded:: 1.9.0 | def check(config: "Config") -> None:
"""Check if revision command with autogenerate has pending upgrade ops.
:param config: a :class:`.Config` object.
.. versionadded:: 1.9.0
"""
script_directory = ScriptDirectory.from_config(config)
command_args = dict(
message=None,
autogenerate=True,
sql=False,
head="head",
splice=False,
branch_label=None,
version_path=None,
rev_id=None,
depends_on=None,
)
revision_context = autogen.RevisionContext(
config,
script_directory,
command_args,
)
def retrieve_migrations(rev, context):
revision_context.run_autogenerate(rev, context)
return []
with EnvironmentContext(
config,
script_directory,
fn=retrieve_migrations,
as_sql=False,
template_args=revision_context.template_args,
revision_context=revision_context,
):
script_directory.run_env()
# the revision_context now has MigrationScript structure(s) present.
migration_script = revision_context.generated_revisions[-1]
diffs = []
for upgrade_ops in migration_script.upgrade_ops_list:
diffs.extend(upgrade_ops.as_diffs())
if diffs:
raise util.AutogenerateDiffsDetected(
f"New upgrade operations detected: {diffs}"
)
else:
config.print_stdout("No new upgrade operations detected.") |
Merge two revisions together. Creates a new migration file.
:param config: a :class:`.Config` instance
:param revisions: The revisions to merge.
:param message: string message to apply to the revision.
:param branch_label: string label name to apply to the new revision.
:param rev_id: hardcoded revision identifier instead of generating a new
one.
.. seealso::
:ref:`branches` | def merge(
config: Config,
revisions: _RevIdType,
message: Optional[str] = None,
branch_label: Optional[_RevIdType] = None,
rev_id: Optional[str] = None,
) -> Optional[Script]:
"""Merge two revisions together. Creates a new migration file.
:param config: a :class:`.Config` instance
:param revisions: The revisions to merge.
:param message: string message to apply to the revision.
:param branch_label: string label name to apply to the new revision.
:param rev_id: hardcoded revision identifier instead of generating a new
one.
.. seealso::
:ref:`branches`
"""
script = ScriptDirectory.from_config(config)
template_args = {
"config": config # Let templates use config for
# e.g. multiple databases
}
environment = util.asbool(config.get_main_option("revision_environment"))
if environment:
def nothing(rev, context):
return []
with EnvironmentContext(
config,
script,
fn=nothing,
as_sql=False,
template_args=template_args,
):
script.run_env()
return script.generate_revision(
rev_id or util.rev_id(),
message,
refresh=True,
head=revisions,
branch_labels=branch_label,
**template_args, # type:ignore[arg-type]
) |
Upgrade to a later version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May be
``"heads"`` to target the most recent revision(s).
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :meth:`.EnvironmentContext.get_tag_argument`
method. | def upgrade(
config: Config,
revision: str,
sql: bool = False,
tag: Optional[str] = None,
) -> None:
"""Upgrade to a later version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May be
``"heads"`` to target the most recent revision(s).
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :meth:`.EnvironmentContext.get_tag_argument`
method.
"""
script = ScriptDirectory.from_config(config)
starting_rev = None
if ":" in revision:
if not sql:
raise util.CommandError("Range revision not allowed")
starting_rev, revision = revision.split(":", 2)
def upgrade(rev, context):
return script._upgrade_revs(revision, rev)
with EnvironmentContext(
config,
script,
fn=upgrade,
as_sql=sql,
starting_rev=starting_rev,
destination_rev=revision,
tag=tag,
):
script.run_env() |
Revert to a previous version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May
be ``"base"`` to target the first revision.
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :meth:`.EnvironmentContext.get_tag_argument`
method. | def downgrade(
config: Config,
revision: str,
sql: bool = False,
tag: Optional[str] = None,
) -> None:
"""Revert to a previous version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May
be ``"base"`` to target the first revision.
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :meth:`.EnvironmentContext.get_tag_argument`
method.
"""
script = ScriptDirectory.from_config(config)
starting_rev = None
if ":" in revision:
if not sql:
raise util.CommandError("Range revision not allowed")
starting_rev, revision = revision.split(":", 2)
elif sql:
raise util.CommandError(
"downgrade with --sql requires <fromrev>:<torev>"
)
def downgrade(rev, context):
return script._downgrade_revs(revision, rev)
with EnvironmentContext(
config,
script,
fn=downgrade,
as_sql=sql,
starting_rev=starting_rev,
destination_rev=revision,
tag=tag,
):
script.run_env() |
Show the revision(s) denoted by the given symbol.
:param config: a :class:`.Config` instance.
:param rev: string revision target. May be ``"current"`` to show the
revision(s) currently applied in the database. | def show(config: Config, rev: str) -> None:
"""Show the revision(s) denoted by the given symbol.
:param config: a :class:`.Config` instance.
:param rev: string revision target. May be ``"current"`` to show the
revision(s) currently applied in the database.
"""
script = ScriptDirectory.from_config(config)
if rev == "current":
def show_current(rev, context):
for sc in script.get_revisions(rev):
config.print_stdout(sc.log_entry)
return []
with EnvironmentContext(config, script, fn=show_current):
script.run_env()
else:
for sc in script.get_revisions(rev):
config.print_stdout(sc.log_entry) |
List changeset scripts in chronological order.
:param config: a :class:`.Config` instance.
:param rev_range: string revision range.
:param verbose: output in verbose mode.
:param indicate_current: indicate current revision. | def history(
config: Config,
rev_range: Optional[str] = None,
verbose: bool = False,
indicate_current: bool = False,
) -> None:
"""List changeset scripts in chronological order.
:param config: a :class:`.Config` instance.
:param rev_range: string revision range.
:param verbose: output in verbose mode.
:param indicate_current: indicate current revision.
"""
base: Optional[str]
head: Optional[str]
script = ScriptDirectory.from_config(config)
if rev_range is not None:
if ":" not in rev_range:
raise util.CommandError(
"History range requires [start]:[end], " "[start]:, or :[end]"
)
base, head = rev_range.strip().split(":")
else:
base = head = None
environment = (
util.asbool(config.get_main_option("revision_environment"))
or indicate_current
)
def _display_history(config, script, base, head, currents=()):
for sc in script.walk_revisions(
base=base or "base", head=head or "heads"
):
if indicate_current:
sc._db_current_indicator = sc.revision in currents
config.print_stdout(
sc.cmd_format(
verbose=verbose,
include_branches=True,
include_doc=True,
include_parents=True,
)
)
def _display_history_w_current(config, script, base, head):
def _display_current_history(rev, context):
if head == "current":
_display_history(config, script, base, rev, rev)
elif base == "current":
_display_history(config, script, rev, head, rev)
else:
_display_history(config, script, base, head, rev)
return []
with EnvironmentContext(config, script, fn=_display_current_history):
script.run_env()
if base == "current" or head == "current" or environment:
_display_history_w_current(config, script, base, head)
else:
_display_history(config, script, base, head) |
Show current available heads in the script directory.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
:param resolve_dependencies: treat dependency version as down revisions. | def heads(
config: Config, verbose: bool = False, resolve_dependencies: bool = False
) -> None:
"""Show current available heads in the script directory.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
:param resolve_dependencies: treat dependency version as down revisions.
"""
script = ScriptDirectory.from_config(config)
if resolve_dependencies:
heads = script.get_revisions("heads")
else:
heads = script.get_revisions(script.get_heads())
for rev in heads:
config.print_stdout(
rev.cmd_format(
verbose, include_branches=True, tree_indicators=False
)
) |
Show current branch points.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode. | def branches(config: Config, verbose: bool = False) -> None:
"""Show current branch points.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
"""
script = ScriptDirectory.from_config(config)
for sc in script.walk_revisions():
if sc.is_branch_point:
config.print_stdout(
"%s\n%s\n",
sc.cmd_format(verbose, include_branches=True),
"\n".join(
"%s -> %s"
% (
" " * len(str(sc.revision)),
rev_obj.cmd_format(
False, include_branches=True, include_doc=verbose
),
)
for rev_obj in (
script.get_revision(rev) for rev in sc.nextrev
)
),
) |
Display the current revision for a database.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode. | def current(config: Config, verbose: bool = False) -> None:
"""Display the current revision for a database.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
"""
script = ScriptDirectory.from_config(config)
def display_version(rev, context):
if verbose:
config.print_stdout(
"Current revision(s) for %s:",
util.obfuscate_url_pw(context.connection.engine.url),
)
for rev in script.get_all_current(rev):
config.print_stdout(rev.cmd_format(verbose))
return []
with EnvironmentContext(
config, script, fn=display_version, dont_mutate=True
):
script.run_env() |
'stamp' the revision table with the given revision; don't
run any migrations.
:param config: a :class:`.Config` instance.
:param revision: target revision or list of revisions. May be a list
to indicate stamping of multiple branch heads; may be ``"base"``
to remove all revisions from the table or ``"heads"`` to stamp the
most recent revision(s).
.. note:: this parameter is called "revisions" in the command line
interface.
:param sql: use ``--sql`` mode
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :class:`.EnvironmentContext.get_tag_argument`
method.
:param purge: delete all entries in the version table before stamping. | def stamp(
config: Config,
revision: _RevIdType,
sql: bool = False,
tag: Optional[str] = None,
purge: bool = False,
) -> None:
"""'stamp' the revision table with the given revision; don't
run any migrations.
:param config: a :class:`.Config` instance.
:param revision: target revision or list of revisions. May be a list
to indicate stamping of multiple branch heads; may be ``"base"``
to remove all revisions from the table or ``"heads"`` to stamp the
most recent revision(s).
.. note:: this parameter is called "revisions" in the command line
interface.
:param sql: use ``--sql`` mode
:param tag: an arbitrary "tag" that can be intercepted by custom
``env.py`` scripts via the :class:`.EnvironmentContext.get_tag_argument`
method.
:param purge: delete all entries in the version table before stamping.
"""
script = ScriptDirectory.from_config(config)
if sql:
destination_revs = []
starting_rev = None
for _revision in util.to_list(revision):
if ":" in _revision:
srev, _revision = _revision.split(":", 2)
if starting_rev != srev:
if starting_rev is None:
starting_rev = srev
else:
raise util.CommandError(
"Stamp operation with --sql only supports a "
"single starting revision at a time"
)
destination_revs.append(_revision)
else:
destination_revs = util.to_list(revision)
def do_stamp(rev, context):
return script._stamp_revs(util.to_tuple(destination_revs), rev)
with EnvironmentContext(
config,
script,
fn=do_stamp,
as_sql=sql,
starting_rev=starting_rev if sql else None,
destination_rev=util.to_tuple(destination_revs),
tag=tag,
purge=purge,
):
script.run_env() |
Edit revision script(s) using $EDITOR.
:param config: a :class:`.Config` instance.
:param rev: target revision. | def edit(config: Config, rev: str) -> None:
"""Edit revision script(s) using $EDITOR.
:param config: a :class:`.Config` instance.
:param rev: target revision.
"""
script = ScriptDirectory.from_config(config)
if rev == "current":
def edit_current(rev, context):
if not rev:
raise util.CommandError("No current revisions")
for sc in script.get_revisions(rev):
util.open_in_editor(sc.path)
return []
with EnvironmentContext(config, script, fn=edit_current):
script.run_env()
else:
revs = script.get_revisions(rev)
if not revs:
raise util.CommandError(
"No revision files indicated by symbol '%s'" % rev
)
for sc in revs:
assert sc
util.open_in_editor(sc.path) |
Create the alembic version table if it doesn't exist already .
:param config: a :class:`.Config` instance.
:param sql: use ``--sql`` mode.
.. versionadded:: 1.7.6 | def ensure_version(config: Config, sql: bool = False) -> None:
"""Create the alembic version table if it doesn't exist already .
:param config: a :class:`.Config` instance.
:param sql: use ``--sql`` mode.
.. versionadded:: 1.7.6
"""
script = ScriptDirectory.from_config(config)
def do_ensure_version(rev, context):
context._ensure_version_table()
return []
with EnvironmentContext(
config,
script,
fn=do_ensure_version,
as_sql=sql,
):
script.run_env() |
The console runner function for Alembic. | def main(
argv: Optional[Sequence[str]] = None,
prog: Optional[str] = None,
**kwargs: Any,
) -> None:
"""The console runner function for Alembic."""
CommandLine(prog=prog).main(argv=argv) |
Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity as well as optional
comparison functions to use for datatypes and
server defaults - see the "autogenerate" arguments
at :meth:`.EnvironmentContext.configure`
for details on these.
The return format is a list of "diff" directives,
each representing individual differences::
from alembic.migration import MigrationContext
from alembic.autogenerate import compare_metadata
from sqlalchemy import (
create_engine,
MetaData,
Column,
Integer,
String,
Table,
text,
)
import pprint
engine = create_engine("sqlite://")
with engine.begin() as conn:
conn.execute(
text(
'''
create table foo (
id integer not null primary key,
old_data varchar,
x integer
)
'''
)
)
conn.execute(text("create table bar (data varchar)"))
metadata = MetaData()
Table(
"foo",
metadata,
Column("id", Integer, primary_key=True),
Column("data", Integer),
Column("x", Integer, nullable=False),
)
Table("bat", metadata, Column("info", String))
mc = MigrationContext.configure(engine.connect())
diff = compare_metadata(mc, metadata)
pprint.pprint(diff, indent=2, width=20)
Output::
[
(
"add_table",
Table(
"bat",
MetaData(),
Column("info", String(), table=<bat>),
schema=None,
),
),
(
"remove_table",
Table(
"bar",
MetaData(),
Column("data", VARCHAR(), table=<bar>),
schema=None,
),
),
(
"add_column",
None,
"foo",
Column("data", Integer(), table=<foo>),
),
[
(
"modify_nullable",
None,
"foo",
"x",
{
"existing_comment": None,
"existing_server_default": False,
"existing_type": INTEGER(),
},
True,
False,
)
],
(
"remove_column",
None,
"foo",
Column("old_data", VARCHAR(), table=<foo>),
),
]
:param context: a :class:`.MigrationContext`
instance.
:param metadata: a :class:`~sqlalchemy.schema.MetaData`
instance.
.. seealso::
:func:`.produce_migrations` - produces a :class:`.MigrationScript`
structure based on metadata comparison. | def compare_metadata(context: MigrationContext, metadata: MetaData) -> Any:
"""Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity as well as optional
comparison functions to use for datatypes and
server defaults - see the "autogenerate" arguments
at :meth:`.EnvironmentContext.configure`
for details on these.
The return format is a list of "diff" directives,
each representing individual differences::
from alembic.migration import MigrationContext
from alembic.autogenerate import compare_metadata
from sqlalchemy import (
create_engine,
MetaData,
Column,
Integer,
String,
Table,
text,
)
import pprint
engine = create_engine("sqlite://")
with engine.begin() as conn:
conn.execute(
text(
'''
create table foo (
id integer not null primary key,
old_data varchar,
x integer
)
'''
)
)
conn.execute(text("create table bar (data varchar)"))
metadata = MetaData()
Table(
"foo",
metadata,
Column("id", Integer, primary_key=True),
Column("data", Integer),
Column("x", Integer, nullable=False),
)
Table("bat", metadata, Column("info", String))
mc = MigrationContext.configure(engine.connect())
diff = compare_metadata(mc, metadata)
pprint.pprint(diff, indent=2, width=20)
Output::
[
(
"add_table",
Table(
"bat",
MetaData(),
Column("info", String(), table=<bat>),
schema=None,
),
),
(
"remove_table",
Table(
"bar",
MetaData(),
Column("data", VARCHAR(), table=<bar>),
schema=None,
),
),
(
"add_column",
None,
"foo",
Column("data", Integer(), table=<foo>),
),
[
(
"modify_nullable",
None,
"foo",
"x",
{
"existing_comment": None,
"existing_server_default": False,
"existing_type": INTEGER(),
},
True,
False,
)
],
(
"remove_column",
None,
"foo",
Column("old_data", VARCHAR(), table=<foo>),
),
]
:param context: a :class:`.MigrationContext`
instance.
:param metadata: a :class:`~sqlalchemy.schema.MetaData`
instance.
.. seealso::
:func:`.produce_migrations` - produces a :class:`.MigrationScript`
structure based on metadata comparison.
"""
migration_script = produce_migrations(context, metadata)
assert migration_script.upgrade_ops is not None
return migration_script.upgrade_ops.as_diffs() |
Produce a :class:`.MigrationScript` structure based on schema
comparison.
This function does essentially what :func:`.compare_metadata` does,
but then runs the resulting list of diffs to produce the full
:class:`.MigrationScript` object. For an example of what this looks like,
see the example in :ref:`customizing_revision`.
.. seealso::
:func:`.compare_metadata` - returns more fundamental "diff"
data from comparing a schema. | def produce_migrations(
context: MigrationContext, metadata: MetaData
) -> MigrationScript:
"""Produce a :class:`.MigrationScript` structure based on schema
comparison.
This function does essentially what :func:`.compare_metadata` does,
but then runs the resulting list of diffs to produce the full
:class:`.MigrationScript` object. For an example of what this looks like,
see the example in :ref:`customizing_revision`.
.. seealso::
:func:`.compare_metadata` - returns more fundamental "diff"
data from comparing a schema.
"""
autogen_context = AutogenContext(context, metadata=metadata)
migration_script = ops.MigrationScript(
rev_id=None,
upgrade_ops=ops.UpgradeOps([]),
downgrade_ops=ops.DowngradeOps([]),
)
compare._populate_migration_script(autogen_context, migration_script)
return migration_script |
Render Python code given an :class:`.UpgradeOps` or
:class:`.DowngradeOps` object.
This is a convenience function that can be used to test the
autogenerate output of a user-defined :class:`.MigrationScript` structure.
:param up_or_down_op: :class:`.UpgradeOps` or :class:`.DowngradeOps` object
:param sqlalchemy_module_prefix: module prefix for SQLAlchemy objects
:param alembic_module_prefix: module prefix for Alembic constructs
:param render_as_batch: use "batch operations" style for rendering
:param imports: sequence of import symbols to add
:param render_item: callable to render items
:param migration_context: optional :class:`.MigrationContext`
:param user_module_prefix: optional string prefix for user-defined types
.. versionadded:: 1.11.0 | def render_python_code(
up_or_down_op: Union[UpgradeOps, DowngradeOps],
sqlalchemy_module_prefix: str = "sa.",
alembic_module_prefix: str = "op.",
render_as_batch: bool = False,
imports: Sequence[str] = (),
render_item: Optional[RenderItemFn] = None,
migration_context: Optional[MigrationContext] = None,
user_module_prefix: Optional[str] = None,
) -> str:
"""Render Python code given an :class:`.UpgradeOps` or
:class:`.DowngradeOps` object.
This is a convenience function that can be used to test the
autogenerate output of a user-defined :class:`.MigrationScript` structure.
:param up_or_down_op: :class:`.UpgradeOps` or :class:`.DowngradeOps` object
:param sqlalchemy_module_prefix: module prefix for SQLAlchemy objects
:param alembic_module_prefix: module prefix for Alembic constructs
:param render_as_batch: use "batch operations" style for rendering
:param imports: sequence of import symbols to add
:param render_item: callable to render items
:param migration_context: optional :class:`.MigrationContext`
:param user_module_prefix: optional string prefix for user-defined types
.. versionadded:: 1.11.0
"""
opts = {
"sqlalchemy_module_prefix": sqlalchemy_module_prefix,
"alembic_module_prefix": alembic_module_prefix,
"render_item": render_item,
"render_as_batch": render_as_batch,
"user_module_prefix": user_module_prefix,
}
if migration_context is None:
from ..runtime.migration import MigrationContext
from sqlalchemy.engine.default import DefaultDialect
migration_context = MigrationContext.configure(
dialect=DefaultDialect()
)
autogen_context = AutogenContext(migration_context, opts=opts)
autogen_context.imports = set(imports)
return render._indent(
render._render_cmd_body(up_or_down_op, autogen_context)
) |
legacy, used by test_autogen_composition at the moment | def _render_migration_diffs(
context: MigrationContext, template_args: Dict[Any, Any]
) -> None:
"""legacy, used by test_autogen_composition at the moment"""
autogen_context = AutogenContext(context)
upgrade_ops = ops.UpgradeOps([])
compare._produce_net_changes(autogen_context, upgrade_ops)
migration_script = ops.MigrationScript(
rev_id=None,
upgrade_ops=upgrade_ops,
downgrade_ops=upgrade_ops.reverse(),
)
render._render_python_into_templatevars(
autogen_context, migration_script, template_args
) |
we want to warn if a computed sql expression has changed. however
we don't want false positives and the warning is not that critical.
so filter out most forms of variability from the SQL text. | def _normalize_computed_default(sqltext: str) -> str:
"""we want to warn if a computed sql expression has changed. however
we don't want false positives and the warning is not that critical.
so filter out most forms of variability from the SQL text.
"""
return re.sub(r"[ \(\)'\"`\[\]\t\r\n]", "", sqltext).lower() |
produce a __repr__() object for a string identifier that may
use quoted_name() in SQLAlchemy 0.9 and greater.
The issue worked around here is that quoted_name() doesn't have
very good repr() behavior by itself when unicode is involved. | def _ident(name: Optional[Union[quoted_name, str]]) -> Optional[str]:
"""produce a __repr__() object for a string identifier that may
use quoted_name() in SQLAlchemy 0.9 and greater.
The issue worked around here is that quoted_name() doesn't have
very good repr() behavior by itself when unicode is involved.
"""
if name is None:
return name
elif isinstance(name, quoted_name):
return str(name)
elif isinstance(name, str):
return name |
Implement a 'safe' version of ForeignKey._get_colspec() that
won't fail if the remote table can't be resolved. | def _fk_colspec(
fk: ForeignKey,
metadata_schema: Optional[str],
namespace_metadata: MetaData,
) -> str:
"""Implement a 'safe' version of ForeignKey._get_colspec() that
won't fail if the remote table can't be resolved.
"""
colspec = fk._get_colspec()
tokens = colspec.split(".")
tname, colname = tokens[-2:]
if metadata_schema is not None and len(tokens) == 2:
table_fullname = "%s.%s" % (metadata_schema, tname)
else:
table_fullname = ".".join(tokens[0:-1])
if (
not fk.link_to_name
and fk.parent is not None
and fk.parent.table is not None
):
# try to resolve the remote table in order to adjust for column.key.
# the FK constraint needs to be rendered in terms of the column
# name.
if table_fullname in namespace_metadata.tables:
col = namespace_metadata.tables[table_fullname].c.get(colname)
if col is not None:
colname = _ident(col.name) # type: ignore[assignment]
colspec = "%s.%s" % (table_fullname, colname)
return colspec |
quote the elements of a dotted name | def quote_dotted(
name: Union[quoted_name, str], quote: functools.partial
) -> Union[quoted_name, str]:
"""quote the elements of a dotted name"""
if isinstance(name, quoted_name):
return quote(name)
result = ".".join([quote(x) for x in name.split(".")])
return result |
Redefine SQLAlchemy's drop constraint to
raise errors for invalid constraint type. | def _mysql_drop_constraint(
element: DropConstraint, compiler: MySQLDDLCompiler, **kw
) -> str:
"""Redefine SQLAlchemy's drop constraint to
raise errors for invalid constraint type."""
constraint = element.element
if isinstance(
constraint,
(
schema.ForeignKeyConstraint,
schema.PrimaryKeyConstraint,
schema.UniqueConstraint,
),
):
assert not kw
return compiler.visit_drop_constraint(element)
elif isinstance(constraint, schema.CheckConstraint):
# note that SQLAlchemy as of 1.2 does not yet support
# DROP CONSTRAINT for MySQL/MariaDB, so we implement fully
# here.
if _is_mariadb(compiler.dialect):
return "ALTER TABLE %s DROP CONSTRAINT %s" % (
compiler.preparer.format_table(constraint.table),
compiler.preparer.format_constraint(constraint),
)
else:
return "ALTER TABLE %s DROP CHECK %s" % (
compiler.preparer.format_table(constraint.table),
compiler.preparer.format_constraint(constraint),
)
else:
raise NotImplementedError(
"No generic 'DROP CONSTRAINT' in MySQL - "
"please specify constraint type"
) |
A function decorator that will register that function as a write hook.
See the documentation linked below for an example.
.. seealso::
:ref:`post_write_hooks_custom` | def register(name: str) -> Callable:
"""A function decorator that will register that function as a write hook.
See the documentation linked below for an example.
.. seealso::
:ref:`post_write_hooks_custom`
"""
def decorate(fn):
_registry[name] = fn
return fn
return decorate |
Invokes the formatter registered for the given name.
:param name: The name of a formatter in the registry
:param revision: A :class:`.MigrationRevision` instance
:param options: A dict containing kwargs passed to the
specified formatter.
:raises: :class:`alembic.util.CommandError` | def _invoke(
name: str, revision: str, options: Mapping[str, Union[str, int]]
) -> Any:
"""Invokes the formatter registered for the given name.
:param name: The name of a formatter in the registry
:param revision: A :class:`.MigrationRevision` instance
:param options: A dict containing kwargs passed to the
specified formatter.
:raises: :class:`alembic.util.CommandError`
"""
try:
hook = _registry[name]
except KeyError as ke:
raise util.CommandError(
f"No formatter with name '{name}' registered"
) from ke
else:
return hook(revision, options) |
Invoke hooks for a generated revision. | def _run_hooks(path: str, hook_config: Mapping[str, str]) -> None:
"""Invoke hooks for a generated revision."""
from .base import _split_on_space_comma
names = _split_on_space_comma.split(hook_config.get("hooks", ""))
for name in names:
if not name:
continue
opts = {
key[len(name) + 1 :]: hook_config[key]
for key in hook_config
if key.startswith(name + ".")
}
opts["_hook_name"] = name
try:
type_ = opts["type"]
except KeyError as ke:
raise util.CommandError(
f"Key {name}.type is required for post write hook {name!r}"
) from ke
else:
with util.status(
f"Running post write hook {name!r}", newline=True
):
_invoke(type_, path, opts) |
Parse options from a string into a list.
Also substitutes the revision script token with the actual filename of
the revision script.
If the revision script token doesn't occur in the options string, it is
automatically prepended. | def _parse_cmdline_options(cmdline_options_str: str, path: str) -> List[str]:
"""Parse options from a string into a list.
Also substitutes the revision script token with the actual filename of
the revision script.
If the revision script token doesn't occur in the options string, it is
automatically prepended.
"""
if REVISION_SCRIPT_TOKEN not in cmdline_options_str:
cmdline_options_str = REVISION_SCRIPT_TOKEN + " " + cmdline_options_str
cmdline_options_list = shlex.split(
cmdline_options_str, posix=compat.is_posix
)
cmdline_options_list = [
option.replace(REVISION_SCRIPT_TOKEN, path)
for option in cmdline_options_list
]
return cmdline_options_list |
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations() |
Run migrations in 'online' mode. | def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations()) |
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations() |
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations() |
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
# for the --sql use case, run migrations for each URL into
# individual files.
engines = {}
for name in re.split(r",\s*", db_names):
engines[name] = rec = {}
rec["url"] = context.config.get_section_option(name, "sqlalchemy.url")
for name, rec in engines.items():
logger.info("Migrating database %s" % name)
file_ = "%s.sql" % name
logger.info("Writing output to %s" % file_)
with open(file_, "w") as buffer:
context.configure(
url=rec["url"],
output_buffer=buffer,
target_metadata=target_metadata.get(name),
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations(engine_name=name) |
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# for the direct-to-DB use case, start a transaction on all
# engines, then run all migrations, then commit all transactions.
engines = {}
for name in re.split(r",\s*", db_names):
engines[name] = rec = {}
rec["engine"] = engine_from_config(
context.config.get_section(name, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
for name, rec in engines.items():
engine = rec["engine"]
rec["connection"] = conn = engine.connect()
if USE_TWOPHASE:
rec["transaction"] = conn.begin_twophase()
else:
rec["transaction"] = conn.begin()
try:
for name, rec in engines.items():
logger.info("Migrating database %s" % name)
context.configure(
connection=rec["connection"],
upgrade_token="%s_upgrades" % name,
downgrade_token="%s_downgrades" % name,
target_metadata=target_metadata.get(name),
)
context.run_migrations(engine_name=name)
if USE_TWOPHASE:
for rec in engines.values():
rec["transaction"].prepare()
for rec in engines.values():
rec["transaction"].commit()
except:
for rec in engines.values():
rec["transaction"].rollback()
raise
finally:
for rec in engines.values():
rec["connection"].close() |
assert that any exception we're catching does not have a __context__
without a __cause__, and that __suppress_context__ is never set.
Python 3 will report nested as exceptions as "during the handling of
error X, error Y occurred". That's not what we want to do. we want
these exceptions in a cause chain. | def _assert_proper_exception_context(exception):
"""assert that any exception we're catching does not have a __context__
without a __cause__, and that __suppress_context__ is never set.
Python 3 will report nested as exceptions as "during the handling of
error X, error Y occurred". That's not what we want to do. we want
these exceptions in a cause chain.
"""
if (
exception.__context__ is not exception.__cause__
and not exception.__suppress_context__
):
assert False, (
"Exception %r was correctly raised but did not set a cause, "
"within context %r as its cause."
% (exception, exception.__context__)
) |
Subsets and Splits