-
Notifications
You must be signed in to change notification settings - Fork 356
/
tests.py
3562 lines (2906 loc) · 146 KB
/
tests.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 cStringIO
import gzip
import json
import logging
import os
import random
import re
import shutil
import socket
import string
import tempfile
import threading
import hadoop
from nose.tools import assert_true, assert_equal, assert_false, assert_not_equal, assert_raises
from nose.plugins.skip import SkipTest
from django.utils.encoding import smart_str
from django.utils.html import escape
from django.contrib.auth.models import User
from django.urls import reverse
from django.db import transaction
from desktop.lib.exceptions_renderable import PopupException
from desktop.conf import \
AUTH_USERNAME as DEFAULT_AUTH_USERNAME, \
AUTH_PASSWORD as DEFAULT_AUTH_PASSWORD, \
AUTH_PASSWORD_SCRIPT as DEFAULT_AUTH_PASSWORD_SCRIPT, \
LDAP_USERNAME, \
LDAP_PASSWORD, \
USE_NEW_EDITOR
from desktop import redaction
from desktop.redaction import logfilter
from desktop.redaction.engine import RedactionPolicy, RedactionRule
from desktop.lib.django_test_util import make_logged_in_client, assert_equal_mod_whitespace
from desktop.lib.parameterization import substitute_variables
from desktop.lib.test_utils import grant_access, add_to_group
from desktop.lib.security_util import get_localhost_name
from desktop.lib.test_export_csvxls import _read_xls_sheet_data
from hadoop.fs.hadoopfs import Hdfs
from hadoop import ssl_client_site
from hadoop.pseudo_hdfs4 import is_live_cluster
import desktop.conf as desktop_conf
import beeswax.create_table
import beeswax.hive_site
import beeswax.models
import beeswax.views
from beeswax import conf, hive_site
from beeswax.common import apply_natural_sort
from beeswax.conf import HIVE_SERVER_HOST, AUTH_USERNAME, AUTH_PASSWORD, AUTH_PASSWORD_SCRIPT
from beeswax.views import collapse_whitespace, _save_design, parse_out_jobs
from beeswax.test_base import make_query, wait_for_query_to_finish, verify_history, get_query_server_config,\
fetch_query_result_data
from beeswax.design import hql_query, strip_trailing_semicolon
from beeswax.data_export import upload, download
from beeswax.models import SavedQuery, QueryHistory, HQL, HIVE_SERVER2
from beeswax.server import dbms
from beeswax.server.dbms import QueryServerException
from beeswax.server.hive_server2_lib import HiveServerClient,\
PartitionKeyCompatible, PartitionValueCompatible, HiveServerTable,\
HiveServerTColumnValue2
from beeswax.test_base import BeeswaxSampleProvider, is_hive_on_spark, get_available_execution_engines
from beeswax.hive_site import get_metastore, hiveserver2_jdbc_url
LOG = logging.getLogger(__name__)
def _list_dir_without_temp_files(fs, target_dir):
return [f for f in fs.listdir(target_dir) if not f.startswith('.')]
def _make_query(client, query, submission_type="Execute",
udfs=None, settings=None, resources=[],
wait=False, name=None, desc=None, local=True,
is_parameterized=True, max=30.0, database='default', email_notify=False, params=None, server_name='beeswax', **kwargs):
res = make_query(client, query, submission_type,
udfs, settings, resources,
wait, name, desc, local, is_parameterized, max, database, email_notify, params, server_name, **kwargs)
# Should be in the history if it's submitted.
if submission_type == 'Execute':
if is_parameterized and params:
query = substitute_variables(query, dict(params))
fragment = collapse_whitespace(smart_str(escape(query[:20])))
verify_history(client, fragment=fragment, server_name=server_name)
return res
def random_generator(size=8, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def get_csv(client, result_response):
"""Get the csv for a query result"""
content = json.loads(result_response.content)
assert_true(content['isSuccess'])
csv_link = '/beeswax/download/%s/csv' % content['id']
csv_resp = client.get(csv_link)
return ''.join(csv_resp.streaming_content)
class TestBeeswaxWithHadoop(BeeswaxSampleProvider):
requires_hadoop = True
def setUp(self):
self.user = User.objects.get(username='test')
add_to_group('test')
self.db = dbms.get(self.user, get_query_server_config())
self.cluster.fs.do_as_user('test', self.cluster.fs.create_home_dir, '/user/test')
def _verify_query_state(self, state, *extra_states):
"""
Verify the state of the latest query.
Return the id of that query
"""
resp = self.client.get('/beeswax/query_history')
history = resp.context[0]['page'].object_list[0]
last_state = history.last_state
assert_true(last_state in (state,) + extra_states)
return history.id
def test_query_with_error(self):
# Creating a table "again" should not work; error should be displayed.
response = _make_query(self.client, "CREATE TABLE test (foo INT)", database=self.db_name, wait=True)
content = json.loads(response.content)
assert_true("AlreadyExistsException" in content.get('message'), content)
def test_query_with_resource(self):
udf = self.cluster.fs_prefix + "/square.py"
script = self.cluster.fs.open(udf, "w")
script.write(
"""#!/usr/bin/python
import sys
for x in sys.stdin:
val = int(x)
print val*val
""")
script.close()
response = _make_query(self.client,
"SELECT TRANSFORM (foo) USING 'python square.py' AS b FROM test",
resources=[("FILE", udf)], local=False, database=self.db_name)
response = wait_for_query_to_finish(self.client, response, max=180.0)
content = fetch_query_result_data(self.client, response)
assert_equal([['0'], ['1'], ['4'], ['9']], content["results"][0:4])
def test_query_with_setting(self):
table_name = 'test_query_with_setting'
response = _make_query(self.client, "CREATE TABLE `%(db)s`.`%(table_name)s` AS SELECT foo+1 FROM test WHERE foo=4" % {'db': self.db_name, 'table_name': table_name},
settings=[("mapred.job.name", "test_query_with_setting"),
("hive.exec.compress.output", "true")], local=False, database=self.db_name) # Run on MR, because that's how we check it worked.
response = wait_for_query_to_finish(self.client, response, max=180.0)
# Check that we actually got a compressed output
table = self.db.get_table(database=self.db_name, table_name=table_name)
hdfs_loc = Hdfs.urlsplit(table.path_location)
files = self.cluster.fs.listdir(hdfs_loc[2])
assert_true(len(files) >= 1, files)
assert_true(files[0].endswith(".deflate"), files[0])
raise SkipTest
# And check that the name is right...
assert_true("test_query_with_setting" in [ x.profile.name for x in self.cluster.jt.all_jobs().jobs ])
# While we're at it, check that we're running jobs as the correct user on MR.
assert_equal("test",
[ x.profile for x in self.cluster.jt.all_jobs().jobs
if x.profile.name == "test_query_with_setting" ][0].user)
def test_lazy_query_status_update(self):
QUERY = """
SELECT MIN(foo), MAX(foo), SUM(foo) FROM test;
"""
wait_for_query_to_finish(self.client, _make_query(self.client, QUERY, local=False, database=self.db_name), max=180.0)
self._verify_query_state(beeswax.models.QueryHistory.STATE.available.value)
# Make sure expired query states are lazily updated.
resp = self.client.get('/beeswax/query_history')
history = resp.context[0]['page'].object_list[0]
self.db.close_operation(history.get_full_object().get_handle())
resp = self.client.get("/beeswax/execute/query/%s" % history.id)
assert_true(resp.status_code, 302)
resp = self.client.get('/beeswax/query_history')
history = resp.context[0]['page'].object_list[0]
assert_equal(history.last_state, beeswax.models.QueryHistory.STATE.expired.value)
def test_basic_flow(self):
# Minimal server operation
databases = self.db.get_databases()
assert_true('default' in databases, databases)
assert_true(self.db_name in databases, databases)
assert_true('%s_other' % self.db_name in databases, databases)
# Use GROUP BY to trigger MR job
QUERY = """
SELECT MIN(foo), MAX(foo), SUM(foo) FROM test;
"""
response = _make_query(self.client, QUERY, local=False, database=self.db_name)
content = json.loads(response.content)
assert_true('watch_url' in content)
# Check that we report this query as "running" (this query should take a little while).
if not is_hive_on_spark():
self._verify_query_state(beeswax.models.QueryHistory.STATE.running.value, beeswax.models.QueryHistory.STATE.available.value)
response = wait_for_query_to_finish(self.client, response, max=180.0)
content = fetch_query_result_data(self.client, response)
assert_equal([0, 255, 32640], content["results"][0], content["results"][0])
assert_equal(['INT_TYPE', 'INT_TYPE', 'BIGINT_TYPE'], [col['type'] for col in content["columns"]])
self._verify_query_state(beeswax.models.QueryHistory.STATE.available.value)
# Query multi-page request
QUERY = """
SELECT * FROM test
"""
response = _make_query(self.client, QUERY, name='select star', local=False, database=self.db_name)
response = wait_for_query_to_finish(self.client, response)
content = fetch_query_result_data(self.client, response)
assert_true([99, u'0x63'] in content['results'], content['results'])
assert_true(content["has_more"])
response = self.client.get("/beeswax/results/%s/%s?format=json" % (content["id"], content["next_row"]))
content = json.loads(response.content)
assert_true([199, u'0xc7'] in content['results'], content['results'])
response = self.client.get("/beeswax/results/%s/0?format=json" % (content["id"]))
content = json.loads(response.content)
assert_true([99, u'0x63'] in content['results'])
assert_equal(0, len(content["hadoop_jobs"]), "SELECT * shouldn't have started jobs.")
# Download the data
response = self.client.get(content["download_urls"]["csv"])
# Header line plus data lines...
assert_equal(257, ''.join(response.streaming_content).count("\n"))
def test_api_get_session(self):
session = None
try:
# Create open session
session = self.db.open_session(self.user)
resp = self.client.get(reverse("beeswax:api_get_session"))
data = json.loads(resp.content)
assert_true('properties' in data, data)
assert_true('session' in data, data)
assert_true('id' in data['session'], data['session'])
finally:
if session is not None:
try:
self.db.close_session(session)
except Exception:
pass
def test_api_close_session(self):
session = None
try:
# Create open session
session = self.db.open_session(self.user)
resp = self.client.post(reverse("beeswax:api_close_session", kwargs={'session_id': session.id}))
data = json.loads(resp.content)
assert_equal(0, data['status'])
assert_true('session' in data)
assert_equal(4, data['session']['status'])
# Closed sessions will return error response
resp = self.client.post(reverse("beeswax:api_close_session", kwargs={'session_id': session.id}))
data = json.loads(resp.content)
assert_equal(-1, data['status'])
finally:
if session is not None:
try:
self.db.close_session(session)
except Exception:
pass
def test_result_escaping(self):
# Check for XSS and NULL display
QUERY = """
SELECT 'abc', 1.0, 1=1, 1, 1/0, '<a>lala</a>lulu', 'some spaces' from test LIMIT 3;
"""
response = _make_query(self.client, QUERY, local=False, database=self.db_name)
content = json.loads(response.content)
assert_true('watch_url' in content)
response = wait_for_query_to_finish(self.client, response, max=180.0)
content = fetch_query_result_data(self.client, response)
assert_equal([
[u'abc', 1.0, True, 1, u'NULL', u'<a>lala</a>lulu', 'some spaces'],
[u'abc', 1.0, True, 1, u'NULL', u'<a>lala</a>lulu', 'some spaces'],
[u'abc', 1.0, True, 1, u'NULL', u'<a>lala</a>lulu', 'some spaces'],
], content["results"], content)
def test_result_nullification(self):
QUERY = """
CREATE TABLE test_result_nullification (a int);
INSERT INTO TABLE test_result_nullification
VALUES
(1), (1), (1), (1), (1), (1), (1), (1),
(2), (2), (2), (2), (2), (2), (2), (2),
(NULL), (3), (3), (3), (3), (3), (3), (3),
(4), (4), (4), (4), (4), (4), (4), (4),
(5), (5), (5), (5), (5), (5), (5), (5),
(6), (6), (6), (6), (6), (6), (6), (6);
"""
response = _make_query(self.client, QUERY, local=False, database=self.db_name)
content = json.loads(response.content)
assert_true('watch_url' in content)
response = wait_for_query_to_finish(self.client, response, max=180.0)
content = fetch_query_result_data(self.client, response)
QUERY = """
SELECT * FROM test_result_nullification;
"""
response = _make_query(self.client, QUERY, local=False, database=self.db_name)
content = json.loads(response.content)
assert_true('watch_url' in content)
response = wait_for_query_to_finish(self.client, response, max=180.0)
content = fetch_query_result_data(self.client, response)
assert_equal([
[1], [1], [1], [1], [1], [1], [1], [1],
[2], [2], [2], [2], [2], [2], [2], [2],
[u'NULL'], [3], [3], [3], [3], [3], [3], [3],
[4], [4], [4], [4], [4], [4], [4], [4],
[5], [5], [5], [5], [5], [5], [5], [5],
[6], [6], [6], [6], [6], [6], [6], [6]
], content["results"], content)
def test_query_with_udf(self):
"""
Testing query with udf
"""
execution_engines = get_available_execution_engines()
for engine in execution_engines:
response = _make_query(self.client, "SELECT my_sqrt(foo), my_float(foo) FROM test where foo=4 GROUP BY foo", # Force MR job with GROUP BY
udfs=[('my_sqrt', 'org.apache.hadoop.hive.ql.udf.UDFSqrt'),
('my_float', 'org.apache.hadoop.hive.ql.udf.UDFToFloat')],
local=False, database=self.db_name, settings=[('hive.execution.engine', engine)])
response = wait_for_query_to_finish(self.client, response, max=60.0)
content = fetch_query_result_data(self.client, response)
assert_equal([2.0, 4.0], content["results"][0])
log = content['log']
assert_true(search_log_line('Completed executing command', log), log)
# Test job extraction while we're at it
assert_equal(1, len(parse_out_jobs(log, engine)), "Should have started 1 job and extracted it.")
def test_query_with_remote_udf(self):
"""
UDF is on HDFS. This was implemented as part of HIVE-1157.
"""
# BeeswaxTest.jar is gone
raise SkipTest
src = file(os.path.join(os.path.dirname(__file__), "..", "..", "java-lib", "BeeswaxTest.jar"))
udf = self.cluster.fs_prefix + "hive1157.jar"
dest = self.cluster.fs.open(udf, "w")
shutil.copyfileobj(src, dest)
dest.close()
src.close()
# Beware that this doesn't work with mapred.job.tracker=local :/
response = _make_query(self.client, "SELECT cube(foo) FROM test WHERE foo=4",
udfs=[('cube', 'com.cloudera.beeswax.CubeSampleUDF')],
resources=[('JAR', udf)], local=False, database=self.db_name)
response = wait_for_query_to_finish(self.client, response, max=60.0)
assert_equal(["64"], response.context[0]["results"][0])
def test_query_with_simple_errors(self):
hql = "SELECT KITTENS ARE TASTY"
resp = _make_query(self.client, hql, name='tasty kittens', wait=False, local=False, database=self.db_name)
assert_true("ParseException line" in json.loads(resp.content)["message"])
# Watch page will fail as operationHandle=None
self._verify_query_state(beeswax.models.QueryHistory.STATE.failed.value)
def test_sync_query_exec(self):
# Execute Query Synchronously, set fetch size and fetch results
# verify the size of resultset,
hql = """
SELECT foo FROM `%(db)s`.`test`;
""" % {'db': self.db_name}
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
results = self.db.fetch(handle, True, 5)
row_list = list(results.rows())
assert_equal(len(row_list), 5)
self.db.close(handle)
def test_sync_query_error(self):
# We don't use synchronous queries anywhere.
# It used to call BeeswaxService.executeAndWait()
raise SkipTest
# Execute incorrect Query , verify the error code and sqlstate
hql = """
SELECT FROM `%(db)s`.`zzzzz`
""" % {'db': self.db_name}
query = hql_query(hql)
try:
self.db.execute_and_wait(query)
except QueryServerException, bex:
assert_equal(bex.errorCode, 40000)
assert_equal(bex.SQLState, "42000")
def test_fetch_configuration(self):
class MockClient:
"""Check if sent fetch correctly supports start_over."""
def __init__(self, support_start_over):
self.support_start_over = support_start_over
def fetch(self, query_id, start_over, fetch_size):
assert_equal(self.support_start_over, start_over)
class Result: pass
res = Result()
res.ready = False
return res
class ConfigVariable:
def __init__(self, **entries):
self.__dict__.update(entries)
client = self.db
prev_get_default_configuration = client.get_default_configuration
prev_client = client.client
try:
client.client = MockClient(True)
client.get_default_configuration = lambda a: []
client.fetch(None, True, 5)
client.client = MockClient(False)
client.get_default_configuration = lambda a: []
client.fetch(None, False, 5)
client.client = MockClient(True)
client.get_default_configuration = lambda a: [ConfigVariable(key='support_start_over', value='true')]
client.fetch(None, True, 5)
client.client = MockClient(False)
client.get_default_configuration = lambda a: [ConfigVariable(key='support_start_over', value='false')]
client.fetch(None, True, 5)
finally:
client.get_default_configuration = prev_get_default_configuration
client.client = prev_client
def test_parameterization(self):
#@TODO@ Prakash fix this test
raise SkipTest
response = _make_query(self.client, "SELECT foo FROM test WHERE foo='$x' and bar='$y'", is_parameterized=False, database=self.db_name)
content = json.loads(response.content)
# Assert no parameterization was offered
assert_true('watch_url' in content, content)
data = {
'query-query': "SELECT foo FROM test WHERE foo='$x' and bar='$y'",
'query-database': self.db_name
}
response = self.client.post(reverse('beeswax:api_parameters'), data)
content = json.loads(response.content)
assert_equal([
{'parameter': 'parameterization-x', 'name': 'x'},
{'parameter': 'parameterization-y', 'name': 'y'}
], content['parameters'], content)
# Now fill it out
response = _make_query(self.client, "SELECT foo FROM test WHERE foo='$x' and bar='$y'", params=[('x', '1'), ('y', '2')], database=self.db_name)
content = json.loads(response.content)
assert_true('watch_url' in content, content)
query_history = QueryHistory.get(content['id'])
# Check that substitution happened!
assert_equal("SELECT foo FROM test WHERE foo='1' and bar='2'", query_history.query)
# Check that error handling is reasonable
response = _make_query(self.client, "SELECT foo FROM test WHERE foo='$x' and bar='$y'", params=[('x', "'_this_is_not SQL "), ('y', '2')], database=self.db_name)
content = json.loads(response.content)
assert_true("FAILED: ParseException" in content.get('message'), content)
# Check multi DB with a non default DB
other_db = '%s_other' % self.db_name
response = _make_query(self.client, "CREATE TABLE test (foo INT, bar STRING)", database=other_db)
response = wait_for_query_to_finish(self.client, response)
response = _make_query(self.client, "SELECT foo FROM test WHERE foo='$x' and bar='$y'", database=other_db)
response = _make_query(self.client, "SELECT foo FROM test WHERE foo='$x' and bar='$y'", database=other_db,
params=[('x', '1'), ('y', '2')])
content = json.loads(response.content)
assert_true('watch_url' in content, content)
query_history = QueryHistory.get(content['id'])
assert_equal(other_db, query_history.design.get_design().query['database'])
def test_explain_query(self):
c = self.client
response = _make_query(c, "SELECT KITTENS ARE TASTY", submission_type="Explain", database=self.db_name)
assert_true("ParseException line" in json.loads(response.content)["message"])
CREATE_TABLE = "CREATE TABLE `%(db)s`.`test_explain` (foo INT, bar STRING);" % {'db': self.db_name}
response = _make_query(c, CREATE_TABLE, database=self.db_name)
wait_for_query_to_finish(c, response)
response = _make_query(c, "SELECT SUM(foo) FROM `%(db)s`.`test_explain`" % {'db': self.db_name}, settings=[('hive.explain.user', 'false')], submission_type="Explain") # Need to prefix database in Explain
explanation = json.loads(response.content)['explanation']
assert_true('STAGE DEPENDENCIES:' in explanation, explanation)
assert_true('STAGE PLANS:' in explanation, explanation)
def test_explain_query_i18n(self):
if is_live_cluster():
raise SkipTest('HUE-2884: Skipping test because we cannot guarantee live cluster supports utf8')
query = u"SELECT foo FROM `%(db)s`.`test_utf8` WHERE bar='%(val)s'" % {'val': unichr(200), 'db': self.db_name}
response = _make_query(self.client, query, settings=[('hive.explain.user', 'false')], submission_type="Explain")
explanation = json.loads(response.content)['explanation']
assert_true('STAGE DEPENDENCIES:' in explanation, explanation)
assert_true('STAGE PLANS:' in explanation, explanation)
def test_query_i18n(self):
# Test fails because HIVE_PLAN cannot be found and raises FileNotFoundException
# because of a Hive bug.
raise SkipTest
# Selecting from utf-8 table should get correct result
query = u"SELECT * FROM `%(db)s`.`test_utf8` WHERE bar='%(val)s'" % {'val': unichr(200), 'db': self.db_name}
response = _make_query(self.client, query, wait=True, database=self.db_name)
assert_equal(["200", unichr(200)], response.context[0]["results"][0], "selecting from utf-8 table should get correct result")
csv = get_csv(self.client, response)
assert_equal('"200","%s"' % (unichr(200).encode('utf-8'),), csv.split()[1])
# Selecting from latin1 table should not blow up
query = u"SELECT * FROM `%(db)s`.`test_latin1` WHERE bar='%(val)s'" % {'val': unichr(200), 'db': self.db_name}
response = _make_query(self.client, query, wait=True, database=self.db_name)
assert_true('results' in response.context, "selecting from latin1 table should not blow up")
# Describe table should be fine with non-ascii comment
response = self.client.get('/beeswax/table/%(db)s/test_utf8' % {'db': self.db_name})
assert_equal(response.context[0]['table'].parameters['comment'], self.get_i18n_table_comment())
def _parallel_query_helper(self, i, result_holder, lock, num_tasks):
client = make_logged_in_client()
try:
q = "SELECT foo+" + str(i + 1) + " FROM test WHERE foo < 2"
LOG.info("Starting " + str(i) + ": " + q)
response = _make_query(client, q, local=False)
response = wait_for_query_to_finish(client, response, max=(240.0 * num_tasks))
lock.acquire()
result_holder[i] = response
lock.release()
LOG.info("Finished: " + str(i))
except Exception, e:
LOG.exception("Saw exception in child thread: %s" % e)
def test_multiple_statements_no_result_set(self):
hql = """
CREATE TABLE test_multiple_statements_1 (a int);
CREATE TABLE test_multiple_statements_2 (a int);
DROP TABLE test_multiple_statements_1;
DROP TABLE test_multiple_statements_2;
"""
resp = _make_query(self.client, hql, database=self.db_name)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = json.loads(resp.content)
history_id = content['id']
query_history = QueryHistory.get(id=history_id)
resp = self.client.get("/beeswax/results/%s/0?format=json" % history_id)
content = json.loads(resp.content)
assert_equal('DROP TABLE test_multiple_statements_2', query_history.get_current_statement(), content)
def test_multiple_statements_with_result_set(self):
hql = """
SELECT foo FROM test;
SELECT count(*) FROM test;
"""
resp = _make_query(self.client, hql, database=self.db_name)
content = json.loads(resp.content)
assert_true('watch_url' in content, content)
watch_url = content['watch_url']
assert_equal('SELECT foo FROM test', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = fetch_query_result_data(self.client, resp)
assert_false(content.get('is_finished'), content)
resp = self.client.post(watch_url, {'next': True})
content = json.loads(resp.content)
assert_equal('SELECT count(*) FROM test', content.get('statement'), content)
def test_multiple_statements_various_queries(self):
hql = """
CREATE TABLE test_multiple_statements_2 (a int);
DROP TABLE test_multiple_statements_2;
SELECT foo FROM test;
"""
resp = _make_query(self.client, hql, database=self.db_name)
content = json.loads(resp.content)
assert_equal('CREATE TABLE test_multiple_statements_2 (a int)', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = json.loads(resp.content)
assert_equal('SELECT foo FROM test', content.get('statement'), content)
content = fetch_query_result_data(self.client, resp)
assert_true(content.get('is_finished'), content)
def test_multiple_statements_with_next_button(self):
hql = """
show tables;
select * from test
"""
resp = _make_query(self.client, hql, database=self.db_name)
# First statement
content = json.loads(resp.content)
watch_url = content['watch_url']
assert_equal('show tables', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = fetch_query_result_data(self.client, resp)
assert_true([u'test'] in content.get('results'), content)
# Next statement
resp = self.client.post(watch_url, {'next': True, 'query-query': hql})
content = json.loads(resp.content)
assert_equal('select * from test', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = fetch_query_result_data(self.client, resp)
assert_true([0, u'0x0'] in content.get('results'), content)
def test_multiple_statements_with_params(self):
#@TODO@ Prakash fix this test
raise SkipTest
hql = """
select ${x} from test;
select ${y} from test;
"""
resp = _make_query(self.client, hql, params=[('x', '1'), ('y', '2')], database=self.db_name)
# First statement
content = json.loads(resp.content)
watch_url = content['watch_url']
assert_equal('select ${x} from test', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
content = fetch_query_result_data(self.client, resp)
# Next statement
resp = self.client.post(watch_url, {'next': True, 'query-query': hql})
content = json.loads(resp.content)
assert_equal('select ${y} from test', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
def test_multiple_statements_with_error(self):
hql = """
show tables;
select * from
"""
resp = _make_query(self.client, hql, database=self.db_name)
content = json.loads(resp.content)
watch_url = content['watch_url']
assert_equal('show tables', content.get('statement'), content)
resp = wait_for_query_to_finish(self.client, resp, max=30.0)
resp = self.client.post(watch_url, {'next': True, 'query-query': hql})
content = json.loads(resp.content)
assert_true('Error while compiling statement' in content.get('message'), content)
hql = """
show tables;
select * from test
"""
# Retry where we were with the statement fixed
resp = self.client.post(watch_url, {'next': True, 'query-query': hql})
content = json.loads(resp.content)
assert_equal('select * from test', content.get('statement'), content)
def test_parallel_queries(self):
"""
Test that we can issue two queries to the BeeswaxServer in parallel.
However, the test assertion has been plagued by the django test framework,
which does not set request.context in a thread safe manner.
So we check the results by looking at the csv files.
"""
raise SkipTest # sqlite does not support concurrent transaction
PARALLEL_TASKS = 2
responses = [ None ] * PARALLEL_TASKS
threads = []
# Protects responses
lock = threading.Lock()
for i in range(PARALLEL_TASKS):
t = threading.Thread(target=self._parallel_query_helper,
args=(i, responses, lock, PARALLEL_TASKS))
t.start()
threads.append(t)
for t in threads:
t.join()
# Commit transactions to be sure that QueryHistory up to date
transaction.commit()
for i in range(PARALLEL_TASKS):
csv = get_csv(self.client, responses[i])
# We get 3 rows: Column header, and 2 rows of results in double quotes
answer = [ int(data.strip('"')) for data in csv.split()[1:] ]
assert_equal( [ i + 1, i + 2 ], answer)
def test_data_export_limit_clause(self):
limit = 3
hql = 'SELECT foo FROM `%(db)s`.`test` limit %(limit)d' % {'limit': limit, 'db': self.db_name}
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
# Get the result in csv. Should have 3 + 1 header row.
csv_resp = download(handle, 'csv', self.db)
csv_content = ''.join(csv_resp.streaming_content)
assert_equal(len(csv_content.strip().split('\n')), limit + 1)
def test_query_done_cb(self):
hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
query = hql_query(hql)
query._data_dict['query']['email_notify'] = False
query_history = self.db.execute_and_watch(query)
response = self.client.get('/beeswax/query_cb/done/%s' % query_history.server_id)
assert_true('email_notify is false' in response.content, response.content)
query = hql_query(hql)
query._data_dict['query']['email_notify'] = True
query_history = self.db.execute_and_watch(query)
response = self.client.get('/beeswax/query_cb/done/%s' % query_history.server_id,)
assert_true('sent' in response.content, response.content)
response = self.client.get('/beeswax/query_cb/done/blahblahblah')
assert_true('QueryHistory matching query does not exist' in response.content, response.content)
def test_data_export(self):
hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
query = hql_query(hql)
# Get the result in xls.
handle = self.db.execute_and_wait(query)
resp = download(handle, 'xls', self.db)
sheet_data = _read_xls_sheet_data(resp)
num_cols = len(sheet_data[0])
# It should have 257 lines (256 + header)
assert_equal(len(sheet_data), 257, sheet_data)
# Get the result in csv.
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
resp = download(handle, 'csv', self.db)
csv_resp = ''.join(resp.streaming_content)
csv_data = [[int(col) if col.isdigit() else col for col in row.split(',')] for row in csv_resp.strip().split('\r\n')]
assert_equal(sheet_data, csv_data)
# Test max cell limit truncation
finish = conf.DOWNLOAD_ROW_LIMIT.set_for_testing(5)
try:
hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
resp = download(handle, 'xls', self.db)
sheet_data = _read_xls_sheet_data(resp)
# It should have 5 lines
assert_equal(len(sheet_data), 5, sheet_data)
finally:
finish()
finish = conf.DOWNLOAD_BYTES_LIMIT.set_for_testing(1024)
try:
hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
resp = download(handle, 'csv', self.db)
content = "".join(resp.streaming_content)
assert_true(len(content) <= 1024)
finally:
finish()
def test_data_upload(self):
hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
query = hql_query(hql)
handle = self.db.execute_and_wait(query)
csv_file = self.cluster.fs_prefix + '/test_data_upload.csv'
upload(csv_file, handle, self.user, self.db, self.cluster.fs)
assert_true(self.cluster.fs.exists(csv_file))
def test_designs(self):
#@TODO@ Prakash fix this test
raise SkipTest
if is_live_cluster():
raise SkipTest('HUE-2902: Skipping because test is not reentrant')
cli = self.client
# An auto hql design should be created, and it should ignore the given name and desc
_make_query(self.client, 'SELECT bogus FROM test', name='mydesign', desc='hyatt', database=self.db_name)
resp = cli.get('/beeswax/list_designs')
n_designs = len(resp.context[0]['page'].object_list)
# Retrieve that design. It's the first one since it's most recent
design = beeswax.models.SavedQuery.objects.all()[0]
resp = cli.get('/beeswax/execute/design/%s' % design.id)
assert_true('query' in resp.context[0]._data, resp.context)
assert_equal(design, resp.context[0]._data['design'], resp.context)
# Retrieve that query history. It's the first one since it's most recent
query_history = beeswax.models.QueryHistory.objects.all()[0]
resp = cli.get('/beeswax/execute/query/%s' % query_history.id)
assert_true('query' in resp.context[0]._data, resp.context)
assert_true(resp.context[0]._data['query'] is not None, resp.context)
assert_true('design' in resp.context[0]._data, resp.context)
assert_true(resp.context[0]._data['design'] is not None, resp.context)
resp = cli.get(reverse('beeswax:api_fetch_saved_design', kwargs={'design_id': design.id}))
content = json.loads(resp.content)
assert_true('SELECT bogus FROM test' in content['design']['query'], content)
# Make a valid auto hql design
resp = _make_query(self.client, 'SELECT * FROM test', database=self.db_name)
wait_for_query_to_finish(self.client, resp, max=60.0)
resp = cli.get('/beeswax/list_designs')
nplus_designs = len(resp.context[0]._data['page'].object_list)
assert_true(nplus_designs == n_designs, 'Auto design should not show up in list_designs')
# Test explicit save and use another DB
query = 'MORE BOGUS JUNKS FROM test'
other_db = '%s_other' % self.db_name
resp = _make_query(self.client, query, name='rubbish', submission_type='Save', database=other_db)
content = json.loads(resp.content)
assert_equal(0, content['status'])
assert_true('design_id' in content, content)
resp = cli.get('/beeswax/list_designs')
assert_true('rubbish' in resp.content, resp.content)
nplusplus_designs = len(resp.context[0]._data['page'].object_list)
assert_true(nplusplus_designs > nplus_designs)
# Retrieve that design and check correct DB is selected
design = beeswax.models.SavedQuery.objects.filter(name='rubbish')[0]
resp = cli.get(reverse('beeswax:api_fetch_saved_design', kwargs={'design_id': design.id}))
content = json.loads(resp.content)
assert_true(query in content['design']['query'], content)
assert_equal('', content['design']['desc'], content)
assert_equal(other_db, content['design']['database'], content)
# Clone the rubbish design
len_before = len(beeswax.models.SavedQuery.objects.filter(name__contains='rubbish'))
resp = cli.get('/beeswax/clone_design/%s' % (design.id,))
len_after = len(beeswax.models.SavedQuery.objects.filter(name__contains='rubbish'))
assert_equal(len_before + 1, len_after)
# Make 3 more designs
resp = cli.get('/beeswax/clone_design/%s' % (design.id,))
resp = cli.get('/beeswax/clone_design/%s' % (design.id,))
resp = cli.get('/beeswax/clone_design/%s' % (design.id,))
designs = beeswax.models.SavedQuery.objects.filter(name__contains='rubbish')[:3]
# Delete a design
resp = cli.get('/beeswax/delete_designs')
assert_true('Delete design(s)' in resp.content, resp.content)
resp = cli.post('/beeswax/delete_designs', {u'designs_selection': [design.id]})
assert_equal(resp.status_code, 302)
# Delete designs
design_ids = map(str, designs.values_list('id', flat=True))
resp = cli.get('/beeswax/delete_designs', {u'designs_selection': design_ids})
assert_true('Delete design(s)' in resp.content, resp.content)
#@TODO@: Prakash fix this test
#resp = cli.post('/beeswax/delete_designs', {u'designs_selection': design_ids})
#assert_equal(resp.status_code, 302)
# Helper to test the view, filtering, etc
def do_view(param):
resp = cli.get('/beeswax/list_designs?' + param)
assert_true(len(resp.context[0]['page'].object_list) >= 0) # Make the query run
return resp
do_view('user=test')
do_view('text=whatever')
do_view('type=hql')
do_view('sort=date')
do_view('sort=-date')
do_view('sort=name')
do_view('sort=-name')
do_view('sort=desc')
do_view('sort=-desc')
do_view('sort=type')
do_view('sort=-type')
do_view('sort=name&user=bogus')
resp = do_view('sort=-type&user=test&type=hql&text=Rubbish')
assert_true('rubbish' in resp.content)
# Test personal saved queries permissions
client_me = make_logged_in_client(username='its_me', is_superuser=False, groupname='test')
grant_access("its_me", "test", "beeswax")
_make_query(client_me, "select one", name='client query 1', submission_type='Save')
_make_query(client_me, "select two", name='client query 2', submission_type='Save')
# TODO in HUE-1589
raise SkipTest
finish = conf.SHARE_SAVED_QUERIES.set_for_testing(True)
try:
resp = client_me.get('/beeswax/list_designs')
assert_true('client query 1' in resp.content, resp.content)
assert_true('client query 2' in resp.content, resp.content)
finally:
finish()
finish = conf.SHARE_SAVED_QUERIES.set_for_testing(False)