-
Notifications
You must be signed in to change notification settings - Fork 8
/
test_views.py
3408 lines (2906 loc) · 137 KB
/
test_views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import copy
import html
import io
import json
import logging.config
import os
import re
import shutil
import sys
import tempfile
import unittest
import urllib
from contextlib import contextmanager
from datetime import datetime as dt, timedelta
from typing import Any, Dict, Generator, List, NamedTuple
from unittest import mock
from unittest.mock import PropertyMock
from urllib.parse import quote_plus
import jinja2
import pytest
from flask import Markup, session as flask_session, template_rendered, url_for
from parameterized import parameterized
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from airflow import models, settings, version
from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG
from airflow.configuration import conf
from airflow.executors.celery_executor import CeleryExecutor
from airflow.jobs.base_job import BaseJob
from airflow.models import DAG, Connection, DagRun, TaskInstance
from airflow.models.baseoperator import BaseOperator, BaseOperatorLink
from airflow.models.renderedtifields import RenderedTaskInstanceFields as RTIF
from airflow.models.serialized_dag import SerializedDagModel
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.plugins_manager import AirflowPlugin, EntryPointSource
from airflow.security import permissions
from airflow.ti_deps.dependencies_states import QUEUEABLE_STATES, RUNNABLE_STATES
from airflow.utils import dates, timezone
from airflow.utils.log.logging_mixin import ExternalLoggingMixin
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 import app as application
from airflow.www.views import ConnectionModelView, get_safe_url, truncate_task_duration
from tests.test_utils import fab_utils
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_runs
from tests.test_utils.mock_plugins import mock_plugin_manager
class TemplateWithContext(NamedTuple):
template: jinja2.environment.Template
context: Dict[str, Any]
@property
def name(self):
return self.template.name
@property
def local_context(self):
"""Returns context without global arguments"""
result = copy.copy(self.context)
keys_to_delete = [
# flask.templating._default_template_ctx_processor
'g',
'request',
'session',
# flask_wtf.csrf.CSRFProtect.init_app
'csrf_token',
# flask_login.utils._user_context_processor
'current_user',
# flask_appbuilder.baseviews.BaseView.render_template
'appbuilder',
'base_template',
# airflow.www.app.py.create_app (inner method - jinja_globals)
'server_timezone',
'default_ui_timezone',
'hostname',
'navbar_color',
'log_fetch_delay_sec',
'log_auto_tailing_offset',
'log_animation_speed',
'state_color_mapping',
'airflow_version',
'git_version',
'k8s_or_k8scelery_executor',
# airflow.www.static_config.configure_manifest_files
'url_for_asset',
# airflow.www.views.AirflowBaseView.render_template
'scheduler_job',
# airflow.www.views.AirflowBaseView.extra_args
'macros',
]
for key in keys_to_delete:
del result[key]
return result
class TestBase(unittest.TestCase):
@classmethod
def setUpClass(cls):
settings.configure_orm()
cls.session = settings.Session
cls.app = application.create_app(testing=True)
cls.appbuilder = cls.app.appbuilder # pylint: disable=no-member
cls.app.config['WTF_CSRF_ENABLED'] = False
cls.app.jinja_env.undefined = jinja2.StrictUndefined
@classmethod
def tearDownClass(cls) -> None:
clear_db_runs()
def setUp(self):
self.client = self.app.test_client()
self.login()
def login(self, username='test', password='test'):
if username == 'test' and not self.appbuilder.sm.find_user(username='test'):
self.appbuilder.sm.add_user(
username='test',
first_name='test',
last_name='test',
email='test@fab.org',
role=self.appbuilder.sm.find_role('Admin'),
password='test',
)
if username == 'test_user' and not self.appbuilder.sm.find_user(username='test_user'):
self.appbuilder.sm.add_user(
username='test_user',
first_name='test_user',
last_name='test_user',
email='test_user@fab.org',
role=self.appbuilder.sm.find_role('User'),
password='test_user',
)
if username == 'test_viewer' and not self.appbuilder.sm.find_user(username='test_viewer'):
self.appbuilder.sm.add_user(
username='test_viewer',
first_name='test_viewer',
last_name='test_viewer',
email='test_viewer@fab.org',
role=self.appbuilder.sm.find_role('Viewer'),
password='test_viewer',
)
return self.client.post('/login/', data={"username": username, "password": password})
def logout(self):
return self.client.get('/logout/')
@contextmanager
def capture_templates(self) -> Generator[List[TemplateWithContext], None, None]:
recorded = []
def record(sender, template, context, **extra): # pylint: disable=unused-argument
recorded.append(TemplateWithContext(template, context))
template_rendered.connect(record, self.app) # type: ignore
try:
yield recorded
finally:
template_rendered.disconnect(record, self.app) # type: ignore
assert recorded, "Failed to catch the templates"
@classmethod
def clear_table(cls, model):
with create_session() as session:
session.query(model).delete()
def check_content_in_response(self, text, resp, resp_code=200):
resp_html = resp.data.decode('utf-8')
assert resp_code == resp.status_code
if isinstance(text, list):
for line in text:
assert line in resp_html
else:
assert text in resp_html
def check_content_not_in_response(self, text, resp, resp_code=200):
resp_html = resp.data.decode('utf-8')
assert resp_code == resp.status_code
if isinstance(text, list):
for line in text:
assert line not in resp_html
else:
assert text not in resp_html
@staticmethod
def percent_encode(obj):
return urllib.parse.quote_plus(str(obj))
def create_user_and_login(self, username, role_name, perms):
self.logout()
fab_utils.create_user(
self.app,
username=username,
role_name=role_name,
permissions=perms,
)
self.login(username=username, password=username)
class TestConnectionModelView(TestBase):
def setUp(self):
super().setUp()
self.connection = {
'conn_id': 'test_conn',
'conn_type': 'http',
'description': 'description',
'host': 'localhost',
'port': 8080,
'username': 'root',
'password': 'admin',
}
def tearDown(self):
self.clear_table(Connection)
super().tearDown()
def test_create_connection(self):
resp = self.client.post('/connection/add', data=self.connection, follow_redirects=True)
self.check_content_in_response('Added Row', resp)
def test_prefill_form_null_extra(self):
mock_form = mock.Mock()
mock_form.data = {"conn_id": "test", "extra": None}
cmv = ConnectionModelView()
cmv.prefill_form(form=mock_form, pk=1)
class TestVariableModelView(TestBase):
def setUp(self):
super().setUp()
self.variable = {'key': 'test_key', 'val': 'text_val', 'is_encrypted': True}
def tearDown(self):
self.clear_table(models.Variable)
super().tearDown()
def test_can_handle_error_on_decrypt(self):
# create valid variable
self.client.post('/variable/add', data=self.variable, follow_redirects=True)
# update the variable with a wrong value, given that is encrypted
Var = models.Variable # pylint: disable=invalid-name
(
self.session.query(Var)
.filter(Var.key == self.variable['key'])
.update({'val': 'failed_value_not_encrypted'}, synchronize_session=False)
)
self.session.commit()
# retrieve Variables page, should not fail and contain the Invalid
# label for the variable
resp = self.client.get('/variable/list', follow_redirects=True)
self.check_content_in_response('<span class="label label-danger">Invalid</span>', resp)
def test_xss_prevention(self):
xss = "/variable/list/<img%20src=''%20onerror='alert(1);'>"
resp = self.client.get(
xss,
follow_redirects=True,
)
assert resp.status_code == 404
assert "<img src='' onerror='alert(1);'>" not in resp.data.decode("utf-8")
def test_import_variables_no_file(self):
resp = self.client.post('/variable/varimport', follow_redirects=True)
self.check_content_in_response('Missing file or syntax error.', resp)
def test_import_variables_failed(self):
content = '{"str_key": "str_value"}'
with mock.patch('airflow.models.Variable.set') as set_mock:
set_mock.side_effect = UnicodeEncodeError
assert self.session.query(models.Variable).count() == 0
try:
# python 3+
bytes_content = io.BytesIO(bytes(content, encoding='utf-8'))
except TypeError:
# python 2.7
bytes_content = io.BytesIO(bytes(content))
resp = self.client.post(
'/variable/varimport', data={'file': (bytes_content, 'test.json')}, follow_redirects=True
)
self.check_content_in_response('1 variable(s) failed to be updated.', resp)
def test_import_variables_success(self):
assert self.session.query(models.Variable).count() == 0
content = (
'{"str_key": "str_value", "int_key": 60, "list_key": [1, 2], "dict_key": {"k_a": 2, "k_b": 3}}'
)
try:
# python 3+
bytes_content = io.BytesIO(bytes(content, encoding='utf-8'))
except TypeError:
# python 2.7
bytes_content = io.BytesIO(bytes(content))
resp = self.client.post(
'/variable/varimport', data={'file': (bytes_content, 'test.json')}, follow_redirects=True
)
self.check_content_in_response('4 variable(s) successfully updated.', resp)
class PluginOperator(BaseOperator):
pass
class TestPluginView(TestBase):
def test_should_list_plugins_on_page_with_details(self):
resp = self.client.get('/plugin')
self.check_content_in_response("test_plugin", resp)
self.check_content_in_response("Airflow Plugins", resp)
self.check_content_in_response("source", resp)
self.check_content_in_response("<em>$PLUGINS_FOLDER/</em>test_plugin.py", resp)
def test_should_list_entrypoint_plugins_on_page_with_details(self):
mock_plugin = AirflowPlugin()
mock_plugin.name = "test_plugin"
mock_plugin.source = EntryPointSource(
mock.Mock(), mock.Mock(version='1.0.0', metadata={'name': 'test-entrypoint-testpluginview'})
)
with mock_plugin_manager(plugins=[mock_plugin]):
resp = self.client.get('/plugin')
self.check_content_in_response("test_plugin", resp)
self.check_content_in_response("Airflow Plugins", resp)
self.check_content_in_response("source", resp)
self.check_content_in_response("<em>test-entrypoint-testpluginview==1.0.0:</em> <Mock id=", resp)
def test_endpoint_should_not_be_unauthenticated(self):
self.logout()
resp = self.client.get('/plugin', follow_redirects=True)
self.check_content_not_in_response("test_plugin", resp)
self.check_content_in_response("Sign In - Airflow", resp)
class TestPoolModelView(TestBase):
def setUp(self):
super().setUp()
self.pool = {
'pool': 'test-pool',
'slots': 777,
'description': 'test-pool-description',
}
def tearDown(self):
self.clear_table(models.Pool)
super().tearDown()
def test_create_pool_with_same_name(self):
# create test pool
resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
self.check_content_in_response('Added Row', resp)
# create pool with the same name
resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
self.check_content_in_response('Already exists.', resp)
def test_create_pool_with_empty_name(self):
self.pool['pool'] = ''
resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
self.check_content_in_response('This field is required.', resp)
def test_odd_name(self):
self.pool['pool'] = 'test-pool<script></script>'
self.session.add(models.Pool(**self.pool))
self.session.commit()
resp = self.client.get('/pool/list/')
self.check_content_in_response('test-pool<script>', resp)
self.check_content_not_in_response('test-pool<script>', resp)
def test_list(self):
self.pool['pool'] = 'test-pool'
self.session.add(models.Pool(**self.pool))
self.session.commit()
resp = self.client.get('/pool/list/')
# We should see this link
with self.app.test_request_context():
url = url_for('TaskInstanceModelView.list', _flt_3_pool='test-pool', _flt_3_state='running')
used_tag = Markup("<a href='{url}'>{slots}</a>").format(url=url, slots=0)
url = url_for('TaskInstanceModelView.list', _flt_3_pool='test-pool', _flt_3_state='queued')
queued_tag = Markup("<a href='{url}'>{slots}</a>").format(url=url, slots=0)
self.check_content_in_response(used_tag, resp)
self.check_content_in_response(queued_tag, resp)
class TestMountPoint(unittest.TestCase):
@classmethod
@conf_vars({("webserver", "base_url"): "http://localhost/test"})
def setUpClass(cls):
application.app = None
application.appbuilder = None
app = application.cached_app(config={'WTF_CSRF_ENABLED': False}, testing=True)
cls.client = Client(app, BaseResponse)
@classmethod
def tearDownClass(cls):
application.app = None
application.appbuilder = None
def test_mount(self):
# Test an endpoint that doesn't need auth!
resp = self.client.get('/test/health')
assert resp.status_code == 200
assert b"healthy" in resp.data
def test_not_found(self):
resp = self.client.get('/', follow_redirects=True)
assert resp.status_code == 404
def test_index(self):
resp = self.client.get('/test/')
assert resp.status_code == 302
assert resp.headers['Location'] == 'http://localhost/test/home'
class TestAirflowBaseViews(TestBase):
EXAMPLE_DAG_DEFAULT_DATE = dates.days_ago(2)
@classmethod
def setUpClass(cls):
super().setUpClass()
models.DagBag(include_examples=True).sync_to_db()
cls.dagbag = models.DagBag(include_examples=True, read_dags_from_db=True)
cls.app.dag_bag = cls.dagbag
def setUp(self):
super().setUp()
self.logout()
self.login()
clear_db_runs()
self.prepare_dagruns()
def prepare_dagruns(self):
self.bash_dag = self.dagbag.get_dag('example_bash_operator')
self.sub_dag = self.dagbag.get_dag('example_subdag_operator')
self.xcom_dag = self.dagbag.get_dag('example_xcom')
self.bash_dagrun = self.bash_dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
state=State.RUNNING,
)
self.sub_dagrun = self.sub_dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
state=State.RUNNING,
)
self.xcom_dagrun = self.xcom_dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
state=State.RUNNING,
)
def test_index(self):
with assert_queries_count(43):
resp = self.client.get('/', follow_redirects=True)
self.check_content_in_response('DAGs', resp)
def test_doc_urls(self):
resp = self.client.get('/', follow_redirects=True)
if "dev" in version.version:
airflow_doc_site = (
"http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/"
)
else:
airflow_doc_site = f'https://airflow.apache.org/docs/apache-airflow/{version.version}'
self.check_content_in_response(airflow_doc_site, resp)
self.check_content_in_response("/api/v1/ui", resp)
def test_health(self):
# case-1: healthy scheduler status
last_scheduler_heartbeat_for_testing_1 = timezone.utcnow()
self.session.add(
BaseJob(
job_type='SchedulerJob',
state='running',
latest_heartbeat=last_scheduler_heartbeat_for_testing_1,
)
)
self.session.commit()
resp_json = json.loads(self.client.get('health', follow_redirects=True).data.decode('utf-8'))
assert 'healthy' == resp_json['metadatabase']['status']
assert 'healthy' == resp_json['scheduler']['status']
assert (
last_scheduler_heartbeat_for_testing_1.isoformat()
== resp_json['scheduler']['latest_scheduler_heartbeat']
)
self.session.query(BaseJob).filter(
BaseJob.job_type == 'SchedulerJob',
BaseJob.state == 'running',
BaseJob.latest_heartbeat == last_scheduler_heartbeat_for_testing_1,
).delete()
self.session.commit()
# case-2: unhealthy scheduler status - scenario 1 (SchedulerJob is running too slowly)
last_scheduler_heartbeat_for_testing_2 = timezone.utcnow() - timedelta(minutes=1)
(
self.session.query(BaseJob)
.filter(BaseJob.job_type == 'SchedulerJob')
.update({'latest_heartbeat': last_scheduler_heartbeat_for_testing_2 - timedelta(seconds=1)})
)
self.session.add(
BaseJob(
job_type='SchedulerJob',
state='running',
latest_heartbeat=last_scheduler_heartbeat_for_testing_2,
)
)
self.session.commit()
resp_json = json.loads(self.client.get('health', follow_redirects=True).data.decode('utf-8'))
assert 'healthy' == resp_json['metadatabase']['status']
assert 'unhealthy' == resp_json['scheduler']['status']
assert (
last_scheduler_heartbeat_for_testing_2.isoformat()
== resp_json['scheduler']['latest_scheduler_heartbeat']
)
self.session.query(BaseJob).filter(
BaseJob.job_type == 'SchedulerJob',
BaseJob.state == 'running',
BaseJob.latest_heartbeat == last_scheduler_heartbeat_for_testing_2,
).delete()
self.session.commit()
# case-3: unhealthy scheduler status - scenario 2 (no running SchedulerJob)
self.session.query(BaseJob).filter(
BaseJob.job_type == 'SchedulerJob', BaseJob.state == 'running'
).delete()
self.session.commit()
resp_json = json.loads(self.client.get('health', follow_redirects=True).data.decode('utf-8'))
assert 'healthy' == resp_json['metadatabase']['status']
assert 'unhealthy' == resp_json['scheduler']['status']
assert resp_json['scheduler']['latest_scheduler_heartbeat'] is None
def test_home(self):
with self.capture_templates() as templates:
resp = self.client.get('home', follow_redirects=True)
self.check_content_in_response('DAGs', resp)
val_state_color_mapping = (
'const STATE_COLOR = {"failed": "red", '
'"null": "lightblue", "queued": "gray", '
'"removed": "lightgrey", "running": "lime", '
'"scheduled": "tan", "sensing": "lightseagreen", '
'"shutdown": "blue", "skipped": "pink", '
'"success": "green", "up_for_reschedule": "turquoise", '
'"up_for_retry": "gold", "upstream_failed": "orange"};'
)
self.check_content_in_response(val_state_color_mapping, resp)
assert len(templates) == 1
assert templates[0].name == 'airflow/dags.html'
state_color_mapping = State.state_color.copy()
state_color_mapping["null"] = state_color_mapping.pop(None)
assert templates[0].local_context['state_color'] == state_color_mapping
def test_users_list(self):
resp = self.client.get('users/list', follow_redirects=True)
self.check_content_in_response('List Users', resp)
def test_roles_list(self):
resp = self.client.get('roles/list', follow_redirects=True)
self.check_content_in_response('List Roles', resp)
def test_userstatschart_view(self):
resp = self.client.get('userstatschartview/chart/', follow_redirects=True)
self.check_content_in_response('User Statistics', resp)
def test_permissions_list(self):
resp = self.client.get('permissions/list/', follow_redirects=True)
self.check_content_in_response('List Base Permissions', resp)
def test_viewmenus_list(self):
resp = self.client.get('viewmenus/list/', follow_redirects=True)
self.check_content_in_response('List View Menus', resp)
def test_permissionsviews_list(self):
resp = self.client.get('permissionviews/list/', follow_redirects=True)
self.check_content_in_response('List Permissions on Views/Menus', resp)
def test_home_filter_tags(self):
from airflow.www.views import FILTER_TAGS_COOKIE
with self.client:
self.client.get('home?tags=example&tags=data', follow_redirects=True)
assert 'example,data' == flask_session[FILTER_TAGS_COOKIE]
self.client.get('home?reset_tags', follow_redirects=True)
assert flask_session[FILTER_TAGS_COOKIE] is None
def test_home_status_filter_cookie(self):
from airflow.www.views import FILTER_STATUS_COOKIE
with self.client:
self.client.get('home', follow_redirects=True)
assert 'all' == flask_session[FILTER_STATUS_COOKIE]
self.client.get('home?status=active', follow_redirects=True)
assert 'active' == flask_session[FILTER_STATUS_COOKIE]
self.client.get('home?status=paused', follow_redirects=True)
assert 'paused' == flask_session[FILTER_STATUS_COOKIE]
self.client.get('home?status=all', follow_redirects=True)
assert 'all' == flask_session[FILTER_STATUS_COOKIE]
def test_task(self):
url = 'task?task_id=runme_0&dag_id=example_bash_operator&execution_date={}'.format(
self.percent_encode(self.EXAMPLE_DAG_DEFAULT_DATE)
)
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('Task Instance Details', resp)
def test_xcom(self):
url = 'xcom?task_id=runme_0&dag_id=example_bash_operator&execution_date={}'.format(
self.percent_encode(self.EXAMPLE_DAG_DEFAULT_DATE)
)
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('XCom', resp)
def test_xcom_list_view_title(self):
resp = self.client.get('xcom/list', follow_redirects=True)
self.check_content_in_response('List XComs', resp)
def test_rendered_template(self):
url = 'rendered-templates?task_id=runme_0&dag_id=example_bash_operator&execution_date={}'.format(
self.percent_encode(self.EXAMPLE_DAG_DEFAULT_DATE)
)
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('Rendered Template', resp)
def test_rendered_k8s(self):
url = 'rendered-k8s?task_id=runme_0&dag_id=example_bash_operator&execution_date={}'.format(
self.percent_encode(self.EXAMPLE_DAG_DEFAULT_DATE)
)
with mock.patch.object(settings, "IS_K8S_OR_K8SCELERY_EXECUTOR", True):
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('K8s Pod Spec', resp)
@conf_vars({('core', 'executor'): 'LocalExecutor'})
def test_rendered_k8s_without_k8s(self):
url = 'rendered-k8s?task_id=runme_0&dag_id=example_bash_operator&execution_date={}'.format(
self.percent_encode(self.EXAMPLE_DAG_DEFAULT_DATE)
)
resp = self.client.get(url, follow_redirects=True)
assert 404 == resp.status_code
def test_blocked(self):
url = 'blocked'
resp = self.client.post(url, follow_redirects=True)
assert 200 == resp.status_code
def test_dag_stats(self):
resp = self.client.post('dag_stats', follow_redirects=True)
assert resp.status_code == 200
def test_task_stats(self):
resp = self.client.post('task_stats', follow_redirects=True)
assert resp.status_code == 200
assert set(list(resp.json.items())[0][1][0].keys()) == {'state', 'count'}
@conf_vars({("webserver", "show_recent_stats_for_completed_runs"): "False"})
def test_task_stats_only_noncompleted(self):
resp = self.client.post('task_stats', follow_redirects=True)
assert resp.status_code == 200
def test_dag_details(self):
url = 'dag_details?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('DAG Details', resp)
@parameterized.expand(["graph", "tree", "dag_details"])
def test_view_uses_existing_dagbag(self, endpoint):
"""
Test that Graph, Tree & Dag Details View uses the DagBag already created in views.py
instead of creating a new one.
"""
url = f'{endpoint}?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
@parameterized.expand(
[
("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),
("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}'),
("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}'),
("\"", r'\"conf\":{\"abc\":\"\\\"\"}'),
]
)
def test_escape_in_tree_view(self, test_str, expected_text):
dag = self.dagbag.get_dag('test_tree_view')
dag.create_dagrun(
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
run_type=DagRunType.MANUAL,
state=State.RUNNING,
conf={"abc": test_str},
)
url = 'tree?dag_id=test_tree_view'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response(expected_text, resp)
def test_dag_details_trigger_origin_tree_view(self):
dag = self.dagbag.get_dag('test_tree_view')
dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
state=State.RUNNING,
)
url = 'dag_details?dag_id=test_tree_view'
resp = self.client.get(url, follow_redirects=True)
params = {'dag_id': 'test_tree_view', 'origin': '/tree?dag_id=test_tree_view'}
href = f"/trigger?{html.escape(urllib.parse.urlencode(params))}"
self.check_content_in_response(href, resp)
def test_dag_details_trigger_origin_graph_view(self):
dag = self.dagbag.get_dag('test_graph_view')
dag.create_dagrun(
run_type=DagRunType.SCHEDULED,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
start_date=timezone.utcnow(),
state=State.RUNNING,
)
url = 'dag_details?dag_id=test_graph_view'
resp = self.client.get(url, follow_redirects=True)
params = {'dag_id': 'test_graph_view', 'origin': '/graph?dag_id=test_graph_view'}
href = f"/trigger?{html.escape(urllib.parse.urlencode(params))}"
self.check_content_in_response(href, resp)
def test_dag_details_subdag(self):
url = 'dag_details?dag_id=example_subdag_operator.section-1'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('DAG Details', resp)
def test_graph(self):
url = 'graph?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('runme_1', resp)
def test_last_dagruns(self):
resp = self.client.post('last_dagruns', follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
def test_last_dagruns_success_when_selecting_dags(self):
resp = self.client.post(
'last_dagruns', data={'dag_ids': ['example_subdag_operator']}, follow_redirects=True
)
assert resp.status_code == 200
stats = json.loads(resp.data.decode('utf-8'))
assert 'example_bash_operator' not in stats
assert 'example_subdag_operator' in stats
# Multiple
resp = self.client.post(
'last_dagruns',
data={'dag_ids': ['example_subdag_operator', 'example_bash_operator']},
follow_redirects=True,
)
stats = json.loads(resp.data.decode('utf-8'))
assert 'example_bash_operator' in stats
assert 'example_subdag_operator' in stats
self.check_content_not_in_response('example_xcom', resp)
def test_tree(self):
url = 'tree?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('runme_1', resp)
def test_tree_subdag(self):
url = 'tree?dag_id=example_subdag_operator.section-1'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('section-1-task-1', resp)
def test_duration(self):
url = 'duration?days=30&dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
def test_duration_missing(self):
url = 'duration?days=30&dag_id=missing_dag'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('seems to be missing', resp)
def test_tries(self):
url = 'tries?days=30&dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
def test_landing_times(self):
url = 'landing_times?days=30&dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
def test_gantt(self):
url = 'gantt?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('example_bash_operator', resp)
def test_code(self):
url = 'code?dag_id=example_bash_operator'
resp = self.client.get(url, follow_redirects=True)
self.check_content_not_in_response('Failed to load file', resp)
self.check_content_in_response('example_bash_operator', resp)
def test_code_no_file(self):
url = 'code?dag_id=example_bash_operator'
mock_open_patch = mock.mock_open(read_data='')
mock_open_patch.side_effect = FileNotFoundError
with mock.patch('builtins.open', mock_open_patch), mock.patch(
"airflow.models.dagcode.STORE_DAG_CODE", False
):
resp = self.client.get(url, follow_redirects=True)
self.check_content_in_response('Failed to load file', resp)
self.check_content_in_response('example_bash_operator', resp)
@conf_vars({("core", "store_dag_code"): "True"})
def test_code_from_db(self):
from airflow.models.dagcode import DagCode
dag = models.DagBag(include_examples=True).get_dag("example_bash_operator")
DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db()
url = 'code?dag_id=example_bash_operator'
resp = self.client.get(url)
self.check_content_not_in_response('Failed to load file', resp)
self.check_content_in_response('example_bash_operator', resp)
@conf_vars({("core", "store_dag_code"): "True"})
def test_code_from_db_all_example_dags(self):
from airflow.models.dagcode import DagCode
dagbag = models.DagBag(include_examples=True)
for dag in dagbag.dags.values():
DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db()
url = 'code?dag_id=example_bash_operator'
resp = self.client.get(url)
self.check_content_not_in_response('Failed to load file', resp)
self.check_content_in_response('example_bash_operator', resp)
def test_paused(self):
url = 'paused?dag_id=example_bash_operator&is_paused=false'
resp = self.client.post(url, follow_redirects=True)
self.check_content_in_response('OK', resp)
def test_failed(self):
form = dict(
task_id="run_this_last",
dag_id="example_bash_operator",
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
upstream="false",
downstream="false",
future="false",
past="false",
)
resp = self.client.post("failed", data=form)
self.check_content_in_response('Wait a minute', resp)
def test_failed_dag_never_run(self):
endpoint = "failed"
dag_id = "example_bash_operator"
form = dict(
task_id="run_this_last",
dag_id=dag_id,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
upstream="false",
downstream="false",
future="false",
past="false",
origin="/graph?dag_id=example_bash_operator",
)
clear_db_runs()
resp = self.client.post(endpoint, data=form, follow_redirects=True)
self.check_content_in_response(f"Cannot make {endpoint}, seem that dag {dag_id} has never run", resp)
def test_failed_flash_hint(self):
form = dict(
task_id="run_this_last",
dag_id="example_bash_operator",
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
confirmed="true",
upstream="false",
downstream="false",
future="false",
past="false",
origin="/graph?dag_id=example_bash_operator",
)
resp = self.client.post("failed", data=form, follow_redirects=True)
self.check_content_in_response("Marked failed on 1 task instances", resp)
def test_success(self):
form = dict(
task_id="run_this_last",
dag_id="example_bash_operator",
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
upstream="false",
downstream="false",
future="false",
past="false",
)
resp = self.client.post('success', data=form)
self.check_content_in_response('Wait a minute', resp)
def test_success_dag_never_run(self):
endpoint = "success"
dag_id = "example_bash_operator"
form = dict(
task_id="run_this_last",
dag_id=dag_id,
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
upstream="false",
downstream="false",
future="false",
past="false",
origin="/graph?dag_id=example_bash_operator",
)
clear_db_runs()
resp = self.client.post('success', data=form, follow_redirects=True)
self.check_content_in_response(f"Cannot make {endpoint}, seem that dag {dag_id} has never run", resp)
def test_success_flash_hint(self):
form = dict(
task_id="run_this_last",
dag_id="example_bash_operator",
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
confirmed="true",
upstream="false",
downstream="false",
future="false",
past="false",
origin="/graph?dag_id=example_bash_operator",
)
resp = self.client.post("success", data=form, follow_redirects=True)
self.check_content_in_response("Marked success on 1 task instances", resp)
def test_clear(self):
form = dict(
task_id="runme_1",
dag_id="example_bash_operator",
execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
upstream="false",
downstream="false",
future="false",
past="false",
only_failed="false",
)
resp = self.client.post("clear", data=form)
self.check_content_in_response(['example_bash_operator', 'Wait a minute'], resp)