forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.py
1416 lines (1165 loc) · 60.9 KB
/
github.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
##
# Copyright 2012-2024 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
Unit tests for talking to GitHub.
@author: Jens Timmerman (Ghent University)
@author: Kenneth Hoste (Ghent University)
"""
import base64
import functools
import os
import random
import re
import sys
import textwrap
import unittest
from test.framework.utilities import EnhancedTestCase, TestLoaderFiltered, init_config
from time import gmtime
from unittest import TextTestRunner
import easybuild.tools.testing
from easybuild.base.rest import RestClient
from easybuild.framework.easyconfig.easyconfig import EasyConfig
from easybuild.framework.easyconfig.tools import categorize_files_by_type
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.config import build_option, module_classes, update_build_option
from easybuild.tools.configobj import ConfigObj
from easybuild.tools.filetools import read_file, write_file
from easybuild.tools.github import GITHUB_EASYCONFIGS_REPO, GITHUB_EASYBLOCKS_REPO, GITHUB_MERGEABLE_STATE_CLEAN
from easybuild.tools.github import VALID_CLOSE_PR_REASONS
from easybuild.tools.github import det_pr_title, fetch_easyconfigs_from_commit, fetch_files_from_commit
from easybuild.tools.github import is_patch_for, pick_default_branch
from easybuild.tools.testing import create_test_report, post_pr_test_report, session_state
from easybuild.tools.py2vs3 import HTTPError, URLError, ascii_letters
import easybuild.tools.github as gh
try:
import keyring
HAVE_KEYRING = True
except ImportError:
HAVE_KEYRING = False
# test account, for which a token may be available
GITHUB_TEST_ACCOUNT = 'easybuild_test'
# the user & repo to use in this test (https://github.com/easybuilders/testrepository)
GITHUB_USER = "easybuilders"
GITHUB_REPO = "testrepository"
# branch to test
GITHUB_BRANCH = 'main'
def requires_github_access():
"""Silently skip for pull requests unless $FORCE_EB_GITHUB_TESTS is set
Useful when the test uses e.g. `git` commands to download from Github and would run into rate limits
"""
if 'FORCE_EB_GITHUB_TESTS' in os.environ or os.getenv('GITHUB_EVENT_NAME') != 'pull_request':
return unittest.skipIf(False, None)
else:
# For pull requests silently skip to avoid rate limits
def decorator(test_item):
@functools.wraps(test_item)
def skip_wrapper(*args, **kwargs):
return
return skip_wrapper
return decorator
class GithubTest(EnhancedTestCase):
""" small test for The github package
This should not be to much, since there is an hourly limit of request
for non authenticated users of 50"""
def setUp(self):
"""Test setup."""
super(GithubTest, self).setUp()
self.github_token = gh.fetch_github_token(GITHUB_TEST_ACCOUNT)
if self.github_token is None:
username, token = None, None
else:
username, token = GITHUB_TEST_ACCOUNT, self.github_token
self.ghfs = gh.Githubfs(GITHUB_USER, GITHUB_REPO, GITHUB_BRANCH, username, None, token)
self.skip_github_tests = self.github_token is None and os.getenv('FORCE_EB_GITHUB_TESTS') is None
self.orig_testing_create_gist = easybuild.tools.testing.create_gist
def tearDown(self):
"""Cleanup after running test."""
easybuild.tools.testing.create_gist = self.orig_testing_create_gist
super(GithubTest, self).tearDown()
def test_det_pr_title(self):
"""Test det_pr_title function"""
# check if patches for extensions are found
rawtxt = textwrap.dedent("""
easyblock = 'ConfigureMake'
name = '%s'
version = '%s'
homepage = 'http://foo.com/'
description = ''
toolchain = {'name': '%s', 'version': '%s'}
moduleclass = '%s'
%s
""")
# 1 easyconfig, with no versionsuffix
ecs = []
ecs.append(EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools', '')))
self.assertEqual(det_pr_title(ecs), '{tools}[GCC/11.2.0] prog v1')
# 2 easyconfigs, with no versionsuffixes
ecs.append(EasyConfig(None, rawtxt=rawtxt % ('otherprog', '2', 'GCCcore', '11.2.0', 'lib', '')))
self.assertEqual(det_pr_title(ecs), '{lib,tools}[GCC/11.2.0,GCCcore/11.2.0] prog v1, otherprog v2')
# 3 easyconfigs, with no versionsuffixes
ecs.append(EasyConfig(None, rawtxt=rawtxt % ('extraprog', '3', 'foss', '2022a', 'astro', '')))
self.assertEqual(det_pr_title(ecs),
'{astro,lib,tools}[GCC/11.2.0,GCCcore/11.2.0,foss/2022a] prog v1, otherprog v2, extraprog v3')
# 2 easyconfigs for the same prog, with no versionsuffixes
ecs[1] = EasyConfig(None, rawtxt=rawtxt % ('prog', '2', 'GCC', '11.3.0', 'tools', ''))
ecs.pop(2)
self.assertEqual(det_pr_title(ecs), '{tools}[GCC/11.2.0,GCC/11.3.0] prog v1, prog v2')
# 1 easyconfig, with versionsuffix
ecs = []
ecs.append(EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-Python-3.10.4"')))
self.assertEqual(det_pr_title(ecs), '{tools}[GCC/11.2.0] prog v1 w/ Python 3.10.4')
# 1 easyconfig, with versionsuffix
ecs[0] = EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-Python-3.10.4-CUDA-11.3.1"'))
self.assertEqual(det_pr_title(ecs), '{tools}[GCC/11.2.0] prog v1 w/ Python 3.10.4 CUDA 11.3.1')
# 2 easyconfigs, with same versionsuffix
ecs[0] = EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-Python-3.10.4"'))
ecs.append(EasyConfig(None, rawtxt=rawtxt % ('prog', '2', 'GCC', '11.3.0', 'tools',
'versionsuffix = "-Python-3.10.4"')))
self.assertEqual(det_pr_title(ecs), '{tools}[GCC/11.2.0,GCC/11.3.0] prog v1, prog v2 w/ Python 3.10.4')
# 2 easyconfigs, with different versionsuffix
ecs[0] = EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-CUDA-11.3.1"'))
self.assertEqual(det_pr_title(ecs),
'{tools}[GCC/11.2.0,GCC/11.3.0] prog v1, prog v2 w/ CUDA 11.3.1, Python 3.10.4')
# 2 easyconfigs, with unusual versionsuffixes
ecs[0] = EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-contrib"'))
ecs[1] = EasyConfig(None, rawtxt=rawtxt % ('prog', '1', 'GCC', '11.2.0', 'tools',
'versionsuffix = "-Python-3.10.4-CUDA-11.3.1-contrib"'))
self.assertEqual(det_pr_title(ecs),
'{tools}[GCC/11.2.0] prog v1 w/ Python 3.10.4 CUDA 11.3.1 contrib, contrib')
def test_github_pick_default_branch(self):
"""Test pick_default_branch function."""
self.assertEqual(pick_default_branch('easybuilders'), 'main')
self.assertEqual(pick_default_branch('foobar'), 'master')
def test_github_walk(self):
"""test the gitubfs walk function"""
if self.skip_github_tests:
print("Skipping test_walk, no GitHub token available?")
return
try:
expected = [
(None, ['a_directory', 'second_dir'], ['README.md']),
('a_directory', ['a_subdirectory'], ['a_file.txt']),
('a_directory/a_subdirectory', [], ['a_file.txt']), ('second_dir', [], ['a_file.txt']),
]
self.assertEqual([x for x in self.ghfs.walk(None)], expected)
except IOError:
pass
def test_github_read_api(self):
"""Test the githubfs read function"""
if self.skip_github_tests:
print("Skipping test_read_api, no GitHub token available?")
return
try:
self.assertEqual(self.ghfs.read("a_directory/a_file.txt").strip(), b"this is a line of text")
except IOError:
pass
def test_github_read(self):
"""Test the githubfs read function without using the api"""
if self.skip_github_tests:
print("Skipping test_read, no GitHub token available?")
return
try:
fp = self.ghfs.read("a_directory/a_file.txt", api=False)
self.assertEqual(read_file(fp).strip(), "this is a line of text")
os.remove(fp)
except (IOError, OSError):
pass
def test_github_add_pr_labels(self):
"""Test add_pr_labels function."""
if self.skip_github_tests:
print("Skipping test_add_pr_labels, no GitHub token available?")
return
build_options = {
'pr_target_account': GITHUB_USER,
'pr_target_repo': GITHUB_EASYBLOCKS_REPO,
'github_user': GITHUB_TEST_ACCOUNT,
'dry_run': True,
}
init_config(build_options=build_options)
self.mock_stdout(True)
error_pattern = "Adding labels to PRs for repositories other than easyconfigs hasn't been implemented yet"
self.assertErrorRegex(EasyBuildError, error_pattern, gh.add_pr_labels, 1)
self.mock_stdout(False)
build_options['pr_target_repo'] = GITHUB_EASYCONFIGS_REPO
init_config(build_options=build_options)
# PR #11262 includes easyconfigs that use 'dummy' toolchain,
# so we need to allow triggering deprecated behaviour
self.allow_deprecated_behaviour()
self.mock_stdout(True)
self.mock_stderr(True)
gh.add_pr_labels(11262)
stdout = self.get_stdout()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertIn("Could not determine any missing labels for PR #11262", stdout)
self.mock_stdout(True)
self.mock_stderr(True)
gh.add_pr_labels(8006) # closed, unmerged, unlabeled PR
stdout = self.get_stdout()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertIn("PR #8006 should be labelled 'update'", stdout)
def test_github_fetch_pr_data(self):
"""Test fetch_pr_data function."""
if self.skip_github_tests:
print("Skipping test_fetch_pr_data, no GitHub token available?")
return
pr_data, _ = gh.fetch_pr_data(1, GITHUB_USER, GITHUB_REPO, GITHUB_TEST_ACCOUNT)
self.assertEqual(pr_data['number'], 1)
self.assertEqual(pr_data['title'], "a pr")
self.assertFalse(any(key in pr_data for key in ['issue_comments', 'review', 'status_last_commit']))
pr_data, _ = gh.fetch_pr_data(2, GITHUB_USER, GITHUB_REPO, GITHUB_TEST_ACCOUNT, full=True)
self.assertEqual(pr_data['number'], 2)
self.assertEqual(pr_data['title'], "an open pr (do not close this please)")
self.assertTrue(pr_data['issue_comments'])
self.assertEqual(pr_data['issue_comments'][0]['body'], "this is a test")
self.assertTrue(pr_data['reviews'])
self.assertEqual(pr_data['reviews'][0]['state'], "APPROVED")
self.assertEqual(pr_data['reviews'][0]['user']['login'], 'boegel')
self.assertEqual(pr_data['status_last_commit'], None)
def test_github_list_prs(self):
"""Test list_prs function."""
if self.skip_github_tests:
print("Skipping test_list_prs, no GitHub token available?")
return
parameters = ('closed', 'created', 'asc')
init_config(build_options={'pr_target_account': GITHUB_USER,
'pr_target_repo': GITHUB_REPO})
expected = "PR #1: a pr"
self.mock_stdout(True)
output = gh.list_prs(parameters, per_page=1, github_user=GITHUB_TEST_ACCOUNT)
stdout = self.get_stdout()
self.mock_stdout(False)
self.assertTrue(stdout.startswith("== Listing PRs with parameters: "))
self.assertEqual(expected, output)
def test_github_reasons_for_closing(self):
"""Test reasons_for_closing function."""
if self.skip_github_tests:
print("Skipping test_reasons_for_closing, no GitHub token available?")
return
repo_owner = gh.GITHUB_EB_MAIN
repo_name = gh.GITHUB_EASYCONFIGS_REPO
build_options = {
'dry_run': True,
'github_user': GITHUB_TEST_ACCOUNT,
'pr_target_account': repo_owner,
'pr_target_repo': repo_name,
'robot_path': [],
}
init_config(build_options=build_options)
pr_data, _ = gh.fetch_pr_data(16080, repo_owner, repo_name, GITHUB_TEST_ACCOUNT, full=True)
self.mock_stdout(True)
self.mock_stderr(True)
# can't easily check return value, since auto-detected reasons may change over time if PR is touched
res = gh.reasons_for_closing(pr_data)
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertIsInstance(res, list)
self.assertEqual(stderr.strip(), "WARNING: Using easyconfigs from closed PR #16080")
patterns = [
"Last comment on",
"No activity since",
"* c-ares-1.18.1",
]
for pattern in patterns:
self.assertIn(pattern, stdout)
def test_github_close_pr(self):
"""Test close_pr function."""
if self.skip_github_tests:
print("Skipping test_close_pr, no GitHub token available?")
return
build_options = {
'dry_run': True,
'github_user': GITHUB_TEST_ACCOUNT,
'pr_target_account': GITHUB_USER,
'pr_target_repo': GITHUB_REPO,
}
init_config(build_options=build_options)
self.mock_stdout(True)
gh.close_pr(2, motivation_msg='just a test')
stdout = self.get_stdout()
self.mock_stdout(False)
patterns = [
"easybuilders/testrepository PR #2 was submitted by migueldiascosta",
"[DRY RUN] Adding comment to testrepository issue #2: '" +
"@migueldiascosta, this PR is being closed for the following reason(s): just a test",
"[DRY RUN] Closed easybuilders/testrepository PR #2",
]
for pattern in patterns:
self.assertIn(pattern, stdout)
retest_msg = VALID_CLOSE_PR_REASONS['retest']
self.mock_stdout(True)
gh.close_pr(2, motivation_msg=retest_msg)
stdout = self.get_stdout()
self.mock_stdout(False)
patterns = [
"easybuilders/testrepository PR #2 was submitted by migueldiascosta",
"[DRY RUN] Adding comment to testrepository issue #2: '" +
"@migueldiascosta, this PR is being closed for the following reason(s): %s" % retest_msg,
"[DRY RUN] Closed easybuilders/testrepository PR #2",
"[DRY RUN] Reopened easybuilders/testrepository PR #2",
]
for pattern in patterns:
self.assertIn(pattern, stdout)
def test_github_fetch_easyblocks_from_pr(self):
"""Test fetch_easyblocks_from_pr function."""
if self.skip_github_tests:
print("Skipping test_fetch_easyblocks_from_pr, no GitHub token available?")
return
init_config(build_options={
'pr_target_account': gh.GITHUB_EB_MAIN,
})
# PR with new easyblock plus non-easyblock file
all_ebs_pr1964 = ['lammps.py']
# PR with changed easyblock
all_ebs_pr1967 = ['siesta.py']
# PR with more than one easyblock
all_ebs_pr1949 = ['configuremake.py', 'rpackage.py']
for pr, all_ebs in [(1964, all_ebs_pr1964), (1967, all_ebs_pr1967), (1949, all_ebs_pr1949)]:
try:
tmpdir = os.path.join(self.test_prefix, 'pr%s' % pr)
eb_files = gh.fetch_easyblocks_from_pr(pr, path=tmpdir, github_user=GITHUB_TEST_ACCOUNT)
self.assertEqual(sorted(all_ebs), sorted([os.path.basename(f) for f in eb_files]))
except URLError as err:
print("Ignoring URLError '%s' in test_fetch_easyblocks_from_pr" % err)
def test_github_fetch_easyconfigs_from_pr(self):
"""Test fetch_easyconfigs_from_pr function."""
if self.skip_github_tests:
print("Skipping test_fetch_easyconfigs_from_pr, no GitHub token available?")
return
init_config(build_options={
'pr_target_account': gh.GITHUB_EB_MAIN,
})
# PR for rename of arrow to Arrow,
# see https://github.com/easybuilders/easybuild-easyconfigs/pull/8007/files
all_ecs_pr8007 = [
'Arrow-0.7.1-intel-2017b-Python-3.6.3.eb',
'bat-0.3.3-fix-pyspark.patch',
'bat-0.3.3-intel-2017b-Python-3.6.3.eb',
]
# PR where also files are patched in test/
# see https://github.com/easybuilders/easybuild-easyconfigs/pull/6587/files
all_ecs_pr6587 = [
'WIEN2k-18.1-foss-2018a.eb',
'WIEN2k-18.1-gimkl-2017a.eb',
'WIEN2k-18.1-intel-2018a.eb',
'libxc-4.2.3-foss-2018a.eb',
'libxc-4.2.3-gimkl-2017a.eb',
'libxc-4.2.3-intel-2018a.eb',
]
# PR where files are renamed
# see https://github.com/easybuilders/easybuild-easyconfigs/pull/7159/files
all_ecs_pr7159 = [
'DOLFIN-2018.1.0.post1-foss-2018a-Python-3.6.4.eb',
'OpenFOAM-5.0-20180108-foss-2018a.eb',
'OpenFOAM-5.0-20180108-intel-2018a.eb',
'OpenFOAM-6-foss-2018b.eb',
'OpenFOAM-6-intel-2018a.eb',
'OpenFOAM-v1806-foss-2018b.eb',
'PETSc-3.9.3-foss-2018a.eb',
'SCOTCH-6.0.6-foss-2018a.eb',
'SCOTCH-6.0.6-foss-2018b.eb',
'SCOTCH-6.0.6-intel-2018a.eb',
'Trilinos-12.12.1-foss-2018a-Python-3.6.4.eb'
]
for pr, all_ecs in [(8007, all_ecs_pr8007), (6587, all_ecs_pr6587), (7159, all_ecs_pr7159)]:
try:
tmpdir = os.path.join(self.test_prefix, 'pr%s' % pr)
ec_files = gh.fetch_easyconfigs_from_pr(pr, path=tmpdir, github_user=GITHUB_TEST_ACCOUNT)
self.assertEqual(sorted(all_ecs), sorted([os.path.basename(f) for f in ec_files]))
except URLError as err:
print("Ignoring URLError '%s' in test_fetch_easyconfigs_from_pr" % err)
def test_github_fetch_files_from_pr_cache(self):
"""Test caching for fetch_files_from_pr."""
if self.skip_github_tests:
print("Skipping test_fetch_files_from_pr_cache, no GitHub token available?")
return
init_config(build_options={
'pr_target_account': gh.GITHUB_EB_MAIN,
})
# clear cache first, to make sure we start with a clean slate
gh.fetch_files_from_pr.clear_cache()
self.assertFalse(gh.fetch_files_from_pr._cache)
pr7159_filenames = [
'DOLFIN-2018.1.0.post1-foss-2018a-Python-3.6.4.eb',
'OpenFOAM-5.0-20180108-foss-2018a.eb',
'OpenFOAM-5.0-20180108-intel-2018a.eb',
'OpenFOAM-6-foss-2018b.eb',
'OpenFOAM-6-intel-2018a.eb',
'OpenFOAM-v1806-foss-2018b.eb',
'PETSc-3.9.3-foss-2018a.eb',
'SCOTCH-6.0.6-foss-2018a.eb',
'SCOTCH-6.0.6-foss-2018b.eb',
'SCOTCH-6.0.6-intel-2018a.eb',
'Trilinos-12.12.1-foss-2018a-Python-3.6.4.eb'
]
pr7159_files = gh.fetch_easyconfigs_from_pr(7159, path=self.test_prefix, github_user=GITHUB_TEST_ACCOUNT)
self.assertEqual(sorted(pr7159_filenames), sorted(os.path.basename(f) for f in pr7159_files))
# check that cache has been populated for PR 7159
self.assertEqual(len(gh.fetch_files_from_pr._cache.keys()), 1)
# github_account value is None (results in using default 'easybuilders')
cache_key = (7159, None, 'easybuild-easyconfigs', self.test_prefix)
self.assertIn(cache_key, gh.fetch_files_from_pr._cache.keys())
cache_entry = gh.fetch_files_from_pr._cache[cache_key]
self.assertEqual(sorted([os.path.basename(f) for f in cache_entry]), sorted(pr7159_filenames))
# same query should return result from cache entry
res = gh.fetch_easyconfigs_from_pr(7159, path=self.test_prefix, github_user=GITHUB_TEST_ACCOUNT)
self.assertEqual(res, pr7159_files)
# inject entry in cache and check result of matching query
pr_id = 12345
tmpdir = os.path.join(self.test_prefix, 'easyblocks-pr-12345')
pr12345_files = [
os.path.join(tmpdir, 'foo.py'),
os.path.join(tmpdir, 'bar.py'),
]
for fp in pr12345_files:
write_file(fp, '')
# github_account value is None (results in using default 'easybuilders')
cache_key = (pr_id, None, 'easybuild-easyblocks', tmpdir)
gh.fetch_files_from_pr.update_cache({cache_key: pr12345_files})
res = gh.fetch_easyblocks_from_pr(12345, tmpdir)
self.assertEqual(sorted(pr12345_files), sorted(res))
def test_fetch_files_from_commit(self):
"""Test fetch_files_from_commit function."""
# easyconfigs commit to add EasyBuild-4.8.2.eb
test_commit = '7c83a553950c233943c7b0189762f8c05cfea852'
# without specifying any files/repo, default is to use easybuilders/easybuilld-easyconfigs
# and determine which files were changed in the commit
res = fetch_files_from_commit(test_commit)
self.assertEqual(len(res), 1)
ec_path = res[0]
expected_path = 'ecs_commit_7c83a553950c233943c7b0189762f8c05cfea852/e/EasyBuild/EasyBuild-4.8.2.eb'
self.assertTrue(ec_path.endswith(expected_path))
self.assertTrue(os.path.exists(ec_path))
self.assertIn("version = '4.8.2'", read_file(ec_path))
# also test downloading a specific file from easyblocks repo
# commit that enables use_pip & co in PythonPackage easyblock
test_commit = 'd6f0cd7b586108e40f7cf1f1054bb07e16718caf'
res = fetch_files_from_commit(test_commit, files=['pythonpackage.py'],
github_account='easybuilders', github_repo='easybuild-easyblocks')
self.assertEqual(len(res), 1)
self.assertIn("'use_pip': [True,", read_file(res[0]))
# test downloading with short commit, download_repo currently enforces using long commit
error_pattern = r"Specified commit SHA 7c83a55 for downloading easybuilders/easybuild-easyconfigs "
error_pattern += r"is not valid, must be full SHA-1 \(40 chars\)"
self.assertErrorRegex(EasyBuildError, error_pattern, fetch_files_from_commit, '7c83a55')
# test downloading of non-existing commit
error_pattern = r"Failed to download diff for commit c0ff33c0ff33 of easybuilders/easybuild-easyconfigs"
self.assertErrorRegex(EasyBuildError, error_pattern, fetch_files_from_commit, 'c0ff33c0ff33')
def test_fetch_easyconfigs_from_commit(self):
"""Test fetch_easyconfigs_from_commit function."""
# commit in which easyconfigs for PyTables 3.9.2 + dependencies were added
test_commit = '6515b44cd84a20fe7876cb4bdaf3c0080e688566'
# without specifying any files/repo, default is to determine which files were changed in the commit
res = fetch_easyconfigs_from_commit(test_commit)
self.assertEqual(len(res), 5)
expected_ec_filenames = ['Blosc-1.21.5-GCCcore-13.2.0.eb', 'Blosc2-2.13.2-GCCcore-13.2.0.eb',
'PyTables-3.9.2-foss-2023b.eb', 'PyTables-3.9.2_fix-find-blosc2-dep.patch',
'py-cpuinfo-9.0.0-GCCcore-13.2.0.eb']
self.assertEqual(sorted([os.path.basename(f) for f in res]), expected_ec_filenames)
for ec_path in res:
self.assertTrue(os.path.exists(ec_path))
if ec_path.endswith('.eb'):
self.assertIn("version =", read_file(ec_path))
else:
self.assertTrue(ec_path.endswith('.patch'))
# merge commit for release of EasyBuild v4.9.0
test_commit = 'bdcc586189fcb3e5a340cddebb50d0e188c63cdc'
res = fetch_easyconfigs_from_commit(test_commit, files=['RELEASE_NOTES'], path=self.test_prefix)
self.assertEqual(len(res), 1)
self.assertIn("v4.9.0 (30 December 2023)", read_file(res[0]))
def test_github_fetch_latest_commit_sha(self):
"""Test fetch_latest_commit_sha function."""
if self.skip_github_tests:
print("Skipping test_fetch_latest_commit_sha, no GitHub token available?")
return
sha = gh.fetch_latest_commit_sha('easybuild-framework', 'easybuilders', github_user=GITHUB_TEST_ACCOUNT)
self.assertTrue(re.match('^[0-9a-f]{40}$', sha))
sha = gh.fetch_latest_commit_sha('easybuild-easyblocks', 'easybuilders', github_user=GITHUB_TEST_ACCOUNT,
branch='develop')
self.assertTrue(re.match('^[0-9a-f]{40}$', sha))
def test_github_download_repo(self):
"""Test download_repo function."""
if self.skip_github_tests:
print("Skipping test_download_repo, no GitHub token available?")
return
cwd = os.getcwd()
# default: download tarball for master branch of easybuilders/easybuild-easyconfigs repo
path = gh.download_repo(path=self.test_prefix, github_user=GITHUB_TEST_ACCOUNT)
repodir = os.path.join(self.test_prefix, 'easybuilders', 'easybuild-easyconfigs-main')
self.assertTrue(os.path.samefile(path, repodir))
self.assertExists(repodir)
shafile = os.path.join(repodir, 'latest-sha')
self.assertTrue(re.match('^[0-9a-f]{40}$', read_file(shafile)))
self.assertExists(os.path.join(repodir, 'easybuild', 'easyconfigs', 'f', 'foss', 'foss-2019b.eb'))
# current directory should not have changed after calling download_repo
self.assertTrue(os.path.samefile(cwd, os.getcwd()))
# existing downloaded repo is not reperformed, except if SHA is different
account, repo, branch = 'boegel', 'easybuild-easyblocks', 'develop'
repodir = os.path.join(self.test_prefix, account, '%s-%s' % (repo, branch))
latest_sha = gh.fetch_latest_commit_sha(repo, account, branch=branch, github_user=GITHUB_TEST_ACCOUNT)
# put 'latest-sha' fail in place, check whether repo was (re)downloaded (should not)
shafile = os.path.join(repodir, 'latest-sha')
write_file(shafile, latest_sha)
path = gh.download_repo(repo=repo, branch=branch, account=account, path=self.test_prefix,
github_user=GITHUB_TEST_ACCOUNT)
self.assertTrue(os.path.samefile(path, repodir))
self.assertEqual(os.listdir(repodir), ['latest-sha'])
# remove 'latest-sha' file and verify that download was performed
os.remove(shafile)
path = gh.download_repo(repo=repo, branch=branch, account=account, path=self.test_prefix,
github_user=GITHUB_TEST_ACCOUNT)
self.assertTrue(os.path.samefile(path, repodir))
self.assertIn('easybuild', os.listdir(repodir))
self.assertTrue(re.match('^[0-9a-f]{40}$', read_file(shafile)))
self.assertExists(os.path.join(repodir, 'easybuild', 'easyblocks', '__init__.py'))
def test_github_download_repo_commit(self):
"""Test downloading repo at specific commit (which does not require any GitHub token)"""
# commit bdcc586189fcb3e5a340cddebb50d0e188c63cdc corresponds to easybuild-easyconfigs release v4.9.0
test_commit = 'bdcc586189fcb3e5a340cddebb50d0e188c63cdc'
gh.download_repo(path=self.test_prefix, commit=test_commit)
repo_path = os.path.join(self.test_prefix, 'easybuilders', 'easybuild-easyconfigs-' + test_commit)
self.assertTrue(os.path.exists(repo_path))
setup_py_txt = read_file(os.path.join(repo_path, 'setup.py'))
self.assertTrue("VERSION = '4.9.0'" in setup_py_txt)
# also check downloading non-default forked repo
test_commit = '434151c3dbf88b2382e8ead8655b4b2c01b92617'
gh.download_repo(path=self.test_prefix, account='boegel', repo='easybuild-framework', commit=test_commit)
repo_path = os.path.join(self.test_prefix, 'boegel', 'easybuild-framework-' + test_commit)
self.assertTrue(os.path.exists(repo_path))
release_notes_txt = read_file(os.path.join(repo_path, 'RELEASE_NOTES'))
self.assertTrue("v4.9.0 (30 December 2023)" in release_notes_txt)
# short commit doesn't work, must be full commit ID
self.assertErrorRegex(EasyBuildError, "Specified commit SHA bdcc586 .* is not valid", gh.download_repo,
path=self.test_prefix, commit='bdcc586')
self.assertErrorRegex(EasyBuildError, "Failed to download tarball .* commit", gh.download_repo,
path=self.test_prefix, commit='0000000000000000000000000000000000000000')
def test_install_github_token(self):
"""Test for install_github_token function."""
if self.skip_github_tests:
print("Skipping test_install_github_token, no GitHub token available?")
return
if not HAVE_KEYRING:
print("Skipping test_install_github_token, keyring module not available")
return
random_user = ''.join(random.choice(ascii_letters) for _ in range(10))
self.assertEqual(gh.fetch_github_token(random_user), None)
# poor mans mocking of getpass
# inject leading/trailing spaces to verify stripping of provided value
def fake_getpass(*args, **kwargs):
return ' ' + self.github_token + ' '
orig_getpass = gh.getpass.getpass
gh.getpass.getpass = fake_getpass
token_installed = False
try:
gh.install_github_token(random_user, silent=True)
token_installed = True
except Exception as err:
print(err)
gh.getpass.getpass = orig_getpass
token = gh.fetch_github_token(random_user)
# cleanup
if token_installed:
keyring.delete_password(gh.KEYRING_GITHUB_TOKEN, random_user)
# deliberately not using assertEqual, keep token secret!
self.assertTrue(token_installed)
self.assertTrue(token == self.github_token)
def test_validate_github_token(self):
"""Test for validate_github_token function."""
if self.skip_github_tests:
print("Skipping test_validate_github_token, no GitHub token available?")
return
if not HAVE_KEYRING:
print("Skipping test_validate_github_token, keyring module not available")
return
self.assertTrue(gh.validate_github_token(self.github_token, GITHUB_TEST_ACCOUNT))
# if a token in the old format is available, test with that too
token_old_format = os.getenv('TEST_GITHUB_TOKEN_OLD_FORMAT')
if token_old_format:
self.assertTrue(gh.validate_github_token(token_old_format, GITHUB_TEST_ACCOUNT))
# if a fine-grained token is available, test with that too
finegrained_token = os.getenv('TEST_GITHUB_TOKEN_FINEGRAINED')
if finegrained_token:
self.assertTrue(gh.validate_github_token(finegrained_token, GITHUB_TEST_ACCOUNT))
def test_github_find_easybuild_easyconfig(self):
"""Test for find_easybuild_easyconfig function"""
if self.skip_github_tests:
print("Skipping test_find_easybuild_easyconfig, no GitHub token available?")
return
path = gh.find_easybuild_easyconfig(github_user=GITHUB_TEST_ACCOUNT)
expected = os.path.join('e', 'EasyBuild', r'EasyBuild-[1-9]+\.[0-9]+\.[0-9]+\.eb')
regex = re.compile(expected)
self.assertTrue(regex.search(path), "Pattern '%s' found in '%s'" % (regex.pattern, path))
self.assertExists(path)
def test_github_find_patches(self):
""" Test for find_software_name_for_patch """
test_dir = os.path.dirname(os.path.abspath(__file__))
ec_path = os.path.join(test_dir, 'easyconfigs')
init_config(build_options={
'allow_modules_tool_mismatch': True,
'minimal_toolchains': True,
'use_existing_modules': True,
'external_modules_metadata': ConfigObj(),
'silent': True,
'valid_module_classes': module_classes(),
'validate': False,
})
self.mock_stdout(True)
ec = gh.find_software_name_for_patch('toy-0.0_fix-silly-typo-in-printf-statement.patch', [ec_path])
txt = self.get_stdout()
self.mock_stdout(False)
self.assertEqual(ec, 'toy')
reg = re.compile(r'[1-9]+ of [1-9]+ easyconfigs checked')
self.assertTrue(re.search(reg, txt))
self.assertEqual(gh.find_software_name_for_patch('test.patch', []), None)
# check behaviour of find_software_name_for_patch when non-UTF8 patch files are present (only with Python 3)
if sys.version_info[0] >= 3:
non_utf8_patch = os.path.join(self.test_prefix, 'problem.patch')
with open(non_utf8_patch, 'wb') as fp:
fp.write(bytes("+ ximage->byte_order=T1_byte_order; /* Set t1lib\xb4s byteorder */\n", 'iso_8859_1'))
self.assertEqual(gh.find_software_name_for_patch('test.patch', [self.test_prefix]), None)
def test_github_det_commit_status(self):
"""Test det_commit_status function."""
if self.skip_github_tests:
print("Skipping test_det_commit_status, no GitHub token available?")
return
# ancient commit, from Jenkins era, no commit status available anymore
commit_sha = 'ec5d6f7191676a86a18404616691796a352c5f1d'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, None)
# ancient commit with passing tests from Travis CI era (no GitHub Actions yet),
# no commit status available anymore
commit_sha = '21354990e4e6b4ca169b93d563091db4c6b2693e'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, None)
# ancient commit tested by both Travis CI and GitHub Actions, no commit status available anymore
commit_sha = '1fba8ac835d62e78cdc7988b08f4409a1570cef1'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, None)
# old commit only tested by GitHub Actions, no commit status available anymore
commit_sha = 'd7130683f02fe8284df3557f0b2fd3947c2ea153'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, None)
# commit in test repo where no CI is running at all, no None as result
commit_sha = '8456f867b03aa001fd5a6fe5a0c4300145c065dc'
res = gh.det_commit_status('easybuilders', GITHUB_REPO, commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, None)
# recent commit (2023-04-11) with cancelled checks (GitHub Actions only)
commit_sha = 'c074f0bb3110c27d9969c3d0b19dde3eca868bd4'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, 'cancelled')
# recent commit (2023-04-10) with failing checks (GitHub Actions only)
commit_sha = '1b4a45c62d7deaf19125756c46dc8f011fef66e1'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, 'failure')
# recent commit (2023-04-10) with successful checks (GitHub Actions only)
commit_sha = '56812a347acbaaa87f229fe319425020fe399647'
res = gh.det_commit_status('easybuilders', 'easybuild-easyconfigs', commit_sha, GITHUB_TEST_ACCOUNT)
self.assertEqual(res, 'success')
def test_github_check_pr_eligible_to_merge(self):
"""Test check_pr_eligible_to_merge function"""
def run_check(expected_result=False):
"""Helper function to check result of check_pr_eligible_to_merge"""
self.mock_stdout(True)
self.mock_stderr(True)
res = gh.check_pr_eligible_to_merge(pr_data)
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res, expected_result)
self.assertEqual(stdout, expected_stdout)
self.assertIn(expected_warning, stderr)
return stderr
pr_data = {
'base': {
'ref': 'main',
'repo': {
'name': 'easybuild-easyconfigs',
'owner': {'login': 'easybuilders'},
},
},
'status_last_commit': None,
'issue_comments': [],
'milestone': None,
'number': '1234',
'merged': False,
'mergeable_state': 'unknown',
'reviews': [{'state': 'CHANGES_REQUESTED', 'user': {'login': 'boegel'}},
# to check that duplicates are filtered
{'state': 'CHANGES_REQUESTED', 'user': {'login': 'boegel'}}],
}
test_result_warning_template = "* test suite passes: %s => not eligible for merging!"
expected_stdout = "Checking eligibility of easybuilders/easybuild-easyconfigs PR #1234 for merging...\n"
# target branch for PR must be develop
expected_warning = "* targets develop branch: FAILED; found 'main' => not eligible for merging!\n"
run_check()
pr_data['base']['ref'] = 'develop'
expected_stdout += "* targets develop branch: OK\n"
# test suite must PASS (not failed, pending or unknown) in Travis
tests = [
('pending', 'pending...'),
('error', '(status: error)'),
('failure', '(status: failure)'),
('foobar', '(status: foobar)'),
('', '(status: )'),
]
for status, test_result in tests:
pr_data['status_last_commit'] = status
expected_warning = test_result_warning_template % test_result
run_check()
pr_data['status_last_commit'] = 'success'
expected_stdout += "* test suite passes: OK\n"
expected_warning = ''
run_check()
# at least the last test report must be successful (and there must be one)
expected_warning = "* last test report is successful: (no test reports found) => not eligible for merging!"
run_check()
pr_data['issue_comments'] = [
{'body': "@easybuild-easyconfigs/maintainers: please review/merge?"},
{'body': "Test report by @boegel\n**SUCCESS**\nit's all good!"},
{'body': "Test report by @boegel\n**FAILED**\nnothing ever works..."},
{'body': "this is just a regular comment"},
]
expected_warning = "* last test report is successful: FAILED => not eligible for merging!"
run_check()
pr_data['issue_comments'].extend([
{'body': "yet another comment"},
{'body': "Test report by @boegel\n**SUCCESS**\nit's all good!"},
])
expected_stdout += "* last test report is successful: OK\n"
expected_warning = ''
run_check()
# approved style review by a human is required
expected_warning = "* approved review: MISSING => not eligible for merging!"
run_check()
pr_data['issue_comments'].insert(2, {'body': 'lgtm'})
run_check()
expected_warning = "* no pending change requests: FAILED (changes requested by boegel)"
expected_warning += " => not eligible for merging!"
run_check()
# if PR is approved by a different user that requested changes and that request has not been dismissed,
# the PR is still not mergeable
pr_data['reviews'].append({'state': 'APPROVED', 'user': {'login': 'not_boegel'}})
expected_stdout_saved = expected_stdout
expected_stdout += "* approved review: OK (by not_boegel)\n"
run_check()
# if the user that requested changes approves the PR, it's mergeable
pr_data['reviews'].append({'state': 'APPROVED', 'user': {'login': 'boegel'}})
expected_stdout = expected_stdout_saved + "* no pending change requests: OK\n"
expected_stdout += "* approved review: OK (by not_boegel, boegel)\n"
expected_warning = ''
run_check()
# milestone must be set
expected_warning = "* milestone is set: no milestone found => not eligible for merging!"
run_check()
pr_data['milestone'] = {'title': '3.3.1'}
expected_stdout += "* milestone is set: OK (3.3.1)\n"
# mergeable state must be clean
expected_warning = "* mergeable state is clean: FAILED (mergeable state is 'unknown')"
run_check()
pr_data['mergeable_state'] = GITHUB_MERGEABLE_STATE_CLEAN
expected_stdout += "* mergeable state is clean: OK\n"
# all checks pass, PR is eligible for merging
expected_warning = ''
self.assertEqual(run_check(True), '')
def test_github_det_pr_labels(self):
"""Test for det_pr_labels function."""
file_info = {'new_folder': [False], 'new_file_in_existing_folder': [True]}
res = gh.det_pr_labels(file_info, GITHUB_EASYCONFIGS_REPO)
self.assertEqual(res, ['update'])
file_info = {'new_folder': [True], 'new_file_in_existing_folder': [False]}
res = gh.det_pr_labels(file_info, GITHUB_EASYCONFIGS_REPO)
self.assertEqual(res, ['new'])
file_info = {'new_folder': [True, False], 'new_file_in_existing_folder': [False, True]}
res = gh.det_pr_labels(file_info, GITHUB_EASYCONFIGS_REPO)
self.assertTrue(sorted(res), ['new', 'update'])
file_info = {'new': [True]}
res = gh.det_pr_labels(file_info, GITHUB_EASYBLOCKS_REPO)
self.assertEqual(res, ['new'])
def test_github_det_patch_specs(self):
"""Test for det_patch_specs function."""
patch_paths = [os.path.join(self.test_prefix, p) for p in ['1.patch', '2.patch', '3.patch']]
file_info = {'ecs': []}
rawtxt = textwrap.dedent("""
easyblock = 'ConfigureMake'
name = 'A'
version = '42'
homepage = 'http://foo.com/'
description = ''
toolchain = {"name":"GCC", "version": "4.6.3"}
patches = ['1.patch']
""")
file_info['ecs'].append(EasyConfig(None, rawtxt=rawtxt))
rawtxt = textwrap.dedent("""
easyblock = 'ConfigureMake'
name = 'B'