forked from CCExtractor/sample-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_controllers.py
More file actions
4181 lines (3417 loc) · 177 KB
/
test_controllers.py
File metadata and controls
4181 lines (3417 loc) · 177 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
import json
import unittest
from importlib import reload
from unittest import mock
from unittest.mock import MagicMock
from flask import g
from mod_auth.models import Role
from mod_ci.controllers import (Workflow_builds, get_info_for_pr_comment,
is_valid_commit_hash, mark_test_failed,
progress_type_request, retry_with_backoff,
safe_db_commit, start_platforms)
from mod_ci.models import BlockedUsers
from mod_customized.models import CustomizedTest
from mod_home.models import CCExtractorVersion, GeneralData
from mod_regression.models import (RegressionTest, RegressionTestOutput,
RegressionTestOutputFiles)
from mod_test.models import Test, TestPlatform, TestResultFile, TestType
from tests.base import (BaseTestCase, MockResponse, create_mock_db_query,
create_mock_regression_test, empty_github_token,
generate_git_api_header, generate_signature,
mock_api_request_github)
class MockGcpInstance:
"""Mock GcpInstance object."""
def __init__(self, name):
self.name = name
class MockPlatform:
"""Mock platform object."""
def __init__(self, platform):
self.platform = platform
self.value = 'linux'
class MockStatus:
"""Mock GitHub commit status object."""
def __init__(self, context):
self.context = context
class MockFork:
"""Mock fork object."""
def __init__(self, *args, **kwargs):
self.github = None
class MockTest:
"""Mock test object."""
def __init__(self):
self.id = 1
self.test_type = TestType.commit
self.fork = MockFork()
self.platform = MockPlatform(TestPlatform.linux)
WSGI_ENVIRONMENT = {'REMOTE_ADDR': "192.30.252.0"}
class TestControllers(BaseTestCase):
"""Test CI-related controllers."""
def test_comment_info_handles_variant_files_correctly(self):
"""Test that allowed variants of output files are handled correctly in PR comments.
Make sure that the info used for the PR comment treats tests as successes if they got one of the allowed
variants of the output file instead of the original version
"""
VARIANT_HASH = 'abcdefgh_this_is_a_hash'
TEST_RUN_ID = 1
# Setting up the database
# create regression test with an output file that has an allowed variant
regression_test: RegressionTest = RegressionTest.query.filter(RegressionTest.id == 1).first()
output_file: RegressionTestOutput = regression_test.output_files[0]
variant_output_file = RegressionTestOutputFiles(VARIANT_HASH, output_file.id)
output_file.multiple_files.append(variant_output_file)
g.db.add(output_file)
test_run_output_file: TestResultFile = TestResultFile.query.filter(
TestResultFile.regression_test_output_id == output_file.id,
TestResultFile.test_id == TEST_RUN_ID
).first()
# mark the test as getting the variant as output, not the expected file
test_run_output_file.got = VARIANT_HASH
g.db.add(test_run_output_file)
g.db.commit()
# The actual test
test: Test = Test.query.get(TEST_RUN_ID)
comment_info = get_info_for_pr_comment(test)
# we got a valid variant, so should still pass
self.assertEqual(comment_info.common_failed_tests, [])
self.assertEqual(comment_info.extra_failed_tests, [])
self.assertEqual(comment_info.fixed_tests, [])
for stats in comment_info.category_stats:
# make sure the stats for the category confirm that everything passed too
self.assertEqual(stats.success, stats.total)
def test_comment_info_handles_invalid_variants_correctly(self):
"""Test that invalid variants of output files are handled correctly in PR comments.
Make sure that regression tests are correctly marked as not passing when an invalid file hash is found
"""
INVALID_VARIANT_HASH = 'this_is_an_invalid_hash'
TEST_RUN_ID = 1
test_result_file: TestResultFile = TestResultFile.query.filter(TestResultFile.test_id == TEST_RUN_ID).first()
test_result_file.got = INVALID_VARIANT_HASH
g.db.add(test_result_file)
g.db.commit()
test: Test = Test.query.get(TEST_RUN_ID)
comment_info = get_info_for_pr_comment(test)
# all categories that this regression test applies to should fail because of the invalid hash
for category in test_result_file.regression_test.categories:
stats = [stat for stat in comment_info.category_stats if stat.category == category.name]
for stat in stats:
self.assertEqual(stat.success, 0)
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.delete_expired_instances')
@mock.patch('mod_ci.controllers.gcp_instance')
@mock.patch('run.log')
def test_start_platform_none_specified(self, mock_log, mock_gcp_instance,
mock_delete_expired_instances, mock_get_compute_service_object):
"""Test that both platforms run when no platform value is passed."""
start_platforms(mock.ANY, 1)
mock_delete_expired_instances.assert_called_once()
mock_get_compute_service_object.assert_called_once()
self.assertEqual(2, mock_gcp_instance.call_count)
self.assertEqual(4, mock_log.info.call_count)
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.delete_expired_instances')
@mock.patch('mod_ci.controllers.gcp_instance')
@mock.patch('run.log')
def test_start_platform_linux_specified(self, mock_log, mock_gcp_instance,
mock_delete_expired_instances, mock_get_compute_service_object):
"""Test that only Linux platform runs when platform is specified as Linux."""
start_platforms(mock.ANY, platform=TestPlatform.linux)
self.assertEqual(1, mock_gcp_instance.call_count)
self.assertEqual(2, mock_log.info.call_count)
mock_log.info.assert_called_with("Linux GCP instances process kicked off")
mock_delete_expired_instances.assert_called_once()
mock_get_compute_service_object.assert_called_once()
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.delete_expired_instances')
@mock.patch('mod_ci.controllers.gcp_instance')
@mock.patch('run.log')
def test_start_platform_windows_specified(self, mock_log, mock_gcp_instance,
mock_delete_expired_instances, mock_get_compute_service_object):
"""Test that only Windows platform runs when platform is specified as Windows."""
start_platforms(mock.ANY, platform=TestPlatform.windows)
self.assertEqual(1, mock_gcp_instance.call_count)
self.assertEqual(2, mock_log.info.call_count)
mock_log.info.assert_called_with("Windows GCP instances process kicked off")
mock_delete_expired_instances.assert_called_once()
mock_get_compute_service_object.assert_called_once()
@mock.patch('run.log')
@mock.patch('mod_ci.controllers.MaintenanceMode')
def test_gcp_instance_maintenance_mode(self, mock_maintenance, mock_log):
"""Test that gcp instance does not run when in maintainenace."""
from mod_ci.controllers import gcp_instance
class MockMaintenance:
def __init__(self):
self.disabled = True
mock_maintenance.query.filter.return_value.first.return_value = MockMaintenance()
gcp_instance(mock.ANY, mock.ANY, "test", mock.ANY, 1)
mock_log.info.assert_called_once()
mock_log.critical.assert_not_called()
self.assertEqual(mock_log.debug.call_count, 2)
@mock.patch('github.Github')
@mock.patch('mod_ci.controllers.delete_expired_instances')
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.gcp_instance')
def test_cron_job_testing_false(self, mock_gcp_instance, mock_get_compute_service_object,
mock_delete_expired_instances, mock_github):
"""Test working of cron function when testing is disabled."""
from mod_ci.cron import cron
mock_delete_expired_instances.reset_mock()
mock_get_compute_service_object.reset_mock()
cron()
self.assertEqual(mock_delete_expired_instances.call_count, 1)
self.assertEqual(mock_get_compute_service_object.call_count, 1)
@mock.patch('github.Github')
@mock.patch('mod_ci.controllers.delete_expired_instances')
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.gcp_instance')
def test_cron_job_testing_true(self, mock_gcp_instance, mock_get_compute_service_object,
mock_delete_expired_instances, mock_github):
"""Test working of cron function when testing is enabled."""
from mod_ci.cron import cron
mock_delete_expired_instances.reset_mock()
mock_get_compute_service_object.reset_mock()
cron(testing=True)
mock_delete_expired_instances.assert_not_called()
mock_get_compute_service_object.assert_not_called()
@mock.patch.dict('run.config', {'GITHUB_TOKEN': '', 'GITHUB_OWNER': 'test', 'GITHUB_REPOSITORY': 'test'})
@mock.patch('run.log')
def test_cron_job_empty_token(self, mock_log):
"""Test cron returns early when GitHub token is empty."""
from mod_ci.cron import cron
cron()
mock_log.error.assert_called_with('GITHUB_TOKEN not configured, cannot run CI cron')
@mock.patch('mod_ci.controllers.wait_for_operation')
@mock.patch('mod_ci.controllers.create_instance')
@mock.patch('builtins.open', new_callable=mock.mock_open())
@mock.patch('mod_ci.controllers.g')
@mock.patch('mod_ci.controllers.TestProgress')
@mock.patch('mod_ci.controllers.GcpInstance')
def test_start_test(self, mock_gcp_instance, mock_test_progress, mock_g, mock_open_file,
mock_create_instance, mock_wait_for_operation):
"""Test start_test function."""
import zipfile
import requests
from github.Artifact import Artifact
from mod_ci.controllers import Artifact_names, start_test
# Mock locking checks to return None (no existing instances/progress)
mock_gcp_instance.query.filter.return_value.first.return_value = None
mock_test_progress.query.filter.return_value.first.return_value = None
test = Test.query.first()
repository = MagicMock()
artifact1 = MagicMock(Artifact)
artifact1.name = Artifact_names.windows
artifact1.workflow_run.head_sha = '1978060bf7d2edd119736ba3ba88341f3bec3322'
artifact2 = MagicMock(Artifact)
artifact2.name = Artifact_names.linux
artifact2.workflow_run.head_sha = '1978060bf7d2edd119736ba3ba88341f3bec3323'
class mock_zip:
def __enter__(self):
return self
def __exit__(self, *args):
return False
def extractall(*args, **kwargs):
return None
repository.get_artifacts.return_value = [artifact1, artifact2]
response = requests.models.Response()
response.status_code = 200
requests.get = MagicMock(return_value=response)
zipfile.ZipFile = MagicMock(return_value=mock_zip())
customized_test = CustomizedTest(1, 1)
g.db.add(customized_test)
g.db.commit()
# Set up mock db query chain to avoid AsyncMock behavior in Python 3.13+
mock_query = create_mock_db_query(mock_g)
mock_query.c.got = MagicMock()
# Test when gcp create instance fails synchronously (error in operation response)
mock_create_instance.return_value = {'error': {'errors': [{'code': 'TEST_ERROR'}]}}
start_test(mock.ANY, self.app, mock_g.db, repository, test, mock.ANY)
# Commit IS called to record the test failure in the database
mock_g.db.commit.assert_called_once()
mock_g.db.commit.reset_mock()
mock_create_instance.reset_mock()
# Test when gcp create instance is successful and verified
mock_create_instance.return_value = {'name': 'test-operation-123', 'status': 'RUNNING'}
mock_wait_for_operation.return_value = {'status': 'DONE'} # Success
start_test(mock.ANY, self.app, mock_g.db, repository, test, mock.ANY)
mock_g.db.commit.assert_called_once()
mock_create_instance.assert_called_once()
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.start_test')
@mock.patch('mod_ci.controllers.get_compute_service_object')
@mock.patch('mod_ci.controllers.g')
def test_gcp_instance(self, mock_g, mock_get_compute_service_object, mock_start_test, mock_repo):
"""Test gcp_instance function."""
from mod_ci.controllers import gcp_instance
repo = mock_repo()
# Making test with id 1 invalid with pr_nr = 0
test_1 = Test.query.get(1)
test_1.pr_nr = 0
# Test with id 2 has a different commit than PR head, but we still run it
# (we no longer cancel tests just because a newer commit was pushed)
test_2 = Test.query.get(2)
pr_head_sha = test_2.commit + 'f'
repo.get_pull.return_value.head.sha = pr_head_sha
repo.get_pull.return_value.state = 'open'
# Creating a test with pull_request type that is valid
test_3 = Test(TestPlatform.linux, TestType.pull_request, 1, "pull_request", pr_head_sha, 2)
g.db.add(test_3)
# Creating a test with commit type that is valid
test_4 = Test(TestPlatform.linux, TestType.commit, 1, "master", pr_head_sha)
g.db.add(test_4)
g.db.commit()
# Set up mock db query chain to avoid AsyncMock behavior in Python 3.13+
create_mock_db_query(mock_g)
gcp_instance(self.app, mock_g.db, TestPlatform.linux, repo, None)
# test_1 is descheduled (invalid pr_nr=0)
# test_2, test_3, test_4 all run (3 total)
self.assertEqual(mock_start_test.call_count, 3)
mock_get_compute_service_object.assert_called_once()
def test_get_compute_service_object(self):
"""Test get_compute_service_object function."""
import googleapiclient
from google.oauth2 import service_account
from mod_ci.controllers import get_compute_service_object
service_account.Credentials.from_service_account_file = MagicMock()
compute = get_compute_service_object()
self.assertEqual(type(compute), googleapiclient.discovery.Resource)
@mock.patch('builtins.open', new_callable=mock.mock_open())
def test_create_instance_linux(self, mock_open_file):
"""Test create_instance function for linux platform."""
from mod_ci.controllers import create_instance
compute = MagicMock()
instance = create_instance(compute, "test", "test", Test.query.get(1), "")
mock_open_file.assert_called()
self.assertEqual(str(type(instance)), str(MagicMock))
@mock.patch('builtins.open', new_callable=mock.mock_open())
def test_create_instance_windows(self, mock_open_file):
"""Test create_instance function for windows platform."""
from mod_ci.controllers import create_instance
compute = MagicMock()
new_test = Test(TestPlatform.windows, TestType.commit, 1, "test", "test")
g.db.add(new_test)
g.db.commit()
instance = create_instance(compute, "test", "test", new_test, "")
mock_open_file.assert_called()
self.assertEqual(str(type(instance)), str(MagicMock))
@mock.patch('mod_ci.controllers.GeneralData')
@mock.patch('mod_ci.controllers.g')
def test_set_avg_time_first(self, mock_g, mock_gd):
"""Test setting average time for the first time."""
from mod_ci.controllers import set_avg_time
mock_gd.query.filter.return_value.first.return_value = None
set_avg_time(TestPlatform.linux, "build", 100)
mock_gd.query.filter.assert_called_once_with(mock_gd.key == 'avg_build_count_linux')
self.assertEqual(mock_gd.call_count, 2)
self.assertEqual(mock_g.db.add.call_count, 2)
mock_g.db.commit.assert_called_once()
@mock.patch('mod_ci.controllers.int')
@mock.patch('mod_ci.controllers.GeneralData')
@mock.patch('mod_ci.controllers.g')
def test_set_avg_time(self, mock_g, mock_gd, mock_int):
"""Test setting average time for NOT first time."""
from mod_ci.controllers import set_avg_time
mock_int.return_value = 5
set_avg_time(TestPlatform.windows, "prep", 100)
mock_gd.query.filter.assert_called_with(mock_gd.key == 'avg_prep_count_windows')
self.assertEqual(mock_gd.call_count, 0)
self.assertEqual(mock_g.db.add.call_count, 0)
mock_g.db.commit.assert_called_once()
@mock.patch('github.Github')
def test_comments_successfully_in_passed_pr_test(self, mock_github):
"""Check comments in passed PR test."""
import mod_ci.controllers
reload(mod_ci.controllers)
from github.IssueComment import IssueComment
from mod_ci.controllers import Status, comment_pr
from mod_test.models import Test
pull_request = mock_github.return_value.get_repo.return_value.get_pull(number=1)
pull_request.get_issue_comments.return_value = [MagicMock(IssueComment)]
# Comment on test that fails some/all regression tests
test = Test.query.get(2)
comment_pr(test)
pull_request.get_issue_comments.assert_called_with()
args, kwargs = pull_request.create_issue_comment.call_args
message = kwargs['body']
if "passed" not in message:
assert False, "Message not Correct"
@mock.patch('mod_test.controllers.get_test_results')
@mock.patch('github.Github')
def test_comments_successfuly_in_failed_pr_test(self, mock_github, mock_get_test_results):
"""Check comments in failed PR test."""
import mod_ci.controllers
reload(mod_ci.controllers)
from github.IssueComment import IssueComment
from mod_ci.controllers import comment_pr
from mod_regression.models import Category, RegressionTest
from mod_test.models import Test
pull_request = mock_github.return_value.get_repo.return_value.get_pull(number=1)
pull_request.get_issue_comments.return_value = [MagicMock(IssueComment)]
regression_test = RegressionTest.query.first()
mock_get_test_results.return_value = [{'category': MagicMock(Category), 'tests': [{
'test': regression_test, 'error': True}]}]
# Comment on test that fails some/all regression tests
test = Test.query.get(2)
comment_pr(test)
pull_request.get_issue_comments.assert_called_with()
args, kwargs = pull_request.create_issue_comment.call_args
message = kwargs['body']
if regression_test.command not in message:
assert False, "Message not Correct"
def test_get_running_instances(self):
"""Test get_running_instances function."""
from mod_ci.controllers import get_running_instances
result = get_running_instances(MagicMock(), "test", "test")
self.assertEqual(result, [])
def test_check_main_repo_returns_in_false_url(self):
"""Test main repo checking."""
from mod_ci.controllers import is_main_repo
assert is_main_repo('random_user/random_repo') is False
assert is_main_repo('test_owner/test_repo') is True
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.update_status_on_github')
@mock.patch('mod_ci.controllers.get_running_instances')
def test_delete_expired_instances(self, mock_get_running_instances, mock_update_github_status, mock_repo):
"""Test working of delete_expired_instances function."""
from datetime import datetime, timedelta, timezone
from mod_ci.controllers import delete_expired_instances
current_timestamp = datetime.now(timezone.utc)
expired_instance_time = current_timestamp - timedelta(minutes=150)
mock_get_running_instances.return_value = [{
'name': 'windows-1',
'creationTimestamp': current_timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f%z"),
}, {
'name': 'linux-2',
'creationTimestamp': expired_instance_time.strftime("%Y-%m-%dT%H:%M:%S.%f%z"),
}, {
'name': 'osx-3',
'creationTimestamp': current_timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f%z"),
}]
compute = MagicMock()
pendingOperations = [
{'status': "DONE"},
{'status': "PENDING"}
]
compute.zoneOperations.return_value.get.return_value.execute = pendingOperations.pop
delete_expired_instances(compute, 120, 'a', 'a', MagicMock(), MagicMock())
mock_get_running_instances.assert_called_once()
mock_update_github_status.assert_called_once()
def test_customizedtest_added_to_queue(self):
"""Test queue with a customized test addition."""
regression_test = RegressionTest.query.filter(RegressionTest.id == 1).first()
regression_test.active = False
g.db.add(regression_test)
g.db.commit()
import mod_ci.controllers
reload(mod_ci.controllers)
from mod_ci.controllers import add_test_entry, queue_test
# Use valid hex commit hash (customizedcommitcheck is not valid hex)
test_commit = 'abc1234def567890abc1234def567890abcd1234'
add_test_entry(g.db, test_commit, TestType.commit)
queue_test(None, test_commit, TestType.commit, TestPlatform.linux)
queue_test(None, test_commit, TestType.commit, TestPlatform.windows)
test = Test.query.filter(Test.id == 3).first()
customized_test = test.get_customized_regressiontests()
self.assertIn(2, customized_test)
self.assertNotIn(1, customized_test)
@mock.patch('flask.g.log.error')
@mock.patch('mailer.Mailer')
@mock.patch('mod_ci.controllers.get_html_issue_body')
def test_inform_mailing_list(self, mock_get_html_issue_body, mock_email, mock_log_error):
"""Test the inform_mailing_list function."""
from mod_ci.controllers import inform_mailing_list
mock_get_html_issue_body.return_value = """2430 - Some random string\n\n
Link to Issue: https://www.github.com/test_owner/test_repo/issues/matejmecka\n\n
Some random string(https://github.com/Some random string)\n\n\n
Lorem Ipsum sit dolor amet...\n """
inform_mailing_list(mock_email, "matejmecka", "2430", "Some random string", "Lorem Ipsum sit dolor amet...")
mock_email.send_simple_message.assert_called_once_with(
{
'to': 'ccextractor-dev@googlegroups.com',
'subject': 'GitHub Issue #matejmecka',
'html': """2430 - Some random string\n\n
Link to Issue: https://www.github.com/test_owner/test_repo/issues/matejmecka\n\n
Some random string(https://github.com/Some random string)\n\n\n
Lorem Ipsum sit dolor amet...\n """
}
)
mock_get_html_issue_body.assert_called_once()
mock_log_error.assert_not_called()
mock_email.send_simple_message.return_value = False
inform_mailing_list(mock_email, "matejmecka", "2430", "Some random string", "Lorem Ipsum sit dolor amet...")
mock_log_error.assert_called_once()
@staticmethod
@mock.patch('mod_ci.controllers.markdown')
def test_get_html_issue_body(mock_markdown):
"""Test the get_html_issue_body for correct email formatting."""
from mod_ci.controllers import get_html_issue_body
title = "[BUG] Test Title"
author = "abcxyz"
body = "i'm issue body"
issue_number = 1
url = "www.example.com"
get_html_issue_body(title, author, body, issue_number, url)
mock_markdown.assert_called_once_with(body, extras=["target-blank-links", "task_list", "code-friendly"])
@mock.patch('mod_ci.controllers.update_status_on_github')
@mock.patch('github.Github.get_repo')
def test_add_blocked_users(self, mock_repo, mock_update_gh_status):
"""Check adding a user to block list."""
from github.PullRequest import PullRequest
self.create_user_with_role(self.user.name, self.user.email, self.user.password, Role.admin)
mock_pr = MagicMock(PullRequest)
mock_pr.user.id = 1
mock_pr.number = 3
mock_repo.return_value.get_pulls.return_value = [mock_pr]
new_test = Test(TestPlatform.linux, TestType.pull_request, 1, "test", "test", 3)
g.db.add(new_test)
g.db.commit()
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
c.post("/blocked_users", data=dict(user_id=1, comment="Bad user", add=True))
self.assertNotEqual(BlockedUsers.query.filter(BlockedUsers.user_id == 1).first(), None)
with c.session_transaction() as session:
flash_message = dict(session['_flashes']).get('message')
self.assertEqual(flash_message, "User blocked successfully.")
def test_add_blocked_users_wrong_id(self):
"""Check adding invalid user id to block list."""
self.create_user_with_role(self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
response = c.post("/blocked_users", data=dict(user_id=0, comment="Bad user", add=True))
self.assertEqual(BlockedUsers.query.filter(BlockedUsers.user_id == 0).first(), None)
self.assertIn("GitHub User ID not filled in", str(response.data))
def test_add_blocked_users_empty_id(self):
"""Check adding blank user id to block list."""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
response = c.post("/blocked_users", data=dict(comment="Bad user", add=True))
self.assertEqual(BlockedUsers.query.filter(BlockedUsers.user_id.is_(None)).first(), None)
self.assertIn("GitHub User ID not filled in", str(response.data))
@mock.patch('requests.get', return_value=MockResponse({"login": "test"}, 200))
def test_add_blocked_users_already_exists(self, mock_request):
"""Check adding existing blocked user again."""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
blocked_user = BlockedUsers(1, "Bad user")
g.db.add(blocked_user)
g.db.commit()
c.post("/blocked_users", data=dict(user_id=1, comment="Bad user", add=True))
with c.session_transaction() as session:
flash_message = dict(session['_flashes']).get('message')
self.assertEqual(flash_message, "User already blocked.")
def test_remove_blocked_users(self):
"""Check removing user from block list."""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
blocked_user = BlockedUsers(1, "Bad user")
g.db.add(blocked_user)
g.db.commit()
self.assertNotEqual(BlockedUsers.query.filter(BlockedUsers.comment == "Bad user").first(), None)
c.post("/blocked_users/1", data=dict(remove=True))
self.assertEqual(BlockedUsers.query.filter(BlockedUsers.user_id == 1).first(), None)
with c.session_transaction() as session:
flash_message = dict(session['_flashes']).get('message')
self.assertEqual(flash_message, "User removed successfully.")
def test_remove_blocked_users_wrong_id(self):
"""Check removing non existing id from block list."""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
c.post("/blocked_users/7355608", data=dict(remove=True))
with c.session_transaction() as session:
flash_message = dict(session['_flashes']).get('message')
self.assertEqual(flash_message, "No such user in Blacklist")
def test_remove_blocked_users_invalid_id(self):
"""Check invalid id for the blocked_user url."""
self.create_user_with_role(
self.user.name, self.user.email, self.user.password, Role.admin)
with self.app.test_client() as c:
c.post("/account/login", data=self.create_login_form_data(self.user.email, self.user.password))
response = c.post("/blocked_users/hello", data=dict(remove=True))
self.assertEqual(response.status_code, 404)
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_wrong_url(self, mock_request):
"""Check webhook fails when ping with wrong url."""
with self.app.test_client() as c:
# non GitHub ip address
wsgi_environment = {'REMOTE_ADDR': '0.0.0.0'}
data = {'action': "published",
'release': {'prerelease': False, 'published_at': "2018-05-30T20:18:44Z", 'tag_name': "0.0.1"}}
response = c.post("/start-ci", environ_overrides=wsgi_environment,
data=json.dumps(data), headers=self.generate_header(data, "ping"))
self.assertNotEqual(response.status_code, 200)
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_ping(self, mock_request):
"""Check webhook release update CCExtractor Version for ping."""
with self.app.test_client() as c:
data = {'action': 'published',
'release': {'prerelease': False, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': '0.0.1'}}
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'ping'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, b'{"msg": "Hi!"}')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_release(self, mock_request, mock_repo):
"""Check webhook release update CCExtractor Version for release."""
# Setup mock for tag ref (lightweight tag)
mock_tag_ref = MagicMock()
mock_tag_ref.object.type = "commit"
mock_tag_ref.object.sha = "abcdef12345678901234567890123456789abcde"
mock_repo.return_value.get_git_ref.return_value = mock_tag_ref
with self.app.test_client() as c:
# Full Release with version with 2.1
data = {'action': 'published',
'release': {'prerelease': False, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': 'v2.1'}}
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.order_by(CCExtractorVersion.released.desc()).first()
self.assertEqual(last_release.version, '2.1')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_release_edited(self, mock_request, mock_repo):
"""Check webhook action "edited" updates the specified version."""
from datetime import datetime
# Setup mock for tag ref
mock_tag_ref = MagicMock()
mock_tag_ref.object.type = "commit"
mock_tag_ref.object.sha = "fedcba09876543210fedcba09876543210fedcba"
mock_repo.return_value.get_git_ref.return_value = mock_tag_ref
with self.app.test_client() as c:
release = CCExtractorVersion('2.1', '2018-05-30T20:18:44Z', 'abcdefgh12345678abcdefgh12345678abcdefgh')
g.db.add(release)
g.db.commit()
# Full Release with version with 2.1
data = {'action': 'edited',
'release': {'prerelease': False, 'published_at': '2018-06-30T20:18:44Z', 'tag_name': 'v2.1'}}
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.filter_by(version='2.1').first()
self.assertEqual(last_release.released,
datetime.strptime('2018-06-30T20:18:44Z', '%Y-%m-%dT%H:%M:%SZ').date())
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_release_deleted(self, mock_request, mock_repo):
"""Check webhook action "delete" removes the specified version."""
with self.app.test_client() as c:
# Use valid commit hash
release = CCExtractorVersion('2.1', '2018-05-30T20:18:44Z', '1111111111111111111111111111111111111111')
g.db.add(release)
g.db.commit()
# Delete full release with version with 2.1
data = {'action': 'deleted',
'release': {'prerelease': False, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': 'v2.1'}}
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'release'))
last_release = CCExtractorVersion.query.order_by(CCExtractorVersion.released.desc()).first()
self.assertNotEqual(last_release.version, '2.1')
def test_webhook_prerelease(self):
"""Check webhook release update CCExtractor Version for prerelease."""
with self.app.test_client() as c:
# Full Release with version with 2.1 (prereleased action is ignored)
data = {'action': 'prereleased',
'release': {'prerelease': True, 'published_at': '2018-05-30T20:18:44Z', 'tag_name': 'v2.1'}}
sig = generate_signature(str(json.dumps(data)).encode('utf-8'), g.github['ci_key'])
headers = generate_git_api_header('release', sig)
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'ping'))
last_release = CCExtractorVersion.query.order_by(CCExtractorVersion.released.desc()).first()
self.assertNotEqual(last_release.version, '2.1')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
@mock.patch('run.log')
def test_webhook_push_no_after(self, mock_log, mock_request, mock_repo):
"""Test webhook triggered with push event without 'after' in payload."""
data = {'no_after': 'test'}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'push'))
mock_log.debug.assert_called_with("push event detected")
mock_log.warning.assert_any_call("Unknown push type! Dumping payload for analysis")
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
@mock.patch('mod_ci.controllers.add_test_entry')
@mock.patch('mod_ci.controllers.GeneralData')
def test_webhook_push_valid(self, mock_gd, mock_add_test_entry, mock_request, mock_repo):
"""Test webhook triggered with push event with valid data."""
data = {'after': 'abcdefgh', 'ref': 'refs/heads/master'}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'push'))
mock_gd.query.filter.assert_called()
mock_add_test_entry.assert_called_once()
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.Test')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_closed(self, mock_requests, mock_test, mock_repo):
"""Test webhook triggered with pull_request event with closed action."""
platform_name = "platform"
class MockTest:
def __init__(self):
self.id = 1
self.progress = []
self.platform = MockPlatform(platform_name)
self.commit = "test"
mock_test.query.filter.return_value.all.return_value = [MockTest()]
# Use MockStatus object instead of dict - code expects .context attribute
# Use 'linux' to match MockPlatform.value
mock_repo.return_value.get_commit.return_value.get_statuses.return_value = [
MockStatus("CI - linux")]
data = {'action': 'closed',
'pull_request': {'number': 1234, 'draft': False}}
# one of ip address from GitHub web hook
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
mock_test.query.filter.assert_called_once()
@mock.patch('mod_ci.controllers.BlockedUsers')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_opened_blocked(self, mock_request, mock_repo, mock_blocked):
"""Test webhook triggered with pull_request event with opened action for blocked user."""
data = {'action': 'opened',
'pull_request': {'number': '1234', 'head': {'sha': 'abcd1234'}, 'user': {'id': 'test'}, 'draft': False}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
self.assertEqual(response.data, b'ERROR')
mock_blocked.query.filter.assert_called_once()
@mock.patch('mod_ci.controllers.BlockedUsers')
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.add_test_entry')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_opened(self, mock_request, mock_add_test_entry, mock_repo, mock_blocked):
"""Test webhook triggered with pull_request event with opened action."""
mock_blocked.query.filter.return_value.first.return_value = None
data = {'action': 'opened',
'pull_request': {'number': 1234, 'head': {'sha': 'abcd1234'}, 'user': {'id': 'test'}, 'draft': False}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
self.assertEqual(response.data, b'{"msg": "EOL"}')
mock_blocked.query.filter.assert_called_once_with(mock_blocked.user_id == 'test')
mock_add_test_entry.assert_called_once()
@mock.patch('mod_ci.controllers.BlockedUsers')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_invalid_action(self, mock_request, mock_repo, mock_blocked):
"""Test webhook triggered with pull_request event with an invalid action."""
data = {'action': 'invalid',
'pull_request': {'number': 1234, 'draft': False, 'head': {'sha': 'abcd1234'}, 'user': {'id': 'test'}}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
self.assertEqual(response.data, b'{"msg": "EOL"}')
mock_blocked.query.filter.assert_not_called()
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_opened_draft(self, mock_request, mock_repo):
"""Test webhook triggered with pull_request event with open action, marked as draft."""
data = {'action': 'opened',
'pull_request': {'number': 1234, 'head': {'sha': 'abcd1234'}, 'user': {'id': 'test'}, 'draft': True}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
self.assertEqual(response.data, b'{"msg": "EOL"}')
@mock.patch('github.Github.get_repo')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_pr_synchronize_draft(self, mock_request, mock_repo):
"""Test webhook triggered with pull_request event with synchronize action, marked as draft."""
data = {'action': 'synchronize',
'pull_request': {'number': 1234, 'head': {'sha': 'abcd1234'}, 'user': {'id': 'test'}, 'draft': True}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'pull_request'))
self.assertEqual(response.data, b'{"msg": "EOL"}')
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.schedule_test')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_workflow_run_requested_valid_workflow_name(self, mock_requests, mock_schedule_test, mock_repo):
"""Test webhook triggered with workflow run event with action requested with a valid workflow name."""
data = {'action': 'requested', 'workflow_run': {
'name': Workflow_builds.LINUX, 'head_sha': 'abcd1234'}}
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'workflow_run'))
self.assertEqual(response.data, b'{"msg": "EOL"}')
mock_schedule_test.assert_called_once()
@mock.patch('mod_ci.controllers.verify_artifacts_exist', return_value={'linux': True, 'windows': True})
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.queue_test')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_workflow_run_completed_successful_linux(self, mock_request, mock_queue_test,
mock_repo, mock_verify):
"""Test webhook triggered with workflow run event with action completed and status success on linux."""
data = {'action': 'completed',
'workflow_run': {'event': 'push',
'name': Workflow_builds.LINUX, 'head_sha': '1',
'head_branch': 'master'}, 'sender': {'login': 'test_owner'}}
from github.Workflow import Workflow
workflow = MagicMock(Workflow)
workflow.id = 1
workflow.name = Workflow_builds.LINUX
mock_repo.return_value.get_workflows.return_value = [workflow]
from github.WorkflowRun import WorkflowRun
workflow_run1 = MagicMock(WorkflowRun)
workflow_run1.head_sha = '1'
workflow_run1.workflow_id = 1
workflow_run1.status = 'completed'
workflow_run1.conclusion = 'success'
workflow_run1.name = Workflow_builds.LINUX
workflow_run2 = MagicMock(WorkflowRun)
workflow_run2.head_sha = '2'
mock_repo.return_value.get_workflow_runs.return_value = [workflow_run2, workflow_run1]
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'workflow_run'))
mock_queue_test.assert_called_once()
@mock.patch('mod_ci.controllers.verify_artifacts_exist', return_value={'linux': True, 'windows': True})
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.queue_test')
@mock.patch('requests.get', side_effect=mock_api_request_github)
def test_webhook_workflow_run_completed_successful_windows(self, mock_request, mock_queue_test,
mock_repo, mock_verify):
"""Test webhook triggered with workflow run event with action completed and status success on windows."""
data = {'action': 'completed',
'workflow_run': {'event': 'push',
'name': Workflow_builds.WINDOWS, 'head_sha': '1',
'head_branch': 'master'}, 'sender': {'login': 'test_owner'}}
from github.Workflow import Workflow
workflow = MagicMock(Workflow)
workflow.id = 1
workflow.name = Workflow_builds.WINDOWS
mock_repo.return_value.get_workflows.return_value = [workflow]
from github.WorkflowRun import WorkflowRun
workflow_run1 = MagicMock(WorkflowRun)
workflow_run1.head_sha = '1'
workflow_run1.workflow_id = 1
workflow_run1.status = 'completed'
workflow_run1.conclusion = 'success'
workflow_run1.name = Workflow_builds.WINDOWS
mock_repo.return_value.get_workflow_runs.return_value = [workflow_run1]
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'workflow_run'))
mock_queue_test.assert_called_once()
@mock.patch('requests.get', side_effect=mock_api_request_github)
@mock.patch('github.Github.get_repo')
@mock.patch('mod_ci.controllers.deschedule_test')
def test_webhook_workflow_run_completed_failure(self, mock_deschedule_test, mock_repo, mock_request):
"""Test webhook triggered with workflow run event with action completed and status failure."""
data = {'action': 'completed',
'workflow_run': {'event': 'push',
'name': Workflow_builds.WINDOWS, 'head_sha': '1',
'head_branch': 'master'}, 'sender': {'login': 'test_owner'}}
from github.Workflow import Workflow
workflow = MagicMock(Workflow)
workflow.id = 1
workflow.name = Workflow_builds.WINDOWS
mock_repo.return_value.get_workflows.return_value = [workflow]
from github.WorkflowRun import WorkflowRun
workflow_run1 = MagicMock(WorkflowRun)
workflow_run1.head_sha = '1'
workflow_run1.workflow_id = 1
workflow_run1.status = 'completed'
workflow_run1.conclusion = 'failure'
workflow_run1.name = Workflow_builds.WINDOWS
mock_repo.return_value.get_workflow_runs.return_value = [workflow_run1]
from github.PullRequest import PullRequest
pr = MagicMock(PullRequest)
pr.head.sha = '1'
pr.user.id = 1
pr.number = 1
mock_repo.return_value.get_pulls.return_value = [pr]
with self.app.test_client() as c:
response = c.post(
'/start-ci', environ_overrides=WSGI_ENVIRONMENT,
data=json.dumps(data), headers=self.generate_header(data, 'workflow_run'))
mock_deschedule_test.assert_called()