Skip to content

Commit

Permalink
Added exception catching to send default email if template file raise…
Browse files Browse the repository at this point in the history
…s any exception (#24943)

(cherry picked from commit fd6f537)
  • Loading branch information
ecodina authored and ephraimbuddy committed Aug 15, 2022
1 parent ef5b4c9 commit 146d510
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
9 changes: 7 additions & 2 deletions airflow/models/taskinstance.py
Original file line number Diff line number Diff line change
Expand Up @@ -2337,8 +2337,13 @@ def get_email_subject_content(
def render(key: str, content: str) -> str:
if conf.has_option('email', key):
path = conf.get_mandatory_value('email', key)
with open(path) as f:
content = f.read()
try:
with open(path) as f:
content = f.read()
except FileNotFoundError:
self.log.warning(f"Could not find email template file '{path!r}'. Using defaults...")
except OSError:
self.log.exception(f"Error while using email template '{path!r}'. Using defaults...")
return render_template_to_string(jinja_env.from_string(content), jinja_context)

subject = render('subject_template', default_subject)
Expand Down
34 changes: 34 additions & 0 deletions tests/models/test_taskinstance.py
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,40 @@ def test_email_alert_with_config(self, mock_send_email, dag_maker):
assert 'template: test_email_alert_with_config' == title
assert 'template: test_email_alert_with_config' == body

@patch('airflow.models.taskinstance.send_email')
def test_email_alert_with_filenotfound_config(self, mock_send_email, dag_maker):
with dag_maker(dag_id='test_failure_email'):
task = BashOperator(
task_id='test_email_alert_with_config',
bash_command='exit 1',
email='to',
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task

# Run test when the template file is not found
opener = mock_open(read_data='template: {{ti.task_id}}')
opener.side_effect = FileNotFoundError
with patch('airflow.models.taskinstance.open', opener, create=True):
try:
ti.run()
except AirflowException:
pass

(email_error, title_error, body_error), _ = mock_send_email.call_args

# Rerun task without any error and no template file
try:
ti.run()
except AirflowException:
pass

(email_default, title_default, body_default), _ = mock_send_email.call_args

assert email_error == email_default == 'to'
assert title_default == title_error
assert body_default == body_error

@pytest.mark.parametrize("task_id", ["test_email_alert", "test_email_alert__1"])
@patch('airflow.models.taskinstance.send_email')
def test_failure_mapped_taskflow(self, mock_send_email, dag_maker, session, task_id):
Expand Down

0 comments on commit 146d510

Please sign in to comment.