-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
tests.py
2476 lines (2238 loc) · 94.4 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
import json
from datetime import timedelta, datetime
from unittest.mock import MagicMock, patch, Mock, ANY
import sqlparse
from django.contrib.auth import get_user_model
from django.test import TestCase
from common.config import SysConfig
from sql.engines import EngineBase
from sql.engines.goinception import GoInceptionEngine
from sql.engines.models import ResultSet, ReviewSet, ReviewResult
from sql.engines.mssql import MssqlEngine
from sql.engines.redis import RedisEngine
from sql.engines.pgsql import PgSQLEngine
from sql.engines.oracle import OracleEngine
from sql.engines.mongo import MongoEngine
from sql.engines.clickhouse import ClickHouseEngine
from sql.engines.odps import ODPSEngine
from sql.models import DataMaskingColumns, Instance, SqlWorkflow, SqlWorkflowContent
User = get_user_model()
class TestReviewSet(TestCase):
def test_review_set(self):
new_review_set = ReviewSet()
new_review_set.rows = [{"id": "1679123"}]
self.assertIn("1679123", new_review_set.json())
class TestEngineBase(TestCase):
@classmethod
def setUpClass(cls):
cls.u1 = User(username="some_user", display="用户1")
cls.u1.save()
cls.ins1 = Instance(
instance_name="some_ins",
type="master",
db_type="mssql",
host="some_host",
port=1366,
user="ins_user",
password="some_str",
)
cls.ins1.save()
cls.wf1 = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer=cls.u1.username,
engineer_display=cls.u1.display,
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=cls.ins1,
db_name="some_db",
syntax_type=1,
)
cls.wfc1 = SqlWorkflowContent.objects.create(
workflow=cls.wf1,
sql_content="some_sql",
execute_result=json.dumps([{"id": 1, "sql": "some_content"}]),
)
@classmethod
def tearDownClass(cls):
cls.wfc1.delete()
cls.wf1.delete()
cls.ins1.delete()
cls.u1.delete()
def test_init_with_ins(self):
engine = EngineBase(instance=self.ins1)
self.assertEqual(self.ins1.instance_name, engine.instance_name)
self.assertEqual(self.ins1.user, engine.user)
class TestMssql(TestCase):
@classmethod
def setUpClass(cls):
cls.ins1 = Instance(
instance_name="some_ins",
type="slave",
db_type="mssql",
host="some_host",
port=1366,
user="ins_user",
password="some_str",
)
cls.ins1.save()
cls.engine = MssqlEngine(instance=cls.ins1)
cls.wf = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer_display="",
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=cls.ins1,
db_name="some_db",
syntax_type=1,
)
SqlWorkflowContent.objects.create(
workflow=cls.wf, sql_content="insert into some_tb values (1)"
)
@classmethod
def tearDownClass(cls):
cls.ins1.delete()
cls.wf.delete()
SqlWorkflowContent.objects.all().delete()
@patch("sql.engines.mssql.pyodbc.connect")
def testGetConnection(self, connect):
new_engine = MssqlEngine(instance=self.ins1)
new_engine.get_connection()
connect.assert_called_once()
@patch("sql.engines.mssql.pyodbc.connect")
def testQuery(self, connect):
cur = Mock()
connect.return_value.cursor = cur
cur.return_value.execute = Mock()
cur.return_value.fetchmany.return_value = (("v1", "v2"),)
cur.return_value.description = (
("k1", "some_other_des"),
("k2", "some_other_des"),
)
new_engine = MssqlEngine(instance=self.ins1)
query_result = new_engine.query(sql="some_str", limit_num=100)
cur.return_value.execute.assert_called()
cur.return_value.fetchmany.assert_called_once_with(100)
connect.return_value.close.assert_called_once()
self.assertIsInstance(query_result, ResultSet)
@patch.object(MssqlEngine, "query")
def testAllDb(self, mock_query):
db_result = ResultSet()
db_result.rows = [("db_1",), ("db_2",)]
mock_query.return_value = db_result
new_engine = MssqlEngine(instance=self.ins1)
dbs = new_engine.get_all_databases()
self.assertEqual(dbs.rows, ["db_1", "db_2"])
@patch.object(MssqlEngine, "query")
def testAllTables(self, mock_query):
table_result = ResultSet()
table_result.rows = [("tb_1", "some_des"), ("tb_2", "some_des")]
mock_query.return_value = table_result
new_engine = MssqlEngine(instance=self.ins1)
tables = new_engine.get_all_tables("some_db")
mock_query.assert_called_once_with(db_name="some_db", sql=ANY)
self.assertEqual(tables.rows, ["tb_1", "tb_2"])
@patch.object(MssqlEngine, "query")
def testAllColumns(self, mock_query):
db_result = ResultSet()
db_result.rows = [("col_1", "type"), ("col_2", "type2")]
mock_query.return_value = db_result
new_engine = MssqlEngine(instance=self.ins1)
dbs = new_engine.get_all_columns_by_tb("some_db", "some_tb")
self.assertEqual(dbs.rows, ["col_1", "col_2"])
@patch.object(MssqlEngine, "query")
def testDescribe(self, mock_query):
new_engine = MssqlEngine(instance=self.ins1)
new_engine.describe_table("some_db", "some_db")
mock_query.assert_called_once()
def testQueryCheck(self):
new_engine = MssqlEngine(instance=self.ins1)
# 只抽查一个函数
banned_sql = "select concat(phone,1) from user_table"
check_result = new_engine.query_check(db_name="some_db", sql=banned_sql)
self.assertTrue(check_result.get("bad_query"))
banned_sql = "select phone from user_table where phone=concat(phone,1)"
check_result = new_engine.query_check(db_name="some_db", sql=banned_sql)
self.assertTrue(check_result.get("bad_query"))
sp_sql = "sp_helptext '[SomeName].[SomeAction]'"
check_result = new_engine.query_check(db_name="some_db", sql=sp_sql)
self.assertFalse(check_result.get("bad_query"))
self.assertEqual(check_result.get("filtered_sql"), sp_sql)
def test_filter_sql(self):
new_engine = MssqlEngine(instance=self.ins1)
# 只抽查一个函数
banned_sql = "select user from user_table"
check_result = new_engine.filter_sql(sql=banned_sql, limit_num=10)
self.assertEqual(check_result, "select top 10 user from user_table")
def test_filter_sql_with_distinct(self):
new_engine = MssqlEngine(instance=self.ins1)
# 只抽查一个函数
banned_sql = "select distinct * from user_table"
check_result = new_engine.filter_sql(sql=banned_sql, limit_num=10)
self.assertEqual(check_result, "select distinct top 10 * from user_table")
def test_execute_check(self):
new_engine = MssqlEngine(instance=self.ins1)
test_sql = (
"use database\ngo\nsome sql1\nGO\nsome sql2\n\r\nGo\nsome sql3\n\r\ngO\n"
)
check_result = new_engine.execute_check(db_name=None, sql=test_sql)
self.assertIsInstance(check_result, ReviewSet)
self.assertEqual(check_result.rows[1].__dict__["sql"], "use database\n")
self.assertEqual(check_result.rows[2].__dict__["sql"], "\nsome sql1\n")
self.assertEqual(check_result.rows[4].__dict__["sql"], "\nsome sql3\n\r\n")
@patch("sql.engines.mssql.MssqlEngine.execute")
def test_execute_workflow(self, mock_execute):
mock_execute.return_value.error = None
new_engine = MssqlEngine(instance=self.ins1)
new_engine.execute_workflow(self.wf)
# 有多少个备份表, 就需要execute多少次, 另外加上一条实际执行的次数
mock_execute.assert_called()
self.assertEqual(1, mock_execute.call_count)
@patch("sql.engines.mssql.MssqlEngine.get_connection")
def test_execute(self, mock_connect):
mock_cursor = Mock()
mock_connect.return_value.cursor = mock_cursor
new_engine = MssqlEngine(instance=self.ins1)
execute_result = new_engine.execute("some_db", "some_sql")
# 验证结果, 无异常
self.assertIsNone(execute_result.error)
self.assertEqual("some_sql", execute_result.full_sql)
self.assertEqual(2, len(execute_result.rows))
mock_cursor.return_value.execute.assert_called()
mock_cursor.return_value.commit.assert_called()
mock_cursor.reset_mock()
# 验证异常
mock_cursor.return_value.execute.side_effect = Exception(
"Boom! some exception!"
)
execute_result = new_engine.execute("some_db", "some_sql")
self.assertIn("Boom! some exception!", execute_result.error)
self.assertEqual("some_sql", execute_result.full_sql)
self.assertEqual(2, len(execute_result.rows))
mock_cursor.return_value.commit.assert_not_called()
mock_cursor.return_value.rollback.assert_called()
class TestRedis(TestCase):
@classmethod
def setUpClass(cls):
cls.ins = Instance(
instance_name="some_ins",
type="slave",
db_type="redis",
mode="standalone",
host="some_host",
port=1366,
user="ins_user",
password="some_str",
)
cls.ins.save()
@classmethod
def tearDownClass(cls):
cls.ins.delete()
SqlWorkflow.objects.all().delete()
SqlWorkflowContent.objects.all().delete()
@patch("redis.Redis")
def test_engine_base_info(self, _conn):
new_engine = RedisEngine(instance=self.ins)
self.assertEqual(new_engine.name, "Redis")
self.assertEqual(new_engine.info, "Redis engine")
@patch("redis.Redis")
def test_get_connection(self, _conn):
new_engine = RedisEngine(instance=self.ins)
new_engine.get_connection()
_conn.assert_called_once()
@patch("redis.Redis.execute_command", return_value=[1, 2, 3])
def test_query_return_list(self, _execute_command):
new_engine = RedisEngine(instance=self.ins)
query_result = new_engine.query(db_name=0, sql="keys *", limit_num=100)
self.assertIsInstance(query_result, ResultSet)
self.assertTupleEqual(query_result.rows, ([1], [2], [3]))
@patch("redis.Redis.execute_command", return_value="text")
def test_query_return_str(self, _execute_command):
new_engine = RedisEngine(instance=self.ins)
query_result = new_engine.query(db_name=0, sql="keys *", limit_num=100)
self.assertIsInstance(query_result, ResultSet)
self.assertTupleEqual(query_result.rows, (["text"],))
@patch("redis.Redis.execute_command", return_value="text")
def test_query_execute(self, _execute_command):
new_engine = RedisEngine(instance=self.ins)
query_result = new_engine.query(db_name=0, sql="keys *", limit_num=100)
self.assertIsInstance(query_result, ResultSet)
self.assertTupleEqual(query_result.rows, (["text"],))
@patch("redis.Redis.execute_command")
def test_query_with_dict_response(self, _execute_command):
# 定义 execute_command 的字典响应
dict_response = {
"key1": "value1",
"key2": {"subkey": "subvalue"},
"key3": ["listitem1", "listitem2"],
}
_execute_command.return_value = dict_response
new_engine = RedisEngine(instance=self.ins)
query_result = new_engine.query(db_name=0, sql="keys *", limit_num=100)
# 验证结果集
expected_rows = [
["key1", "value1"],
["key2", json.dumps({"subkey": "subvalue"})],
["key3", json.dumps(["listitem1", "listitem2"])],
]
self.assertIsInstance(query_result, ResultSet)
self.assertEqual(query_result.column_list, ["field", "value"])
self.assertEqual(query_result.rows, tuple(expected_rows))
self.assertEqual(query_result.affected_rows, len(expected_rows))
@patch("redis.Redis.config_get", return_value={"databases": 4})
def test_get_all_databases(self, _config_get):
new_engine = RedisEngine(instance=self.ins)
dbs = new_engine.get_all_databases()
self.assertListEqual(dbs.rows, ["0", "1", "2", "3"])
@patch("redis.Redis.info")
@patch("redis.Redis.config_get")
def test_get_all_databases_exception_handling(self, mock_config_get, mock_info):
# 模拟config_get方法抛出异常
mock_config_get.side_effect = Exception("模拟config_get异常")
# 模拟info方法返回特定的Keyspace信息
mock_info.return_value = {
"db0": "some_info",
"db1": "some_info",
"db18": "some_info",
}
# 实例化RedisEngine并调用get_all_databases方法
new_engine = RedisEngine(instance=self.ins)
result = new_engine.get_all_databases()
# 验证返回的数据库列表是否符合预期.
expected_dbs = [str(x) for x in range(int(19))]
self.assertListEqual(result.rows, expected_dbs)
# 验证config_get方法被调用
mock_config_get.assert_called_once_with("databases")
# 验证info方法被调用
mock_info.assert_called_once_with("Keyspace")
@patch("redis.Redis.info")
@patch("redis.Redis.config_get")
def test_get_all_databases_with_empty_return_value(
self, mock_config_get, mock_info
):
"""
测试当Redis CONFIG GET命令因异常而失败,并且info命令返回空Keyspace信息时,
get_all_databases方法应正确处理并返回包含从0到15的数据库索引列表。
"""
# 模拟config_get方法抛出异常
mock_config_get.side_effect = Exception("模拟config_get异常")
# 模拟info方法返回空的Keyspace信息
mock_info.return_value = {}
# 实例化RedisEngine并调用get_all_databases方法
new_engine = RedisEngine(instance=self.ins)
result = new_engine.get_all_databases()
# 验证返回的数据库列表,应该包括0到15,总共16个数据库
expected_dbs = [str(x) for x in range(16)]
self.assertListEqual(result.rows, expected_dbs)
# 验证config_get和info方法的调用
mock_config_get.assert_called_once_with("databases")
mock_info.assert_called_once_with("Keyspace")
@patch("redis.Redis.info")
@patch("redis.Redis.config_get")
def test_get_all_databases_with_less_than_15_dbs(self, mock_config_get, mock_info):
"""
测试当Redis CONFIG GET命令因异常而失败,并且info命令返回的Keyspace信息
db num数据库值小于15时,get_all_databases方法应正确处理并返回包含从0到15的数据库索引列表。
"""
# 模拟config_get方法抛出异常
mock_config_get.side_effect = Exception("模拟config_get异常")
# 模拟info方法返回小于15个数据库的Keyspace信息
mock_info.return_value = {
"db0": "some_info",
"db1": "some_info",
"db5": "some_info",
# 假设只有3个数据库
}
# 实例化RedisEngine并调用get_all_databases方法
new_engine = RedisEngine(instance=self.ins)
result = new_engine.get_all_databases()
# 验证返回的数据库列表,应该包括0到15,总共16个数据库
expected_dbs = [str(x) for x in range(16)]
self.assertListEqual(result.rows, expected_dbs)
# 验证config_get和info方法的调用
mock_config_get.assert_called_once_with("databases")
mock_info.assert_called_once_with("Keyspace")
def test_query_check_safe_cmd(self):
safe_cmd = "keys 1*"
new_engine = RedisEngine(instance=self.ins)
check_result = new_engine.query_check(db_name=0, sql=safe_cmd)
self.assertDictEqual(
check_result,
{
"msg": "禁止执行该命令!",
"bad_query": True,
"filtered_sql": safe_cmd,
"has_star": False,
},
)
def test_query_check_danger_cmd(self):
safe_cmd = "keys *"
new_engine = RedisEngine(instance=self.ins)
check_result = new_engine.query_check(db_name=0, sql=safe_cmd)
self.assertDictEqual(
check_result,
{
"msg": "禁止执行该命令!",
"bad_query": True,
"filtered_sql": safe_cmd,
"has_star": False,
},
)
def test_filter_sql(self):
safe_cmd = "keys 1*"
new_engine = RedisEngine(instance=self.ins)
check_result = new_engine.filter_sql(sql=safe_cmd, limit_num=100)
self.assertEqual(check_result, "keys 1*")
def test_query_masking(self):
query_result = ResultSet()
new_engine = RedisEngine(instance=self.ins)
masking_result = new_engine.query_masking(
db_name=0, sql="", resultset=query_result
)
self.assertEqual(masking_result, query_result)
def test_execute_check(self):
sql = "set 1 1"
row = ReviewResult(
id=1,
errlevel=0,
stagestatus="Audit completed",
errormessage="暂不支持显示影响行数",
sql=sql,
affected_rows=0,
execute_time=0,
)
new_engine = RedisEngine(instance=self.ins)
check_result = new_engine.execute_check(db_name=0, sql=sql)
self.assertIsInstance(check_result, ReviewSet)
self.assertEqual(check_result.rows[0].__dict__, row.__dict__)
@patch("redis.Redis.execute_command", return_value="text")
def test_execute_workflow_success(self, _execute_command):
sql = "set 1 1"
row = ReviewResult(
id=1,
errlevel=0,
stagestatus="Execute Successfully",
errormessage="暂不支持显示影响行数",
sql=sql,
affected_rows=0,
execute_time=0,
)
wf = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer_display="",
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=self.ins,
db_name="some_db",
syntax_type=1,
)
SqlWorkflowContent.objects.create(workflow=wf, sql_content=sql)
new_engine = RedisEngine(instance=self.ins)
execute_result = new_engine.execute_workflow(workflow=wf)
self.assertIsInstance(execute_result, ReviewSet)
self.assertEqual(execute_result.rows[0].__dict__.keys(), row.__dict__.keys())
@patch("sql.engines.redis.RedisEngine.get_connection")
def test_processlist(self, mock_get_connection):
"""测试 processlist 方法,模拟获取连接并返回客户端列表"""
# 模拟 Redis 连接的客户端列表
mock_conn = Mock()
return_value_mock = [
{"id": "1", "idle": 10, "name": "client_1"},
{"id": "2", "idle": 5, "name": "client_2"},
{"id": "3", "idle": 20, "name": "client_3"},
]
mock_conn.client_list.return_value = return_value_mock
# 设置 get_connection 返回模拟连接
mock_get_connection.return_value = mock_conn
# 创建 RedisEngine 实例
new_engine = RedisEngine(instance=self.ins)
# 调用 processlist 方法并测试其返回值
command_types = ["All"] # 假设支持的命令类型
for command_type in command_types:
result_set = new_engine.processlist(command_type=command_type)
# 验证返回值是 ResultSet 实例
self.assertIsInstance(result_set, ResultSet)
# 验证返回的客户端列表被正确排序
sorted_clients = sorted(
return_value_mock, key=lambda client: client.get("idle"), reverse=False
)
self.assertEqual(result_set.rows, sorted_clients)
# 验证 get_connection 是否被调用
mock_get_connection.assert_called()
class TestPgSQL(TestCase):
@classmethod
def setUpClass(cls):
cls.ins = Instance(
instance_name="some_ins",
type="slave",
db_type="pgsql",
host="some_host",
port=1366,
user="ins_user",
password="some_str",
)
cls.ins.save()
cls.sys_config = SysConfig()
@classmethod
def tearDownClass(cls):
cls.ins.delete()
cls.sys_config.purge()
@patch("psycopg2.connect")
def test_engine_base_info(self, _conn):
new_engine = PgSQLEngine(instance=self.ins)
self.assertEqual(new_engine.name, "PgSQL")
self.assertEqual(new_engine.info, "PgSQL engine")
@patch("psycopg2.connect")
def test_get_connection(self, _conn):
new_engine = PgSQLEngine(instance=self.ins)
new_engine.get_connection("some_dbname")
_conn.assert_called_once()
@patch("psycopg2.connect.cursor.execute")
@patch("psycopg2.connect.cursor")
@patch("psycopg2.connect")
def test_query(self, _conn, _cursor, _execute):
_conn.return_value.cursor.return_value.fetchmany.return_value = [(1,)]
new_engine = PgSQLEngine(instance=self.ins)
query_result = new_engine.query(
db_name="some_dbname",
sql="select 1",
limit_num=100,
schema_name="some_schema",
)
self.assertIsInstance(query_result, ResultSet)
self.assertListEqual(query_result.rows, [(1,)])
@patch("psycopg2.connect.cursor.execute")
@patch("psycopg2.connect.cursor")
@patch("psycopg2.connect")
def test_query_not_limit(self, _conn, _cursor, _execute):
# 模拟数据库连接和游标
mock_cursor = MagicMock()
_conn.return_value.cursor.return_value = mock_cursor
# 模拟 SQL 查询的返回结果,包含 JSONB 类型、字符串和数字数据
mock_cursor.fetchall.return_value = [
({"key": "value"}, "test_string", 123) # 返回一行数据,三列
]
mock_cursor.description = [
("json_column", 3802), # JSONB 类型
("string_column", 25), # 25 表示 TEXT 类型的 OID
("number_column", 23), # 23 表示 INTEGER 类型的 OID
]
# _conn.return_value.cursor.return_value.fetchall.return_value = [(1,)]
new_engine = PgSQLEngine(instance=self.ins)
query_result = new_engine.query(
db_name="some_dbname",
sql="SELECT json_column, string_column, number_column FROM some_table",
limit_num=0,
schema_name="some_schema",
)
# 断言查询结果的类型和数据
self.assertIsInstance(query_result, ResultSet)
# 验证返回的 JSONB 列已转换为 JSON 字符串
expected_row = ('{"key": "value"}', "test_string", 123)
self.assertListEqual(query_result.rows, [expected_row])
expected_column = ["json_column", "string_column", "number_column"]
# 验证列名是否正确
self.assertEqual(query_result.column_list, expected_column)
# 验证受影响的行数
self.assertEqual(query_result.affected_rows, 1)
# 验证类型代码是否正确(3802 表示 JSONB,25 表示 TEXT,23 表示 INTEGER)
expected_column_type_codes = [3802, 25, 23]
actual_column_type_codes = [desc[1] for desc in mock_cursor.description]
self.assertListEqual(actual_column_type_codes, expected_column_type_codes)
@patch(
"sql.engines.pgsql.PgSQLEngine.query",
return_value=ResultSet(
rows=[("postgres",), ("archery",), ("template1",), ("template0",)]
),
)
def test_get_all_databases(self, query):
new_engine = PgSQLEngine(instance=self.ins)
dbs = new_engine.get_all_databases()
self.assertListEqual(dbs.rows, ["postgres", "archery"])
@patch(
"sql.engines.pgsql.PgSQLEngine.query",
return_value=ResultSet(
rows=[("information_schema",), ("archery",), ("pg_catalog",)]
),
)
def test_get_all_schemas(self, _query):
new_engine = PgSQLEngine(instance=self.ins)
schemas = new_engine.get_all_schemas(db_name="archery")
self.assertListEqual(schemas.rows, ["archery"])
@patch(
"sql.engines.pgsql.PgSQLEngine.query",
return_value=ResultSet(rows=[("test",), ("test2",)]),
)
def test_get_all_tables(self, _query):
new_engine = PgSQLEngine(instance=self.ins)
tables = new_engine.get_all_tables(db_name="archery", schema_name="archery")
self.assertListEqual(tables.rows, ["test2"])
@patch(
"sql.engines.pgsql.PgSQLEngine.query",
return_value=ResultSet(rows=[("id",), ("name",)]),
)
def test_get_all_columns_by_tb(self, _query):
new_engine = PgSQLEngine(instance=self.ins)
columns = new_engine.get_all_columns_by_tb(
db_name="archery", tb_name="test2", schema_name="archery"
)
self.assertListEqual(columns.rows, ["id", "name"])
@patch(
"sql.engines.pgsql.PgSQLEngine.query",
return_value=ResultSet(
rows=[("postgres",), ("archery",), ("template1",), ("template0",)]
),
)
def test_describe_table(self, _query):
new_engine = PgSQLEngine(instance=self.ins)
describe = new_engine.describe_table(
db_name="archery", schema_name="archery", tb_name="text"
)
self.assertIsInstance(describe, ResultSet)
def test_query_check_disable_sql(self):
sql = "update xxx set a=1 "
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.query_check(db_name="archery", sql=sql)
self.assertDictEqual(
check_result,
{
"msg": "不支持的查询语法类型!",
"bad_query": True,
"filtered_sql": sql.strip(),
"has_star": False,
},
)
def test_query_check_star_sql(self):
sql = "select * from xx "
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.query_check(db_name="archery", sql=sql)
self.assertDictEqual(
check_result,
{
"msg": "SQL语句中含有 * ",
"bad_query": False,
"filtered_sql": sql.strip(),
"has_star": True,
},
)
def test_query_check_explain(self):
sql = "explain select x from xx "
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.query_check(db_name="archery", sql=sql)
self.assertDictEqual(
check_result,
{
"msg": "",
"bad_query": False,
"filtered_sql": sql.strip(),
"has_star": False,
},
)
def test_filter_sql_with_delimiter(self):
sql = "select * from xx;"
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.filter_sql(sql=sql, limit_num=100)
self.assertEqual(check_result, "select * from xx limit 100;")
def test_filter_sql_without_delimiter(self):
sql = "select * from xx"
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.filter_sql(sql=sql, limit_num=100)
self.assertEqual(check_result, "select * from xx limit 100;")
def test_filter_sql_with_limit(self):
sql = "select * from xx limit 10"
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.filter_sql(sql=sql, limit_num=1)
self.assertEqual(check_result, "select * from xx limit 10;")
def test_query_masking(self):
query_result = ResultSet()
new_engine = PgSQLEngine(instance=self.ins)
masking_result = new_engine.query_masking(
db_name=0, sql="", resultset=query_result
)
self.assertEqual(masking_result, query_result)
def test_execute_check_select_sql(self):
sql = "select * from user;"
row = ReviewResult(
id=1,
errlevel=2,
stagestatus="驳回不支持语句",
errormessage="仅支持DML和DDL语句,查询语句请使用SQL查询功能!",
sql=sql,
)
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.execute_check(db_name="archery", sql=sql)
self.assertIsInstance(check_result, ReviewSet)
self.assertEqual(check_result.rows[0].__dict__, row.__dict__)
def test_execute_check_critical_sql(self):
self.sys_config.set("critical_ddl_regex", "^|update")
self.sys_config.get_all_config()
sql = "update user set id=1"
row = ReviewResult(
id=1,
errlevel=2,
stagestatus="驳回高危SQL",
errormessage="禁止提交匹配" + "^|update" + "条件的语句!",
sql=sql,
)
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.execute_check(db_name="archery", sql=sql)
self.assertIsInstance(check_result, ReviewSet)
self.assertEqual(check_result.rows[0].__dict__, row.__dict__)
def test_execute_check_normal_sql(self):
self.sys_config.purge()
sql = "alter table tb set id=1"
row = ReviewResult(
id=1,
errlevel=0,
stagestatus="Audit completed",
errormessage="None",
sql=sql,
affected_rows=0,
execute_time=0,
)
new_engine = PgSQLEngine(instance=self.ins)
check_result = new_engine.execute_check(db_name="archery", sql=sql)
self.assertIsInstance(check_result, ReviewSet)
self.assertEqual(check_result.rows[0].__dict__, row.__dict__)
@patch("psycopg2.connect.cursor.execute")
@patch("psycopg2.connect.cursor")
@patch("psycopg2.connect")
def test_execute_workflow_success(self, _conn, _cursor, _execute):
sql = "update user set id=1"
row = ReviewResult(
id=1,
errlevel=0,
stagestatus="Execute Successfully",
errormessage="None",
sql=sql,
affected_rows=0,
execute_time=0,
)
wf = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer_display="",
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=self.ins,
db_name="some_db",
syntax_type=1,
)
SqlWorkflowContent.objects.create(workflow=wf, sql_content=sql)
new_engine = PgSQLEngine(instance=self.ins)
execute_result = new_engine.execute_workflow(workflow=wf)
self.assertIsInstance(execute_result, ReviewSet)
self.assertEqual(execute_result.rows[0].__dict__.keys(), row.__dict__.keys())
@patch("psycopg2.connect.cursor.execute")
@patch("psycopg2.connect.cursor")
@patch("psycopg2.connect", return_value=RuntimeError)
def test_execute_workflow_exception(self, _conn, _cursor, _execute):
sql = "update user set id=1"
row = ReviewResult(
id=1,
errlevel=2,
stagestatus="Execute Failed",
errormessage=f'异常信息:{f"Oracle命令执行报错,语句:{sql}"}',
sql=sql,
affected_rows=0,
execute_time=0,
)
wf = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer_display="",
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=self.ins,
db_name="some_db",
syntax_type=1,
)
SqlWorkflowContent.objects.create(workflow=wf, sql_content=sql)
with self.assertRaises(AttributeError):
new_engine = PgSQLEngine(instance=self.ins)
execute_result = new_engine.execute_workflow(workflow=wf)
self.assertIsInstance(execute_result, ReviewSet)
self.assertEqual(
execute_result.rows[0].__dict__.keys(), row.__dict__.keys()
)
@patch("psycopg2.connect")
def test_processlist_not_idle(self, mock_connect):
# 模拟数据库连接和游标
mock_cursor = MagicMock()
mock_connect.return_value.cursor.return_value = mock_cursor
# 假设 query 方法返回的结果
mock_cursor.fetchall.return_value = [
(123, "test_db", "user", "app_name", "active")
]
# 创建 PgSQLEngine 实例
new_engine = PgSQLEngine(instance=self.ins)
# 调用 processlist 方法
result = new_engine.processlist(command_type="Not Idle")
self.assertEqual(result.rows, mock_cursor.fetchall.return_value)
@patch("psycopg2.connect")
def test_processlist_idle(self, mock_connect):
# 模拟数据库连接和游标
mock_cursor = MagicMock()
mock_connect.return_value.cursor.return_value = mock_cursor
# 假设 query 方法返回的结果
mock_cursor.fetchall.return_value = [
(123, "test_db", "user", "app_name", "idle")
]
# 创建 PgSQLEngine 实例
new_engine = PgSQLEngine(instance=self.ins)
# 调用 processlist 方法
result = new_engine.processlist(command_type="Idle")
self.assertEqual(result.rows, mock_cursor.fetchall.return_value)
class TestModel(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_result_set_rows_shadow(self):
# 测试默认值为空列表的坑
# 如果默认值是空列表,又使用的是累加的方法更新,会导致残留上次的列表
result_set1 = ResultSet()
for i in range(10):
result_set1.rows += [i]
brand_new_result_set = ResultSet()
self.assertEqual(brand_new_result_set.rows, [])
review_set1 = ReviewSet()
for i in range(10):
review_set1.rows += [i]
brand_new_review_set = ReviewSet()
self.assertEqual(brand_new_review_set.rows, [])
class TestGoInception(TestCase):
def setUp(self):
self.ins = Instance.objects.create(
instance_name="some_ins",
type="slave",
db_type="mysql",
host="some_host",
port=3306,
user="ins_user",
password="some_str",
)
self.ins_inc = Instance.objects.create(
instance_name="some_ins_inc",
type="slave",
db_type="goinception",
host="some_host",
port=4000,
)
self.wf = SqlWorkflow.objects.create(
workflow_name="some_name",
group_id=1,
group_name="g1",
engineer_display="",
audit_auth_groups="some_group",
create_time=datetime.now() - timedelta(days=1),
status="workflow_finish",
is_backup=True,
instance=self.ins,
db_name="some_db",
syntax_type=1,
)
SqlWorkflowContent.objects.create(workflow=self.wf)
def tearDown(self):
self.ins.delete()
self.ins_inc.delete()
SqlWorkflow.objects.all().delete()
SqlWorkflowContent.objects.all().delete()
@patch("MySQLdb.connect")
def test_get_connection(self, _connect):
new_engine = GoInceptionEngine()
new_engine.get_connection()
_connect.assert_called_once()
@patch("sql.engines.goinception.GoInceptionEngine.query")
def test_execute_check_normal_sql(self, _query):
sql = "update user set id=100"
row = [
1,
"CHECKED",
0,
"Audit completed",
"None",
"use archery",
0,
"'0_0_0'",
"None",
"0",
"",
"",
]
_query.return_value = ResultSet(full_sql=sql, rows=[row])
new_engine = GoInceptionEngine()
check_result = new_engine.execute_check(instance=self.ins, db_name=0, sql=sql)
self.assertIsInstance(check_result, ReviewSet)
@patch("sql.engines.goinception.GoInceptionEngine.query")
def test_execute_exception(self, _query):
sql = "update user set id=100"
row = [
1,
"CHECKED",
1,
"Execute failed",
"None",
"use archery",
0,
"'0_0_0'",
"None",
"0",
"",
"",
]