-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathtests.py
More file actions
1461 lines (1205 loc) · 54 KB
/
tests.py
File metadata and controls
1461 lines (1205 loc) · 54 KB
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
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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 os
import sys
import json
import time
import uuid
import logging
import tempfile
import subprocess
from io import StringIO as string_io
from unittest.mock import Mock, patch
import pytest
from configobj import ConfigObj
from django.core.management import call_command
from django.core.paginator import Paginator
from django.db import connection
from django.db.models import CharField, SmallIntegerField, query
from django.http import HttpResponse
from django.test.client import Client
from django.urls import re_path, reverse
from django.views.static import serve
import desktop
import desktop.conf
import desktop.urls
import desktop.views as views
import notebook.conf
import desktop.redaction as redaction
from dashboard.conf import HAS_SQL_ENABLED
from desktop.appmanager import DESKTOP_APPS
from desktop.auth.backend import rewrite_user
from desktop.lib.conf import _configs_from_dir, validate_path
from desktop.lib.django_test_util import make_logged_in_client
from desktop.lib.django_util import TruncatingModel
from desktop.lib.exceptions_renderable import PopupException
from desktop.lib.paths import get_desktop_root
from desktop.lib.python_util import force_dict_to_strings
from desktop.lib.test_utils import grant_access
from desktop.middleware import DJANGO_VIEW_AUTH_WHITELIST
from desktop.models import HUE_VERSION, ClusterConfig, Directory, Document, Document2, _version_from_properties, get_data_link
from desktop.redaction import logfilter
from desktop.redaction.engine import RedactionPolicy, RedactionRule
from desktop.settings import DATABASES
from desktop.views import _get_config_errors, check_config, collect_validation_messages, generate_configspec, home, load_confs
from notebook.conf import ENABLE_ALL_INTERPRETERS, SHOW_NOTEBOOKS
from useradmin.models import GroupPermission, User
LOG = logging.getLogger()
@pytest.mark.django_db
def test_home():
c = make_logged_in_client(username="test_home", groupname="test_home", recreate=True, is_superuser=False)
user = User.objects.get(username="test_home")
response = c.get(reverse(home))
assert sorted(["notmine", "trash", "mine", "history"]) == sorted(list(json.loads(response.context[0]['json_tags']).keys()))
assert 200 == response.status_code
from pig.models import PigScript
script, created = PigScript.objects.get_or_create(owner=user)
doc = Document.objects.link(script, owner=script.owner, name='test_home')
response = c.get(reverse(home))
assert str(doc.id) in json.loads(response.context[0]['json_documents'])
response = c.get(reverse(home))
tags = json.loads(response.context[0]['json_tags'])
assert [doc.id] == tags['mine'][0]['docs'], tags
assert [] == tags['trash']['docs'], tags
assert [] == tags['history']['docs'], tags
doc.send_to_trash()
response = c.get(reverse(home))
tags = json.loads(response.context[0]['json_tags'])
assert [] == tags['mine'][0]['docs'], tags
assert [doc.id] == tags['trash']['docs'], tags
assert [] == tags['history']['docs'], tags
doc.restore_from_trash()
response = c.get(reverse(home))
tags = json.loads(response.context[0]['json_tags'])
assert [doc.id] == tags['mine'][0]['docs'], tags
assert [] == tags['trash']['docs'], tags
assert [] == tags['history']['docs'], tags
doc.add_to_history()
response = c.get(reverse(home))
tags = json.loads(response.context[0]['json_tags'])
assert [] == tags['mine'][0]['docs'], tags
assert [] == tags['trash']['docs'], tags
assert [] == tags['history']['docs'], tags # We currently don't fetch [doc.id]
@pytest.mark.django_db
def test_skip_wizard():
pytest.skip("Skipping due to failures with pytest, investigation ongoing.")
c = make_logged_in_client() # is_superuser
response = c.get('/', follow=True)
assert ['admin_wizard.mako' in _template.filename for _template in response.templates], [
_template.filename for _template in response.templates
]
c.cookies['hueLandingPage'] = 'home'
response = c.get('/', follow=True)
assert ['home.mako' in _template.filename for _template in response.templates], [_template.filename for _template in response.templates]
c.cookies['hueLandingPage'] = ''
response = c.get('/', follow=True)
assert ['admin_wizard.mako' in _template.filename for _template in response.templates], [
_template.filename for _template in response.templates
]
c = make_logged_in_client(username="test_skip_wizard", password="test_skip_wizard", is_superuser=False)
response = c.get('/', follow=True)
assert ['home.mako' in _template.filename for _template in response.templates], [_template.filename for _template in response.templates]
c.cookies['hueLandingPage'] = 'home'
response = c.get('/', follow=True)
assert ['home.mako' in _template.filename for _template in response.templates], [_template.filename for _template in response.templates]
c.cookies['hueLandingPage'] = ''
response = c.get('/', follow=True)
assert ['home.mako' in _template.filename for _template in response.templates], [_template.filename for _template in response.templates]
@pytest.mark.django_db
def test_public_views():
c = Client()
for view in DJANGO_VIEW_AUTH_WHITELIST:
if view is serve:
url = reverse(view, kwargs={'path': 'desktop/art/favicon.ico'})
else:
url = reverse(view)
response = c.get(url)
assert 200 == response.status_code
def test_prometheus_view():
if not desktop.conf.ENABLE_PROMETHEUS.get():
pytest.skip("Skipping Test")
ALL_PROMETHEUS_METRICS = [
'django_http_requests_before_middlewares_total',
'django_http_responses_before_middlewares_total',
'django_http_requests_latency_including_middlewares_seconds',
'django_http_requests_unknown_latency_including_middlewares_total',
'django_http_requests_latency_seconds_by_view_method',
'django_http_requests_unknown_latency_total',
'django_http_ajax_requests_total',
'django_http_requests_total_by_method',
'django_http_requests_total_by_transport',
'django_http_requests_total_by_view_transport_method',
'django_http_requests_body_total_bytes',
'django_http_responses_total_by_templatename',
'django_http_responses_total_by_status',
'django_http_responses_body_total_bytes',
'django_http_responses_total_by_charset',
'django_http_responses_streaming_total',
'django_http_exceptions_total_by_type',
'django_http_exceptions_total_by_view',
]
c = Client()
response = c.get('/metrics')
for metric in ALL_PROMETHEUS_METRICS:
metric = metric if isinstance(metric, bytes) else metric.encode('utf-8')
if metric not in desktop.metrics.ALLOWED_DJANGO_PROMETHEUS_METRICS:
assert metric not in response.content, 'metric: %s \n %s' % (metric, response.content)
else:
assert metric in response.content, 'metric: %s \n %s' % (metric, response.content)
def hue_version():
global HUE_VERSION
HUE_VERSION_BAK = HUE_VERSION
try:
assert 'cdh6.x-SNAPSHOT' == _version_from_properties(
string_io(
"""# Autogenerated build properties
version=3.9.0-cdh5.9.0-SNAPSHOT
git.hash=f5fbe90b6a1d0c186b0ddc6e65ce5fc8d24725c8
cloudera.cdh.release=cdh6.x-SNAPSHOT
cloudera.hash=f5fbe90b6a1d0c186b0ddc6e65ce5fc8d24725c8aaaaa"""
)
)
assert not _version_from_properties(
string_io(
"""# Autogenerated build properties
version=3.9.0-cdh5.9.0-SNAPSHOT
git.hash=f5fbe90b6a1d0c186b0ddc6e65ce5fc8d24725c8
cloudera.hash=f5fbe90b6a1d0c186b0ddc6e65ce5fc8d24725c8aaaaa"""
)
)
assert not _version_from_properties(string_io(''))
finally:
HUE_VERSION = HUE_VERSION_BAK
@pytest.mark.django_db
def test_prefs():
c = make_logged_in_client()
# Get everything
response = c.get('/desktop/api2/user_preferences/')
assert {} == json.loads(response.content)['data']
# Set and get
response = c.post('/desktop/api2/user_preferences/foo', {'set': 'bar'})
assert 'bar' == json.loads(response.content)['data']['foo']
response = c.get('/desktop/api2/user_preferences/')
assert 'bar' == json.loads(response.content)['data']['foo']
# Reset (use post this time)
c.post('/desktop/api2/user_preferences/foo', {'set': 'baz'})
response = c.get('/desktop/api2/user_preferences/foo')
assert 'baz' == json.loads(response.content)['data']['foo']
# Check multiple values
c.post('/desktop/api2/user_preferences/elephant', {'set': 'room'})
response = c.get('/desktop/api2/user_preferences/')
assert "baz" in list(json.loads(response.content)['data'].values()), response.content
assert "room" in list(json.loads(response.content)['data'].values()), response.content
# Delete everything
c.post('/desktop/api2/user_preferences/elephant', {'delete': ''})
c.post('/desktop/api2/user_preferences/foo', {'delete': ''})
response = c.get('/desktop/api2/user_preferences/')
assert {} == json.loads(response.content)['data']
# Check non-existent value
response = c.get('/desktop/api2/user_preferences/doesNotExist')
assert None is json.loads(response.content)['data']
@pytest.mark.django_db
def test_status_bar():
"""
Subs out the status_bar_views registry with temporary examples.
Tests handling of errors on view functions.
"""
backup = views._status_bar_views
views._status_bar_views = []
c = make_logged_in_client()
views.register_status_bar_view(lambda _: HttpResponse("foo", status=200))
views.register_status_bar_view(lambda _: HttpResponse("bar"))
views.register_status_bar_view(lambda _: None)
def f(r):
raise Exception()
views.register_status_bar_view(f)
response = c.get("/desktop/status_bar")
assert b"foobar" == response.content
views._status_bar_views = backup
def test_paginator():
"""
Test that the paginator works with partial list.
"""
def assert_page(page, data, start, end):
assert page.object_list == data
assert page.start_index() == start
assert page.end_index() == end
# First page 1-20
obj = list(range(20))
pgn = Paginator(obj, per_page=20)
assert_page(pgn.page(1), obj, 1, 20)
# Handle extra data on first page (22 items on a 20-page)
obj = list(range(22))
pgn = Paginator(obj, per_page=20)
assert_page(pgn.page(1), list(range(20)), 1, 20)
# Handle total < len(obj). Only works for QuerySet.
obj = query.QuerySet()
obj._result_cache = list(range(10))
pgn = Paginator(obj, per_page=10)
assert_page(pgn.page(1), list(range(10)), 1, 10)
# Still works with a normal complete list
obj = list(range(25))
pgn = Paginator(obj, per_page=20)
assert_page(pgn.page(1), list(range(20)), 1, 20)
assert_page(pgn.page(2), list(range(20, 25)), 21, 25)
def test_truncating_model():
class TinyModel(TruncatingModel):
short_field = CharField(max_length=10)
non_string_field = SmallIntegerField()
a = TinyModel()
a.short_field = 'a' * 9 # One less than it's max length
assert a.short_field == 'a' * 9, 'Short-enough field does not get truncated'
a.short_field = 'a' * 11 # One more than it's max_length
assert a.short_field == 'a' * 10, 'Too-long field gets truncated'
a.non_string_field = 10**10
assert a.non_string_field == 10**10, 'non-string fields are not truncated'
def test_error_handling():
pytest.skip("Skipping Test")
restore_django_debug = desktop.conf.DJANGO_DEBUG_MODE.set_for_testing(False)
restore_500_debug = desktop.conf.HTTP_500_DEBUG_MODE.set_for_testing(False)
exc_msg = "error_raising_view: Test earráid handling"
def error_raising_view(request, *args, **kwargs):
raise Exception(exc_msg)
def popup_exception_view(request, *args, **kwargs):
raise PopupException(exc_msg, title="earráid", detail=exc_msg)
# Add an error view
error_url_pat = [re_path('^500_internal_error$', error_raising_view), re_path('^popup_exception$', popup_exception_view)]
desktop.urls.urlpatterns.extend(error_url_pat)
try:
def store_exc_info(*args, **kwargs):
pass
# Disable the test client's exception forwarding
c = make_logged_in_client()
c.store_exc_info = store_exc_info
response = c.get('/500_internal_error')
assert any(["500.mako" in _template.filename for _template in response.templates])
assert 'Thank you for your patience' in response.content
assert exc_msg not in response.content
# Now test the 500 handler with backtrace
desktop.conf.HTTP_500_DEBUG_MODE.set_for_testing(True)
response = c.get('/500_internal_error')
assert response.template.name == 'Technical 500 template'
assert exc_msg in response.content
# PopupException
response = c.get('/popup_exception')
assert any(["popup_error.mako" in _template.filename for _template in response.templates])
assert exc_msg in response.content
finally:
# Restore the world
for i in error_url_pat:
desktop.urls.urlpatterns.remove(i)
restore_django_debug()
restore_500_debug()
@pytest.mark.django_db
def test_desktop_permissions():
USERNAME = 'test_core_permissions'
GROUPNAME = 'default'
desktop.conf.REDIRECT_WHITELIST.set_for_testing(r'^\/.*$,^http:\/\/testserver\/.*$')
c = make_logged_in_client(USERNAME, groupname=GROUPNAME, recreate=True, is_superuser=False)
# Access to the basic works
assert 200 == c.get('/hue/accounts/login/', follow=True).status_code
assert 200 == c.get('/accounts/logout', follow=True).status_code
assert 200 == c.get('/home', follow=True).status_code
@pytest.mark.django_db
def test_app_permissions():
USERNAME = 'test_app_permissions'
GROUPNAME = 'impala_only'
resets = [
desktop.conf.REDIRECT_WHITELIST.set_for_testing(r'^\/.*$,^http:\/\/testserver\/.*$'),
HAS_SQL_ENABLED.set_for_testing(False),
ENABLE_ALL_INTERPRETERS.set_for_testing(True),
SHOW_NOTEBOOKS.set_for_testing(True)
]
try:
c = make_logged_in_client(USERNAME, groupname=GROUPNAME, recreate=True, is_superuser=False)
user = rewrite_user(User.objects.get(username=USERNAME))
# Reset all perms
GroupPermission.objects.filter(group__name=GROUPNAME).delete()
def check_app(status_code, app_name):
if app_name in DESKTOP_APPS:
assert status_code == c.get('/' + app_name, follow=True).status_code, 'status_code=%s app_name=%s' % (status_code, app_name)
# Access to nothing
check_app(401, 'beeswax')
check_app(401, 'hive')
check_app(401, 'impala')
check_app(401, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(401, 'oozie')
# Clean INTERPRETERS_CACHE before every get_apps() call to have dynamic interpreters value for test_user
# because every testcase below needs clean INTERPRETERS_CACHE value as ENABLE_ALL_INTERPRETERS is now false by default.
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'browser' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'dashboard' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'sdkapps' not in apps, apps
# Should always be enabled as it is a lib
grant_access(USERNAME, GROUPNAME, "beeswax")
# Add access to hive
grant_access(USERNAME, GROUPNAME, "hive")
check_app(200, 'beeswax')
check_app(200, 'hive')
check_app(401, 'impala')
check_app(401, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(401, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'browser' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'dashboard' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'sdkapps' not in apps, apps
# Add access to hbase
grant_access(USERNAME, GROUPNAME, "hbase")
check_app(200, 'beeswax')
check_app(200, 'hive')
check_app(401, 'impala')
check_app(200, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(401, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' not in apps.get('editor', {}).get('interpreter_names', []), apps
if 'hbase' not in desktop.conf.APP_BLACKLIST.get():
assert 'browser' in apps, apps
assert 'hbase' in apps['browser']['interpreter_names'], apps['browser']
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'scheduler' not in apps, apps
assert 'dashboard' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'sdkapps' not in apps, apps
# Reset all perms
GroupPermission.objects.filter(group__name=GROUPNAME).delete()
check_app(401, 'beeswax')
check_app(401, 'impala')
check_app(401, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(401, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'browser' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'dashboard' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'sdkapps' not in apps, apps
# Test only impala perm
grant_access(USERNAME, GROUPNAME, "impala")
check_app(401, 'beeswax')
check_app(200, 'impala')
check_app(401, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(401, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'browser' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'dashboard' not in apps, apps
assert 'scheduler' not in apps, apps
assert 'sdkapps' not in apps, apps
# Oozie Editor and Browser
grant_access(USERNAME, GROUPNAME, "oozie")
check_app(401, 'hive')
check_app(200, 'impala')
check_app(401, 'hbase')
check_app(401, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(200, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'scheduler' in apps, apps
assert 'browser' not in apps, apps # Actually should be true, but logic not implemented
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
grant_access(USERNAME, GROUPNAME, "pig")
check_app(401, 'hive')
check_app(200, 'impala')
check_app(401, 'hbase')
check_app(200, 'pig')
check_app(401, 'search')
check_app(401, 'spark')
check_app(200, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
if 'search' not in desktop.conf.APP_BLACKLIST.get():
grant_access(USERNAME, GROUPNAME, "search")
check_app(401, 'hive')
check_app(200, 'impala')
check_app(401, 'hbase')
check_app(200, 'pig')
check_app(200, 'search')
check_app(401, 'spark')
check_app(200, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' not in apps.get('editor', {}).get('interpreter_names', []), apps
if 'spark' not in desktop.conf.APP_BLACKLIST.get():
grant_access(USERNAME, GROUPNAME, "spark")
check_app(401, 'hive')
check_app(200, 'impala')
check_app(401, 'hbase')
check_app(200, 'pig')
check_app(200, 'search')
check_app(200, 'spark')
check_app(200, 'oozie')
notebook.conf.INTERPRETERS_CACHE = None
apps = ClusterConfig(user=user).get_apps()
assert 'hive' not in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'impala' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pig' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'solr' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'spark' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'pyspark' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'r' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'jar' in apps.get('editor', {}).get('interpreter_names', []), apps
assert 'py' in apps.get('editor', {}).get('interpreter_names', []), apps
finally:
for f in resets:
f()
notebook.conf.INTERPRETERS_CACHE = None
@pytest.mark.django_db
def test_404_handling():
pytest.skip("Skipping due to failures with pytest, investigation ongoing.")
view_name = '/the-view-that-is-not-there'
c = make_logged_in_client()
response = c.get(view_name)
assert any(['404.mako' in _template.filename for _template in response.templates]), response.templates
assert b'not found' in response.content
if not isinstance(view_name, bytes):
view_name = view_name.encode('utf-8')
assert view_name in response.content
class RecordingHandler(logging.Handler):
def __init__(self, *args, **kwargs):
logging.Handler.__init__(self, *args, **kwargs)
self.records = []
def emit(self, r):
self.records.append(r)
@pytest.mark.django_db
def test_log_event():
c = make_logged_in_client()
root = logging.getLogger("desktop.views.log_frontend_event")
handler = RecordingHandler()
root.addHandler(handler)
c.get("/desktop/log_frontend_event?level=info&message=foo")
assert "INFO" == handler.records[-1].levelname
assert "Untrusted log event from user test: foo" == handler.records[-1].message
assert "desktop.views.log_frontend_event" == handler.records[-1].name
c.get("/desktop/log_frontend_event?level=error&message=foo2")
assert "ERROR" == handler.records[-1].levelname
assert "Untrusted log event from user test: foo2" == handler.records[-1].message
c.get("/desktop/log_frontend_event?message=foo3")
assert "INFO" == handler.records[-1].levelname
assert "Untrusted log event from user test: foo3" == handler.records[-1].message
c.post("/desktop/log_frontend_event", {"message": "01234567" * 1024})
assert "INFO" == handler.records[-1].levelname
assert "Untrusted log event from user test: " == handler.records[-1].message
root.removeHandler(handler)
def test_validate_path():
with tempfile.NamedTemporaryFile() as local_file:
reset = desktop.conf.SSL_PRIVATE_KEY.set_for_testing(local_file.name)
assert [] == validate_path(desktop.conf.SSL_PRIVATE_KEY, is_dir=False)
reset()
try:
reset = desktop.conf.SSL_PRIVATE_KEY.set_for_testing('/tmm/does_not_exist')
assert [] != validate_path(desktop.conf.SSL_PRIVATE_KEY, is_dir=True)
assert False
except Exception as ex:
assert 'does not exist' in str(ex), ex
finally:
reset()
@pytest.mark.integration
@pytest.mark.requires_hadoop
@pytest.mark.django_db
def test_config_check():
with tempfile.NamedTemporaryFile() as cert_file:
with tempfile.NamedTemporaryFile() as key_file:
reset = (
desktop.conf.SECRET_KEY.set_for_testing(''),
desktop.conf.SECRET_KEY_SCRIPT.set_for_testing(present=False),
desktop.conf.SSL_CERTIFICATE.set_for_testing(cert_file.name),
desktop.conf.SSL_PRIVATE_KEY.set_for_testing(key_file.name),
desktop.conf.DEFAULT_SITE_ENCODING.set_for_testing('klingon'),
)
cli = make_logged_in_client()
try:
resp = cli.get('/desktop/debug/check_config')
assert 'Secret key should be configured' in resp.content, resp
assert 'klingon' in resp.content, resp
assert 'Encoding not supported' in resp.content, resp
finally:
for old_conf in reset:
old_conf()
prev_env_conf = os.environ.get("HUE_CONF_DIR")
try:
# Set HUE_CONF_DIR and make sure check_config returns appropriate conf
os.environ["HUE_CONF_DIR"] = "/tmp/test_hue_conf_dir"
def validate_by_spec(error_list):
pass
# Monkey patch as this will fail as the conf dir doesn't exist
if not hasattr(desktop.views, 'real_validate_by_spec'):
desktop.views.real_validate_by_spec = desktop.views.validate_by_spec
desktop.views.validate_by_spec = validate_by_spec
resp = cli.get('/desktop/debug/check_config')
assert '/tmp/test_hue_conf_dir' in resp.content, resp
finally:
if prev_env_conf is None:
os.environ.pop("HUE_CONF_DIR", None)
else:
os.environ["HUE_CONF_DIR"] = prev_env_conf
desktop.views.validate_by_spec = desktop.views.real_validate_by_spec
def test_last_access_time():
pytest.skip("Skipping Test")
c = make_logged_in_client(username="access_test")
c.post('/hue/accounts/login/')
login = desktop.auth.views.get_current_users()
before_access_time = time.time()
response = c.get('/home')
after_access_time = time.time()
access = desktop.auth.views.get_current_users()
user = response.context[0]['user']
login_time = login[user]['time']
access_time = access[user]['time']
# Check that 'last_access_time' is later than login time
assert login_time < access_time
# Check that 'last_access_time' is in between the timestamps before and after the last access path
assert before_access_time < access_time
assert access_time < after_access_time
@pytest.mark.django_db
def test_ui_customizations():
if desktop.conf.is_lb_enabled(): # Assumed that live cluster connects to direct Hue
custom_message = 'You are accessing a non-optimized Hue, please switch to one of the available addresses'
else:
custom_message = 'test ui customization'
reset = (
desktop.conf.CUSTOM.BANNER_TOP_HTML.set_for_testing(custom_message),
desktop.conf.CUSTOM.LOGIN_SPLASH_HTML.set_for_testing(custom_message),
)
try:
c = make_logged_in_client()
c.logout()
if not isinstance(custom_message, bytes):
custom_message = custom_message.encode('utf-8')
resp = c.get('/hue/accounts/login/', follow=False)
assert custom_message in resp.content, resp
resp = c.get('/hue/about', follow=True)
assert custom_message in resp.content, resp
finally:
for old_conf in reset:
old_conf()
@pytest.mark.integration
@pytest.mark.requires_hadoop
@pytest.mark.django_db
def test_check_config_ajax():
c = make_logged_in_client()
response = c.get(reverse(check_config))
content = response.content.decode('utf-8')
assert "misconfiguration" in response.content, response.content
def test_oracledb():
"""
Tests that oracledb (external dependency) is built correctly.
"""
if 'ORACLE_HOME' not in os.environ and 'ORACLE_INSTANTCLIENT_HOME' not in os.environ:
pytest.skip("Skipping Test")
try:
import oracledb
return
except ImportError as ex:
if "No module named" in ex.message:
assert (
False,
"oracledb skipped its build. This happens if "
"env var ORACLE_HOME or ORACLE_INSTANTCLIENT_HOME is not defined. "
"So ignore this test failure if your build does not need to work "
"with an oracle backend.",
)
@pytest.mark.django_db
class TestStrictRedirection(object):
def setup_method(self):
self.finish = desktop.conf.AUTH.BACKEND.set_for_testing(['desktop.auth.backend.AllowFirstUserDjangoBackend'])
self.client = make_logged_in_client()
self.user = dict(username="test", password="test")
desktop.conf.REDIRECT_WHITELIST.set_for_testing(r'^\/.*$,^http:\/\/example.com\/.*$')
def teardown_method(self):
self.finish()
def test_redirection_blocked(self):
# Redirection with code 301 should be handled properly
# Redirection with Status code 301 example reference: http://www.somacon.com/p145.php
self._test_redirection(redirection_url='http://www.somacon.com/color/html_css_table_border_styles.php', expected_status_code=403)
# Redirection with code 302 should be handled properly
self._test_redirection(redirection_url='http://www.google.com', expected_status_code=403)
def test_redirection_allowed(self):
# Redirection to the host where Hue is running should be OK.
self._test_redirection(redirection_url='/', expected_status_code=302)
self._test_redirection(redirection_url='/pig', expected_status_code=302)
self._test_redirection(redirection_url='http://testserver/', expected_status_code=302)
self._test_redirection(
redirection_url='https://testserver/',
expected_status_code=302,
**{
'SERVER_PORT': '443',
'wsgi.url_scheme': 'https',
},
)
self._test_redirection(redirection_url='http://example.com/', expected_status_code=302)
def _test_redirection(self, redirection_url, expected_status_code, **kwargs):
data = self.user.copy()
data['next'] = redirection_url
response = self.client.post('/hue/accounts/login/', data, **kwargs)
assert expected_status_code == response.status_code
if expected_status_code == 403:
error_msg = 'Redirect to ' + redirection_url + ' is not allowed.'
if not isinstance(error_msg, bytes):
error_msg = error_msg.encode('utf-8')
assert error_msg in response.content, response.content
class BaseTestPasswordConfig(object):
SCRIPT = '%s -c "print(\'\\n password from script \\n\')"' % sys.executable
def get_config_password(self):
raise NotImplementedError
def get_config_password_script(self):
raise NotImplementedError
def get_password(self):
raise NotImplementedError
def test_read_password_from_script(self):
self._run_test_read_password_from_script_with(present=False)
self._run_test_read_password_from_script_with(data=None)
self._run_test_read_password_from_script_with(data='')
def _run_test_read_password_from_script_with(self, **kwargs):
resets = [
self.get_config_password().set_for_testing(**kwargs),
self.get_config_password_script().set_for_testing(self.SCRIPT),
]
try:
assert self.get_password() == ' password from script ', 'pwd: %s, kwargs: %s' % (self.get_password(), kwargs)
finally:
for reset in resets:
reset()
def test_config_password_overrides_script_password(self):
resets = [
self.get_config_password().set_for_testing(' password from config '),
self.get_config_password_script().set_for_testing(self.SCRIPT),
]
try:
assert self.get_password() == ' password from config '
finally:
for reset in resets:
reset()
def test_password_script_raises_exception(self):
resets = [
self.get_config_password().set_for_testing(present=False),
self.get_config_password_script().set_for_testing('%s -c "import sys; sys.exit(1)"' % sys.executable),
]
try:
with pytest.raises(subprocess.CalledProcessError):
self.get_password()
finally:
for reset in resets:
reset()
resets = [
self.get_config_password().set_for_testing(present=False),
self.get_config_password_script().set_for_testing('/does-not-exist'),
]
try:
with pytest.raises(subprocess.CalledProcessError):
self.get_password()
finally:
for reset in resets:
reset()
class TestSecretKeyConfig(BaseTestPasswordConfig):
def get_config_password(self):
return desktop.conf.SECRET_KEY
def get_config_password_script(self):
return desktop.conf.SECRET_KEY_SCRIPT
def get_password(self):
return desktop.conf.get_secret_key()
class TestDatabasePasswordConfig(BaseTestPasswordConfig):
def get_config_password(self):
return desktop.conf.DATABASE.PASSWORD
def get_config_password_script(self):
return desktop.conf.DATABASE.PASSWORD_SCRIPT
def get_password(self):
return desktop.conf.get_database_password()
class TestLDAPPasswordConfig(BaseTestPasswordConfig):
def get_config_password(self):
return desktop.conf.AUTH_PASSWORD
def get_config_password_script(self):
return desktop.conf.AUTH_PASSWORD_SCRIPT
def get_password(self):
# We are using dynamic_default now, so we need to cheat for the tests as only using set_for_testing(present=False) will trigger it.
if desktop.conf.AUTH_PASSWORD.get():
return desktop.conf.AUTH_PASSWORD.get()
else:
return self.get_config_password_script().get()
@pytest.mark.django_db
class TestLDAPBindPasswordConfig(BaseTestPasswordConfig):
def setup_method(self):
self.finish = desktop.conf.LDAP.LDAP_SERVERS.set_for_testing({'test': {}})
def teardown_method(self):
self.finish()
def get_config_password(self):
return desktop.conf.LDAP.LDAP_SERVERS['test'].BIND_PASSWORD
def get_config_password_script(self):
return desktop.conf.LDAP.LDAP_SERVERS['test'].BIND_PASSWORD_SCRIPT
def get_password(self):
return desktop.conf.get_ldap_bind_password(desktop.conf.LDAP.LDAP_SERVERS['test'])
class TestSMTPPasswordConfig(BaseTestPasswordConfig):
def get_config_password(self):
return desktop.conf.SMTP.PASSWORD
def get_config_password_script(self):
return desktop.conf.SMTP.PASSWORD_SCRIPT
def get_password(self):
return desktop.conf.get_smtp_password()
@pytest.mark.django_db
class TestDocument(object):
def setup_method(self):
make_logged_in_client(username="original_owner", groupname="test_doc", recreate=True, is_superuser=False)