-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathoptions.py
7263 lines (6143 loc) · 329 KB
/
options.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 2013-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 eb command line options.
@author: Kenneth Hoste (Ghent University)
"""
import glob
import json
import os
import re
import shutil
import stat
import sys
import tempfile
import textwrap
import warnings
from easybuild.tools import LooseVersion
from unittest import TextTestRunner
import easybuild.main
import easybuild.tools.build_log
import easybuild.tools.options
import easybuild.tools.toolchain
from easybuild.base import fancylogger
from easybuild.framework.easyblock import EasyBlock
from easybuild.framework.easyconfig import BUILD, CUSTOM, DEPENDENCIES, EXTENSIONS, FILEMANAGEMENT, LICENSE
from easybuild.framework.easyconfig import MANDATORY, MODULES, OTHER, TOOLCHAIN
from easybuild.framework.easyconfig.easyconfig import EasyConfig, get_easyblock_class, robot_find_easyconfig
from easybuild.framework.easyconfig.parser import EasyConfigParser
from easybuild.tools.build_log import EasyBuildError, EasyBuildLog
from easybuild.tools.config import DEFAULT_MODULECLASSES, BuildOptions, ConfigurationVariables
from easybuild.tools.config import build_option, find_last_log, get_build_log_path, get_module_syntax, module_classes
from easybuild.tools.environment import modify_env
from easybuild.tools.filetools import adjust_permissions, change_dir, copy_dir, copy_file, download_file
from easybuild.tools.filetools import is_patch_file, mkdir, move_file, parse_http_header_fields_urlpat
from easybuild.tools.filetools import read_file, remove_dir, remove_file, which, write_file
from easybuild.tools.github import GITHUB_RAW, GITHUB_EB_MAIN, GITHUB_EASYCONFIGS_REPO
from easybuild.tools.github import URL_SEPARATOR, fetch_github_token
from easybuild.tools.module_generator import ModuleGeneratorTcl
from easybuild.tools.modules import Lmod
from easybuild.tools.options import EasyBuildOptions, opts_dict_to_eb_opts, parse_external_modules_metadata
from easybuild.tools.options import set_up_configuration, set_tmpdir, use_color
from easybuild.tools.py2vs3 import URLError, reload, sort_looseversions
from easybuild.tools.toolchain.utilities import TC_CONST_PREFIX
from easybuild.tools.run import run_cmd
from easybuild.tools.systemtools import HAVE_ARCHSPEC
from easybuild.tools.version import VERSION
from test.framework.utilities import EnhancedTestCase, TestLoaderFiltered, cleanup, init_config
try:
import pycodestyle # noqa
except ImportError:
try:
import pep8 # noqa
except ImportError:
pass
EXTERNAL_MODULES_METADATA = """[foobar/1.2.3]
name = foo, bar
version = 1.2.3, 3.2.1
prefix = FOOBAR_DIR
[foobar/2.0]
name = foobar
version = 2.0
prefix = FOOBAR_PREFIX
[foo]
name = Foo
prefix = /foo
[bar/1.2.3]
name = bar
version = 1.2.3
"""
# test account, for which a token may be available
GITHUB_TEST_ACCOUNT = 'easybuild_test'
class CommandLineOptionsTest(EnhancedTestCase):
"""Testcases for command line options."""
logfile = None
def setUp(self):
"""Set up test."""
super(CommandLineOptionsTest, self).setUp()
self.github_token = fetch_github_token(GITHUB_TEST_ACCOUNT)
self.orig_terminal_supports_colors = easybuild.tools.options.terminal_supports_colors
self.orig_os_getuid = easybuild.main.os.getuid
self.orig_experimental = easybuild.tools.build_log.EXPERIMENTAL
def tearDown(self):
"""Clean up after test."""
easybuild.main.os.getuid = self.orig_os_getuid
easybuild.tools.options.terminal_supports_colors = self.orig_terminal_supports_colors
easybuild.tools.build_log.EXPERIMENTAL = self.orig_experimental
super(CommandLineOptionsTest, self).tearDown()
def purge_environment(self):
"""Remove any leftover easybuild variables"""
for var in os.environ.keys():
# retain $EASYBUILD_IGNORECONFIGFILES, to make sure the test is isolated from system-wide config files!
if var.startswith('EASYBUILD_') and var != 'EASYBUILD_IGNORECONFIGFILES':
del os.environ[var]
def test_help_short(self, txt=None):
"""Test short help message."""
if txt is None:
topt = EasyBuildOptions(
go_args=['-h'],
go_nosystemexit=True, # when printing help, optparse ends with sys.exit
go_columns=100, # fix col size for reproducible unittest output
help_to_string=True, # don't print to stdout, but to StingIO fh,
prog='easybuildoptions_test', # generate as if called from generaloption.py
)
outtxt = topt.parser.help_to_file.getvalue()
else:
outtxt = txt
self.assertTrue(re.search(' -h ', outtxt), "Only short options included in short help")
self.assertTrue(re.search("show short help message and exit", outtxt), "Documentation included in short help")
self.assertEqual(re.search("--short-help ", outtxt), None, "Long options not included in short help")
self.assertEqual(re.search("Software search and build options", outtxt), None,
"Not all option groups included in short help (1)")
self.assertEqual(re.search("Regression test options", outtxt), None,
"Not all option groups included in short help (2)")
def test_help_long(self):
"""Test long help message."""
topt = EasyBuildOptions(
go_args=['-H'],
go_nosystemexit=True, # when printing help, optparse ends with sys.exit
go_columns=200, # fix col size for reproducible unittest output
help_to_string=True, # don't print to stdout, but to StingIO fh,
prog='easybuildoptions_test', # generate as if called from generaloption.py
)
outtxt = topt.parser.help_to_file.getvalue()
self.assertTrue(re.search("-H OUTPUT_FORMAT, --help=OUTPUT_FORMAT", outtxt),
"Long documentation expanded in long help")
self.assertTrue(re.search("show short help message and exit", outtxt),
"Documentation included in long help")
self.assertTrue(re.search("Software search and build options", outtxt),
"Not all option groups included in short help (1)")
self.assertTrue(re.search("Regression test options", outtxt),
"Not all option groups included in short help (2)")
# for boolean options, we mention in the help text how to disable them
regex = re.compile(r"default: True; disable with\s*--disable-\s*cleanup-\s*builddir", re.M)
self.assertTrue(regex.search(outtxt), "Pattern '%s' found in: %s" % (regex.pattern, outtxt))
def test_help_rst(self):
"""Test generating --help in RST output format."""
self.mock_stderr(True)
self.mock_stdout(True)
self.eb_main(['--help=rst'], raise_error=True)
stderr, stdout = self.get_stderr(), self.get_stdout()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertFalse(stderr)
patterns = [
r"^Basic options\n-------------",
r"^``--fetch``[ ]*Allow downloading sources",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(stdout), "Pattern '%s' should be found in: %s" % (regex.pattern, stdout))
def test_no_args(self):
"""Test using no arguments."""
outtxt = self.eb_main([])
error_msg = "ERROR.* Please provide one or multiple easyconfig files,"
error_msg += " or use software build options to make EasyBuild search for easyconfigs"
regex = re.compile(error_msg)
self.assertTrue(regex.search(outtxt), "Pattern '%s' found in: %s" % (regex.pattern, outtxt))
def test_debug(self):
"""Test enabling debug logging."""
error_tmpl = "%s log messages are included when using %s: %s"
for debug_arg in ['-d', '--debug']:
args = [
'nosuchfile.eb',
debug_arg,
]
outtxt = self.eb_main(args)
for log_msg_type in ['DEBUG', 'INFO', 'ERROR']:
res = re.search(' %s ' % log_msg_type, outtxt)
self.assertTrue(res, error_tmpl % (log_msg_type, debug_arg, outtxt))
def test_info(self):
"""Test enabling info logging."""
for info_arg in ['--info']:
args = [
'nosuchfile.eb',
info_arg,
]
outtxt = self.eb_main(args)
error_tmpl = "%s log messages are included when using %s ( out: %s)"
for log_msg_type in ['INFO', 'ERROR']:
res = re.search(' %s ' % log_msg_type, outtxt)
self.assertTrue(res, error_tmpl % (log_msg_type, info_arg, outtxt))
for log_msg_type in ['DEBUG']:
res = re.search(' %s ' % log_msg_type, outtxt)
self.assertTrue(not res, "%s log messages are *not* included when using %s" % (log_msg_type, info_arg))
def test_quiet(self):
"""Test enabling quiet logging (errors only)."""
for quiet_arg in ['--quiet']:
args = ['nosuchfile.eb', quiet_arg]
out = self.eb_main(args)
for log_msg_type in ['ERROR']:
res = re.search(' %s ' % log_msg_type, out)
msg = "%s log messages are included when using %s (out: %s)" % (log_msg_type, quiet_arg, out)
self.assertTrue(res, msg)
for log_msg_type in ['DEBUG', 'INFO']:
res = re.search(' %s ' % log_msg_type, out)
msg = "%s log messages are *not* included when using %s (out: %s)" % (log_msg_type, quiet_arg, out)
self.assertTrue(not res, msg)
def test_force(self):
"""Test forcing installation even if the module is already available."""
# use GCC-4.6.3.eb easyconfig file that comes with the tests
eb_file = os.path.join(os.path.dirname(__file__), 'easyconfigs', 'test_ecs', 'g', 'GCC', 'GCC-4.6.3.eb')
# check log message without --force
args = [
eb_file,
'--debug',
]
outtxt, error_thrown = self.eb_main(args, return_error=True)
error_msg = "No error is thrown if software is already installed (error_thrown: %s)" % error_thrown
self.assertTrue(not error_thrown, error_msg)
already_msg = "GCC/4.6.3 is already installed"
error_msg = "Already installed message without --force, outtxt: %s" % outtxt
self.assertTrue(re.search(already_msg, outtxt), error_msg)
# clear log file
write_file(self.logfile, '')
# check that --force and --rebuild work
for arg in ['--force', '--rebuild']:
outtxt = self.eb_main([eb_file, '--debug', arg])
self.assertTrue(not re.search(already_msg, outtxt), "Already installed message not there with %s" % arg)
def test_skip(self):
"""Test skipping installation of module (--skip, -k)."""
# use toy-0.0.eb easyconfig file that comes with the tests
topdir = os.path.abspath(os.path.dirname(__file__))
toy_ec = os.path.join(topdir, 'easyconfigs', 'test_ecs', 't', 'toy', 'toy-0.0.eb')
# check log message with --skip for existing module
args = [
toy_ec,
'--sourcepath=%s' % self.test_sourcepath,
'--buildpath=%s' % self.test_buildpath,
'--installpath=%s' % self.test_installpath,
'--force',
'--debug',
]
self.eb_main(args, do_build=True)
args.append('--skip')
self.mock_stdout(True)
outtxt = self.eb_main(args, do_build=True, verbose=True)
self.mock_stdout(False)
found_msg = "Module toy/0.0 found.\n[^\n]+Going to skip actual main build"
found = re.search(found_msg, outtxt, re.M)
self.assertTrue(found, "Module found message present with --skip, outtxt: %s" % outtxt)
# cleanup for next test
write_file(self.logfile, '')
os.chdir(self.cwd)
# check log message with --skip for non-existing module
args = [
toy_ec,
'--sourcepath=%s' % self.test_sourcepath,
'--buildpath=%s' % self.test_buildpath,
'--installpath=%s' % self.test_installpath,
'--try-software-version=1.2.3.4.5.6.7.8.9',
'--try-amend=sources=toy-0.0.tar.gz,toy-0.0.tar.gz', # hackish, but fine
'--force',
'--debug',
'--skip',
]
outtxt = self.eb_main(args, do_build=True, verbose=True)
found_msg = "Module toy/1.2.3.4.5.6.7.8.9 found."
found = re.search(found_msg, outtxt)
self.assertTrue(not found, "Module found message not there with --skip for non-existing modules: %s" % outtxt)
not_found_msg = "No module toy/1.2.3.4.5.6.7.8.9 found. Not skipping anything."
not_found = re.search(not_found_msg, outtxt)
self.assertTrue(not_found, "Module not found message there with --skip for non-existing modules: %s" % outtxt)
toy_mod_glob = os.path.join(self.test_installpath, 'modules', 'all', 'toy', '*')
for toy_mod in glob.glob(toy_mod_glob):
remove_file(toy_mod)
self.assertFalse(glob.glob(toy_mod_glob))
# make sure that sanity check is *NOT* skipped under --skip
test_ec = os.path.join(self.test_prefix, 'test.eb')
test_ec_txt = read_file(toy_ec)
regex = re.compile(r"sanity_check_paths = \{(.|\n)*\}", re.M)
test_ec_txt = regex.sub("sanity_check_paths = {'files': ['bin/nosuchfile'], 'dirs': []}", test_ec_txt)
write_file(test_ec, test_ec_txt)
args = [
test_ec,
'--skip',
'--force',
]
error_pattern = "Sanity check failed: no file found at 'bin/nosuchfile'"
self.assertErrorRegex(EasyBuildError, error_pattern, self.eb_main, args, do_build=True, raise_error=True)
# check use of skipsteps to skip sanity check
test_ec_txt += "\nskipsteps = ['sanitycheck']\n"
write_file(test_ec, test_ec_txt)
self.eb_main(args, do_build=True, raise_error=True)
self.assertEqual(len(glob.glob(toy_mod_glob)), 1)
# check use of module_only parameter
remove_dir(os.path.join(self.test_installpath, 'modules', 'all', 'toy'))
remove_dir(os.path.join(self.test_installpath, 'software', 'toy', '0.0'))
args = [
test_ec,
'--rebuild',
]
test_ec_txt += "\nmodule_only = True\n"
write_file(test_ec, test_ec_txt)
self.eb_main(args, do_build=True, raise_error=True)
self.assertEqual(len(glob.glob(toy_mod_glob)), 1)
# check that no software was installed
installdir = os.path.join(self.test_installpath, 'software', 'toy', '0.0')
installdir_glob = glob.glob(os.path.join(installdir, '*'))
easybuild_dir = os.path.join(installdir, 'easybuild')
self.assertEqual(installdir_glob, [easybuild_dir])
def test_skip_test_step(self):
"""Test skipping testing the build (--skip-test-step)."""
topdir = os.path.abspath(os.path.dirname(__file__))
toy_ec = os.path.join(topdir, 'easyconfigs', 'test_ecs', 't', 'toy', 'toy-0.0-test.eb')
# check log message without --skip-test-step
args = [
toy_ec,
'--extended-dry-run',
'--force',
'--debug',
]
self.mock_stdout(True)
outtxt = self.eb_main(args, do_build=True)
self.mock_stdout(False)
found_msg = "Running method test_step part of step test"
found = re.search(found_msg, outtxt)
test_run_msg = "execute make_test dummy_cmd as a command for running unit tests"
self.assertTrue(found, "Message about test step being run is present, outtxt: %s" % outtxt)
found = re.search(test_run_msg, outtxt)
self.assertTrue(found, "Test execution command is present, outtxt: %s" % outtxt)
# And now with the argument
args.append('--skip-test-step')
with self.mocked_stdout_stderr() as (_, stderr):
outtxt = self.eb_main(args, do_build=True)
found_msg = "Skipping test step"
found = re.search(found_msg, outtxt)
self.assertTrue(found, "Message about test step being skipped is present, outtxt: %s" % outtxt)
# Warning should be printed to stderr
self.assertIn('Will not run the test step as requested via skip-test-step', stderr.getvalue())
found = re.search(test_run_msg, outtxt)
self.assertFalse(found, "Test execution command is NOT present, outtxt: %s" % outtxt)
def test_ignore_test_failure(self):
"""Test ignore failing tests (--ignore-test-failure)."""
topdir = os.path.abspath(os.path.dirname(__file__))
# This EC uses a `runtest` command which does not exist and hence will make the test step fail
toy_ec = os.path.join(topdir, 'easyconfigs', 'test_ecs', 't', 'toy', 'toy-0.0-test.eb')
args = [toy_ec, '--ignore-test-failure', '--force']
with self.mocked_stdout_stderr() as (_, stderr):
outtxt = self.eb_main(args, do_build=True)
msg = 'Test failure ignored'
self.assertTrue(re.search(msg, outtxt),
"Ignored test failure message in log should be found, outtxt: %s" % outtxt)
self.assertTrue(re.search(msg, stderr.getvalue()),
"Ignored test failure message in stderr should be found, stderr: %s" % stderr.getvalue())
# Passing skip and ignore options is disallowed
args.append('--skip-test-step')
error_pattern = 'Found both ignore-test-failure and skip-test-step enabled'
self.assertErrorRegex(EasyBuildError, error_pattern, self.eb_main, args, do_build=True, raise_error=True)
def test_skip_sanity_check(self):
"""Test skipping of sanity check step (--skip-sanity-check)."""
topdir = os.path.abspath(os.path.dirname(__file__))
toy_ec = os.path.join(topdir, 'easyconfigs', 'test_ecs', 't', 'toy', 'toy-0.0.eb')
test_ec = os.path.join(self.test_prefix, 'test.eb')
write_file(test_ec, read_file(toy_ec) + "\nsanity_check_commands = ['this_will_fail']")
args = [test_ec, '--rebuild']
err_msg = "Sanity check failed"
self.assertErrorRegex(EasyBuildError, err_msg, self.eb_main, args, do_build=True, raise_error=True)
args.append('--skip-sanity-check')
outtext = self.eb_main(args, do_build=True, raise_error=True)
self.assertNotIn('sanity checking...', outtext)
# Passing skip and only options is disallowed
args.append('--sanity-check-only')
error_pattern = 'Found both skip-sanity-check and sanity-check-only enabled'
self.assertErrorRegex(EasyBuildError, error_pattern, self.eb_main, args, do_build=True, raise_error=True)
def test_job(self):
"""Test submitting build as a job."""
# use gzip-1.4.eb easyconfig file that comes with the tests
eb_file = os.path.join(os.path.dirname(__file__), 'easyconfigs', 'test_ecs', 'g', 'gzip', 'gzip-1.4.eb')
def check_args(job_args, passed_args=None):
"""Check whether specified args yield expected result."""
if passed_args is None:
passed_args = job_args[:]
# clear log file
write_file(self.logfile, '')
args = [
eb_file,
'--job',
] + job_args
outtxt = self.eb_main(args, raise_error=True)
job_msg = r"INFO.* Command template for jobs: .* && eb %%\(spec\)s.* %s.*\n" % ' .*'.join(passed_args)
assertmsg = "Info log msg with job command template for --job (job_msg: %s, outtxt: %s)" % (job_msg, outtxt)
self.assertTrue(re.search(job_msg, outtxt), assertmsg)
# options passed are reordered, so order here matters to make tests pass
check_args(['--debug'])
check_args(['--debug', '--stop=configure', '--try-software-name=foo'],
passed_args=['--debug', "--stop='configure'"])
check_args(['--debug', '--robot-paths=/tmp/foo:/tmp/bar'],
passed_args=['--debug', "--robot-paths='/tmp/foo:/tmp/bar'"])
# --robot has preference over --robot-paths, --robot is not passed down
check_args(['--debug', '--robot-paths=/tmp/foo', '--robot=%s' % self.test_prefix],
passed_args=['--debug', "--robot-paths='%s:/tmp/foo'" % self.test_prefix])
# 'zzz' prefix in the test name is intentional to make this test run last,
# since it fiddles with the logging infrastructure which may break things
def test_zzz_logtostdout(self):
"""Testing redirecting log to stdout."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
for stdout_arg in ['--logtostdout', '-l']:
args = [
'--software-name=somethingrandom',
'--robot', '.',
'--debug',
stdout_arg,
]
self.mock_stdout(True)
self.eb_main(args, logfile=dummylogfn)
stdout = self.get_stdout()
self.mock_stdout(False)
# make sure we restore
fancylogger.logToScreen(enable=False, stdout=True)
error_msg = "Log messages are printed to stdout when %s is used (stdout: %s)" % (stdout_arg, stdout)
self.assertTrue(len(stdout) > 100, error_msg)
topdir = os.path.dirname(os.path.abspath(__file__))
toy_ecfile = os.path.join(topdir, 'easyconfigs', 'test_ecs', 't', 'toy', 'toy-0.0.eb')
self.logfile = None
self.mock_stdout(True)
self.eb_main([toy_ecfile, '--debug', '-l', '--force'], do_build=True, raise_error=True)
stdout = self.get_stdout()
self.mock_stdout(False)
self.assertIn("Auto-enabling streaming output", stdout)
self.assertIn("== (streaming) output for command 'gcc toy.c -o toy':", stdout)
if os.path.exists(dummylogfn):
os.remove(dummylogfn)
def test_avail_easyconfig_constants(self):
"""Test listing available easyconfig file constants."""
def run_test(fmt=None):
"""Helper function to test --avail-easyconfig-constants."""
args = ['--avail-easyconfig-constants']
if fmt is not None:
args.append('--output-format=%s' % fmt)
self.mock_stderr(True)
self.mock_stdout(True)
self.eb_main(args, verbose=True, raise_error=True)
stderr, stdout = self.get_stderr(), self.get_stdout()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertFalse(stderr)
if fmt == 'rst':
pattern_lines = [
r'^``ARCH``\s*``(aarch64|ppc64le|x86_64)``\s*CPU architecture .*',
r'^``EXTERNAL_MODULE``.*',
r'^``HOME``.*',
r'``OS_NAME``.*',
r'``OS_PKG_IBVERBS_DEV``.*',
]
else:
pattern_lines = [
r'^\s*ARCH: (aarch64|ppc64le|x86_64) \(CPU architecture .*\)',
r'^\s*EXTERNAL_MODULE:.*',
r'^\s*HOME:.*',
r'\s*OS_NAME: .*',
r'\s*OS_PKG_IBVERBS_DEV: .*',
]
regex = re.compile('\n'.join(pattern_lines), re.M)
self.assertTrue(regex.search(stdout), "Pattern '%s' should match in: %s" % (regex.pattern, stdout))
for fmt in [None, 'txt', 'rst']:
run_test(fmt=fmt)
def test_avail_easyconfig_templates(self):
"""Test listing available easyconfig file templates."""
def run_test(fmt=None):
"""Helper function to test --avail-easyconfig-templates."""
args = ['--avail-easyconfig-templates']
if fmt is not None:
args.append('--output-format=%s' % fmt)
self.mock_stderr(True)
self.mock_stdout(True)
self.eb_main(args, verbose=True, raise_error=True)
stderr, stdout = self.get_stderr(), self.get_stdout()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertFalse(stderr)
if fmt == 'rst':
pattern_lines = [
r'^``%\(version_major\)s``\s+Major version\s*$',
r'^``%\(cudaver\)s``\s+full version for CUDA\s*$',
r'^``%\(cudamajver\)s``\s+major version for CUDA\s*$',
r'^``%\(pyshortver\)s``\s+short version for Python \(<major>.<minor>\)\s*$',
r'^\* ``%\(name\)s``$',
r'^``%\(namelower\)s``\s+lower case of value of name\s*$',
r'^``%\(arch\)s``\s+System architecture \(e.g. x86_64, aarch64, ppc64le, ...\)\s*$',
r'^``%\(cuda_cc_space_sep\)s``\s+Space-separated list of CUDA compute capabilities\s*$',
r'^``SOURCE_TAR_GZ``\s+Source \.tar\.gz bundle\s+``%\(name\)s-%\(version\)s.tar.gz``\s*$',
r'^``%\(software_commit\)s``\s+Git commit id to use for the software as specified '
'by --software-commit command line option',
]
else:
pattern_lines = [
r'^\s+%\(version_major\)s: Major version$',
r'^\s+%\(cudaver\)s: full version for CUDA$',
r'^\s+%\(cudamajver\)s: major version for CUDA$',
r'^\s+%\(pyshortver\)s: short version for Python \(<major>.<minor>\)$',
r'^\s+%\(name\)s$',
r'^\s+%\(namelower\)s: lower case of value of name$',
r'^\s+%\(arch\)s: System architecture \(e.g. x86_64, aarch64, ppc64le, ...\)$',
r'^\s+%\(cuda_cc_space_sep\)s: Space-separated list of CUDA compute capabilities$',
r'^\s+SOURCE_TAR_GZ: Source \.tar\.gz bundle \(%\(name\)s-%\(version\)s.tar.gz\)$',
r'^\s+%\(software_commit\)s: Git commit id to use for the software as specified '
'by --software-commit command line option',
]
for pattern_line in pattern_lines:
regex = re.compile(pattern_line, re.M)
self.assertTrue(regex.search(stdout), "Pattern '%s' should match in: %s" % (regex.pattern, stdout))
for fmt in [None, 'txt', 'rst']:
run_test(fmt=fmt)
def test_avail_easyconfig_params(self):
"""Test listing available easyconfig parameters."""
def run_test(custom=None, extra_params=[], fmt=None):
"""Inner function to run actual test in current setting."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
avail_args = [
'-a',
'--avail-easyconfig-params',
]
for avail_arg in avail_args:
# clear log
write_file(self.logfile, '')
args = [
'--unittest-file=%s' % self.logfile,
avail_arg,
]
if fmt is not None:
args.append('--output-format=%s' % fmt)
if custom is not None:
args.extend(['-e', custom])
self.eb_main(args, logfile=dummylogfn, verbose=True, raise_error=True)
logtxt = read_file(self.logfile)
# check whether all parameter types are listed
par_types = [BUILD, DEPENDENCIES, EXTENSIONS, FILEMANAGEMENT,
LICENSE, MANDATORY, MODULES, OTHER, TOOLCHAIN]
if custom is not None:
par_types.append(CUSTOM)
for param_type in [x[1] for x in par_types]:
# regex for parameter group title, matches both txt and rst formats
regex = re.compile("%s.*\n%s" % (param_type, '-' * len(param_type)), re.I)
tup = (param_type, avail_arg, args, logtxt)
msg = "Parameter type %s is featured in output of eb %s (args: %s): %s" % tup
self.assertTrue(regex.search(logtxt), msg)
ordered_params = ['name', 'toolchain', 'version', 'versionsuffix']
params = ordered_params + ['buildopts', 'sources', 'start_dir', 'dependencies', 'group',
'exts_list', 'moduleclass', 'buildstats'] + extra_params
# check a couple of easyconfig parameters
param_start = 0
for param in params:
# regex for parameter name (with optional '*') & description, matches both txt and rst formats
regex = re.compile(r"^[`]*%s(?:\*)?[`]*\s+\w+" % param, re.M)
tup = (param, avail_arg, args, regex.pattern, logtxt)
msg = "Parameter %s is listed with help in output of eb %s (args: %s, regex: %s): %s" % tup
res = regex.search(logtxt)
self.assertTrue(res, msg)
if param in ordered_params:
# check whether this parameter is listed after previous one
self.assertTrue(param_start < res.start(0), "%s is in expected order in: %s" % (param, logtxt))
param_start = res.start(0)
if os.path.exists(dummylogfn):
os.remove(dummylogfn)
for fmt in [None, 'txt', 'rst']:
run_test(fmt=fmt)
run_test(custom='EB_foo', extra_params=['foo_extra1', 'foo_extra2'], fmt=fmt)
run_test(custom='bar', extra_params=['bar_extra1', 'bar_extra2'], fmt=fmt)
run_test(custom='EB_foofoo', extra_params=['foofoo_extra1', 'foofoo_extra2'], fmt=fmt)
def test_avail_hooks(self):
"""
Test listing available hooks via --avail-hooks
"""
self.mock_stderr(True)
self.mock_stdout(True)
self.eb_main(['--avail-hooks'], verbose=True, raise_error=True)
stderr, stdout = self.get_stderr(), self.get_stdout()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertFalse(stderr)
expected = '\n'.join([
"List of supported hooks (in order of execution):",
" start_hook",
" parse_hook",
" pre_build_and_install_loop_hook",
" pre_fetch_hook",
" post_fetch_hook",
" pre_ready_hook",
" post_ready_hook",
" pre_source_hook",
" post_source_hook",
" pre_patch_hook",
" post_patch_hook",
" pre_prepare_hook",
" post_prepare_hook",
" pre_configure_hook",
" post_configure_hook",
" pre_build_hook",
" post_build_hook",
" pre_test_hook",
" post_test_hook",
" pre_install_hook",
" post_install_hook",
" pre_extensions_hook",
" pre_single_extension_hook",
" post_single_extension_hook",
" post_extensions_hook",
" pre_postiter_hook",
" post_postiter_hook",
" pre_postproc_hook",
" post_postproc_hook",
" pre_sanitycheck_hook",
" post_sanitycheck_hook",
" pre_cleanup_hook",
" post_cleanup_hook",
" pre_module_hook",
" module_write_hook",
" post_module_hook",
" pre_permissions_hook",
" post_permissions_hook",
" pre_package_hook",
" post_package_hook",
" pre_testcases_hook",
" post_testcases_hook",
" post_build_and_install_loop_hook",
" end_hook",
" cancel_hook",
" fail_hook",
" pre_run_shell_cmd_hook",
" post_run_shell_cmd_hook",
'',
])
self.assertEqual(stdout, expected)
# double underscore to make sure it runs first, which is required to detect certain types of bugs,
# e.g. running with non-initialized EasyBuild config (truly mimicing 'eb --list-toolchains')
def test__list_toolchains(self):
"""Test listing known compiler toolchains."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
args = [
'--list-toolchains',
'--unittest-file=%s' % self.logfile,
]
self.eb_main(args, logfile=dummylogfn, raise_error=True)
regex = re.compile(r"INFO List of known toolchains \(toolchain name: module\[, module, \.\.\.\]\):")
logtxt = read_file(self.logfile)
self.assertTrue(regex.search(logtxt), "Pattern '%s' should be found in: %s" % (regex.pattern, logtxt))
# toolchain elements should be in alphabetical order
tcs = {
'system': [],
'goalf': ['ATLAS', 'BLACS', 'FFTW', 'GCC', 'OpenMPI', 'ScaLAPACK'],
'intel': ['icc', 'ifort', 'imkl', 'impi'],
}
for tc, tcelems in tcs.items():
res = re.findall(r"^\s*%s: .*" % tc, logtxt, re.M)
self.assertTrue(res, "Toolchain %s is included in list of known compiler toolchains" % tc)
# every toolchain should only be mentioned once
n = len(res)
self.assertEqual(n, 1, "Toolchain %s is only mentioned once (count: %d)" % (tc, n))
# make sure definition is correct (each element only named once, in alphabetical order)
self.assertEqual("\t%s: %s" % (tc, ', '.join(tcelems)), res[0])
if os.path.exists(dummylogfn):
os.remove(dummylogfn)
def test_list_toolchains_rst(self):
"""Test --list-toolchains --output-format=rst."""
args = [
'--list-toolchains',
'--output-format=rst',
]
self.mock_stderr(True)
self.mock_stdout(True)
self.eb_main(args, raise_error=True)
stderr, stdout = self.get_stderr(), self.get_stdout().strip()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertFalse(stderr)
title = "List of known toolchains"
# separator line: starts/ends with sequence of '=', 4 spaces in between columns
sep_line = r'=(=+\s{4})+[=]+='
col_names = ['Name', r'Compiler\(s\)', 'MPI', 'Linear algebra', 'FFT']
col_names_line = r'\s+'.join(col_names) + r'\s*'
patterns = [
# title
'^' + title + '\n' + '-' * len(title) + '\n',
# header
'\n' + '\n'.join([sep_line, col_names_line, sep_line]) + '\n',
# compiler-only GCC toolchain
r"\n\*\*GCC\*\*\s+GCC\s+\*\(none\)\*\s+\*\(none\)\*\s+\*\(none\)\*\s*\n",
# gompi compiler + MPI toolchain
r"\n\*\*gompi\*\*\s+GCC\s+OpenMPI\s+\*\(none\)\*\s+\*\(none\)\*\s*\n",
# full 'foss' toolchain
r"\*\*foss\*\*\s+GCC\s+OpenMPI\s+OpenBLAS,\s+ScaLAPACK\s+FFTW\s*\n",
# compiler-only iccifort toolchain
r"\*\*iccifort\*\*\s+icc,\s+ifort\s+\*\(none\)\*\s+\*\(none\)\*\s+\*\(none\)\*\s*\n",
# full 'intel' toolchain (imkl appears twice, in linalg + FFT columns)
r"\*\*intel\*\*\s+icc,\s+ifort\s+impi\s+imkl\s+imkl\s*\n",
# fosscuda toolchain, also lists CUDA in compilers column
r"\*\*fosscuda\*\*\s+GCC,\s+CUDA\s+OpenMPI\s+OpenBLAS,\s+ScaLAPACK\s+FFTW\s*\n",
# system toolchain: 'none' in every column
r"\*\*system\*\*\s+\*\(none\)\*\s+\*\(none\)\*\s+\*\(none\)\*\s+\*\(none\)\*\s*\n",
# Cray special case
r"\n\*\*CrayGNU\*\*\s+PrgEnv-gnu\s+cray-mpich\s+cray-libsci\s+\*\(none\)\*\s*\n",
# footer
'\n' + sep_line + '$',
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(stdout), "Pattern '%s' should be found in: %s" % (regex.pattern, stdout))
def test_avail_lists(self):
"""Test listing available values of certain types."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
name_items = {
'modules-tools': ['EnvironmentModulesC', 'Lmod'],
'module-naming-schemes': ['EasyBuildMNS', 'HierarchicalMNS', 'CategorizedHMNS'],
}
for (name, items) in name_items.items():
args = [
'--avail-%s' % name,
'--unittest-file=%s' % self.logfile,
]
self.eb_main(args, logfile=dummylogfn)
logtxt = read_file(self.logfile)
words = name.replace('-', ' ')
info_msg = r"INFO List of supported %s:" % words
self.assertTrue(re.search(info_msg, logtxt), "Info message with list of available %s" % words)
for item in items:
res = re.findall(r"^\s*%s" % item, logtxt, re.M)
self.assertTrue(res, "%s is included in list of available %s" % (item, words))
# every item should only be mentioned once
n = len(res)
self.assertEqual(n, 1, "%s is only mentioned once (count: %d)" % (item, n))
if os.path.exists(dummylogfn):
os.remove(dummylogfn)
def test_avail_cfgfile_constants(self):
"""Test --avail-cfgfile-constants."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
# copy test easyconfigs to easybuild/easyconfigs subdirectory of temp directory
# to check whether easyconfigs install path is auto-included in robot path
tmpdir = tempfile.mkdtemp(prefix='easybuild-easyconfigs-pkg-install-path')
mkdir(os.path.join(tmpdir, 'easybuild'), parents=True)
test_ecs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'easyconfigs')
copy_dir(test_ecs_dir, os.path.join(tmpdir, 'easybuild', 'easyconfigs'))
orig_sys_path = sys.path[:]
sys.path.insert(0, tmpdir) # prepend to give it preference over possible other installed easyconfigs pkgs
args = [
'--avail-cfgfile-constants',
'--unittest-file=%s' % self.logfile,
]
self.eb_main(args, logfile=dummylogfn)
logtxt = read_file(self.logfile)
cfgfile_constants = {
'DEFAULT_ROBOT_PATHS': os.path.join(tmpdir, 'easybuild', 'easyconfigs'),
}
for cst_name, cst_value in cfgfile_constants.items():
cst_regex = re.compile(r"^\*\s%s:\s.*\s\[value: .*%s.*\]" % (cst_name, cst_value), re.M)
tup = (cst_regex.pattern, logtxt)
self.assertTrue(cst_regex.search(logtxt), "Pattern '%s' in --avail-cfgfile_constants output: %s" % tup)
if os.path.exists(dummylogfn):
os.remove(dummylogfn)
sys.path[:] = orig_sys_path
# use test_000_* to ensure this test is run *first*,
# before any tests that pick up additional easyblocks (which are difficult to clean up)
def test_000_list_easyblocks(self):
"""Test listing easyblock hierarchy."""
fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
os.close(fd)
# simple view
for list_arg in ['--list-easyblocks', '--list-easyblocks=simple']:
# clear log
write_file(self.logfile, '')
args = [
list_arg,
'--unittest-file=%s' % self.logfile,
]
self.eb_main(args, logfile=dummylogfn, raise_error=True)
logtxt = read_file(self.logfile)
expected = '\n'.join([
r'EasyBlock',
r'\|-- bar',
r'\|-- ConfigureMake',
r'\| \|-- MakeCp',
r'\|-- EB_EasyBuildMeta',
r'\|-- EB_FFTW',
r'\|-- EB_foo',
r'\| \|-- EB_foofoo',
r'\|-- EB_GCC',
r'\|-- EB_HPL',
r'\|-- EB_libtoy',
r'\|-- EB_OpenBLAS',
r'\|-- EB_OpenMPI',
r'\|-- EB_ScaLAPACK',
r'\|-- EB_toy_buggy',
r'\|-- ExtensionEasyBlock',
r'\| \|-- DummyExtension',
r'\| \|-- EB_toy',
r'\| \| \|-- EB_toy_eula',
r'\| \| \|-- EB_toytoy',
r'\| \|-- Toy_Extension',
r'\|-- ModuleRC',
r'\|-- PythonBundle',
r'\|-- Toolchain',
r'Extension',
r'\|-- ExtensionEasyBlock',
r'\| \|-- DummyExtension',
r'\| \|-- EB_toy',
r'\| \| \|-- EB_toy_eula',
r'\| \| \|-- EB_toytoy',
r'\| \|-- Toy_Extension',
])
regex = re.compile(expected, re.M)
self.assertTrue(regex.search(logtxt), "Pattern '%s' found in: %s" % (regex.pattern, logtxt))
# clear log
write_file(self.logfile, '')
# detailed view
args = [
'--list-easyblocks=detailed',
'--unittest-file=%s' % self.logfile,
]
self.eb_main(args, logfile=dummylogfn)
logtxt = read_file(self.logfile)
patterns = [
r"EasyBlock\s+\(easybuild.framework.easyblock\)\n",
r"\|--\s+EB_foo\s+\(easybuild.easyblocks.foo @ .*/sandbox/easybuild/easyblocks/f/foo.py\)\n" +