-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathmodules.py
1853 lines (1522 loc) · 92 KB
/
modules.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-2025 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 modules.py.
@author: Toon Willems (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Stijn De Weirdt (Ghent University)
"""
import os
import re
import tempfile
import shutil
import stat
import sys
from test.framework.utilities import EnhancedTestCase, TestLoaderFiltered, init_config
from unittest import TextTestRunner
import easybuild.tools.modules as mod
from easybuild.framework.easyblock import EasyBlock
from easybuild.framework.easyconfig.easyconfig import EasyConfig
from easybuild.tools import LooseVersion
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.environment import modify_env
from easybuild.tools.filetools import adjust_permissions, copy_file, copy_dir, mkdir
from easybuild.tools.filetools import read_file, remove_dir, remove_file, symlink, write_file
from easybuild.tools.modules import EnvironmentModules, EnvironmentModulesC, EnvironmentModulesTcl, Lmod, NoModulesTool
from easybuild.tools.modules import curr_module_paths, get_software_libdir, get_software_root, get_software_version
from easybuild.tools.modules import invalidate_module_caches_for, modules_tool, reset_module_caches
from easybuild.tools.run import run_shell_cmd
from easybuild.tools.systemtools import get_shared_lib_ext
# number of modules included for testing purposes
TEST_MODULES_COUNT = 111
class ModulesTest(EnhancedTestCase):
"""Test cases for modules."""
def init_testmods(self, test_modules_paths=None):
"""Initialize set of test modules for test."""
if test_modules_paths is None:
test_modules_paths = [os.path.abspath(os.path.join(os.path.dirname(__file__), 'modules'))]
self.reset_modulepath(test_modules_paths)
# for Lmod, this test has to run first, to avoid that it fails;
# no modules are found if another test ran before it, but using a (very) long module path works fine interactively
def test_long_module_path(self):
"""Test dealing with a (very) long module path."""
# create a really long modules install path
tmpdir = tempfile.mkdtemp()
long_mod_path = tmpdir
subdir = 'foo'
# Lmod v5.1.5 doesn't support module paths longer than 256 characters, so stay just under that magic limit
while (len(os.path.abspath(long_mod_path)) + len(subdir)) < 240:
long_mod_path = os.path.join(long_mod_path, subdir)
# copy one of the test modules there
gcc_mod_dir = os.path.join(long_mod_path, 'GCC')
os.makedirs(gcc_mod_dir)
gcc_mod_path = os.path.join(os.path.dirname(__file__), 'modules', 'GCC', '4.6.3')
copy_file(gcc_mod_path, gcc_mod_dir)
# try and use long modules path
self.init_testmods(test_modules_paths=[long_mod_path])
ms = self.modtool.available()
self.assertEqual(ms, ['GCC/4.6.3'])
shutil.rmtree(tmpdir)
def test_run_module(self):
"""Test for ModulesTool.run_module method."""
testdir = os.path.dirname(os.path.abspath(__file__))
for key in ['EBROOTGCC', 'EBROOTOPENMPI', 'EBROOTOPENBLAS']:
os.environ.pop(key, None)
# arguments can be passed in two ways: multiple arguments, or just 1 list argument
self.modtool.run_module('load', 'GCC/6.4.0-2.28')
self.assertEqual(os.environ['EBROOTGCC'], '/prefix/software/GCC/6.4.0-2.28')
# restore original environment
modify_env(os.environ, self.orig_environ, verbose=False)
self.reset_modulepath([os.path.join(testdir, 'modules')])
self.assertNotIn('EBROOTGCC', os.environ)
self.modtool.run_module(['load', 'GCC/6.4.0-2.28'])
self.assertEqual(os.environ['EBROOTGCC'], '/prefix/software/GCC/6.4.0-2.28')
# skip tests that rely on exit codes when using EnvironmentModulesTcl modules tool,
# because it doesn't use proper exit codes
if not isinstance(self.modtool, EnvironmentModulesTcl):
# by default, exit code is checked and an error is raised if we run something that fails
error_pattern = "Module command '.*thisdoesnotmakesense' failed with exit code [1-9]"
self.assertErrorRegex(EasyBuildError, error_pattern, self.modtool.run_module, 'thisdoesnotmakesense')
# we need to use a different error pattern here with EnvironmentModulesC and
# EnvironmentModules <5.5, because a load of a non-existing module doesnt' trigger a
# non-zero exit code. it will still fail though, just differently
version = LooseVersion(self.modtool.version)
if (isinstance(self.modtool, EnvironmentModulesC)
or (isinstance(self.modtool, EnvironmentModules) and version < '5.5')):
error_pattern = "Unable to locate a modulefile for 'nosuchmodule/1.2.3'"
else:
error_pattern = "Module command '.*load nosuchmodule/1.2.3' failed with exit code [1-9]"
self.assertErrorRegex(EasyBuildError, error_pattern, self.modtool.run_module, 'load', 'nosuchmodule/1.2.3')
# we can choose to blatently ignore the exit code,
# and also disable the output check that serves as a fallback;
# we also enable return_output here, because trying to apply the environment changes produced
# by a faulty command is bound to cause trouble...
kwargs = {
'check_exit_code': False,
'check_output': False,
'return_output': True,
}
self.modtool.run_module('thisdoesnotmakesense', **kwargs)
self.modtool.run_module('load', 'nosuchmodule/1.2.3', **kwargs)
# by default, the output (stdout+stderr) produced by the command is processed;
# result is a list of useful info (module names in case of list/avail)
res = self.modtool.run_module('list')
self.assertEqual(res, [{'mod_name': 'GCC/6.4.0-2.28', 'default': None}])
res = self.modtool.run_module('avail', 'GCC/4.6.3')
self.assertIsInstance(res, list)
self.assertEqual(sorted([x['mod_name'] for x in res]), ['GCC/4.6.3'])
# loading a module produces no output, so we get an empty list
res = self.modtool.run_module('load', 'OpenMPI/2.1.2-GCC-6.4.0-2.28')
self.assertEqual(res, [])
self.assertEqual(os.environ['EBROOTOPENMPI'], '/prefix/software/OpenMPI/2.1.2-GCC-6.4.0-2.28')
# we can opt into getting back the raw output (stdout + stderr);
# in that cases, the output includes Python statements to change the environment;
# the changes that would be made by the module command are *not* applied to the environment
out = self.modtool.run_module('load', 'OpenBLAS/0.2.20-GCC-6.4.0-2.28', return_output=True)
patterns = [
r"^os.environ\[.EBROOTOPENBLAS.\]\s*=\s*./prefix/software/OpenBLAS/0.2.20-GCC-6.4.0-2.28.",
r"^os.environ\[.LOADEDMODULES.\]\s*=.*OpenBLAS/0.2.20-GCC-6.4.0-2.28",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(out), "Pattern '%s' should be found in: %s" % (regex.pattern, out))
# OpenBLAS module did *not* get loaded
self.assertNotIn('EBROOTOPENBLAS', os.environ)
res = self.modtool.list()
expected = ['GCC/6.4.0-2.28', 'OpenMPI/2.1.2-GCC-6.4.0-2.28', 'hwloc/1.11.8-GCC-6.4.0-2.28']
self.assertEqual(sorted([x['mod_name'] for x in res]), expected)
# we can also only obtain the stderr output (which contains the user-facing output),
# and just drop the stdout output (which contains the statements to change the environment)
out = self.modtool.run_module('show', 'OpenBLAS/0.2.20-GCC-6.4.0-2.28', return_stderr=True)
patterns = [
r"test/framework/modules/OpenBLAS/0.2.20-GCC-6.4.0-2.28:\s*$",
r"setenv\W+EBROOTOPENBLAS.+/prefix/software/OpenBLAS/0.2.20-GCC-6.4.0-2.28",
r"prepend[_-]path\W+LD_LIBRARY_PATH.+/prefix/software/OpenBLAS/0.2.20-GCC-6.4.0-2.28/lib",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(out), "Pattern '%s' should be found in: %s" % (regex.pattern, out))
# show method only returns user-facing output (obtained via stderr), not changes to the environment
regex = re.compile(r'^os\.environ\[', re.M)
self.assertFalse(regex.search(out), "Pattern '%s' should not be found in: %s" % (regex.pattern, out))
def test_list(self):
"""
Test running 'module list' via ModulesTool instance.
"""
# make very sure no modules are currently loaded
self.modtool.run_module('purge', '--force')
out = self.modtool.list()
self.assertEqual(out, [])
mods = ['GCC/7.3.0-2.30']
self.modtool.load(mods)
out = self.modtool.list()
self.assertEqual([x['mod_name'] for x in out], mods)
def test_avail(self):
"""Test if getting a (restricted) list of available modules works."""
self.init_testmods()
# test modules include 3 GCC modules and one GCCcore module
ms = self.modtool.available('GCC')
expected = ['GCC/12.3.0', 'GCC/4.6.3', 'GCC/4.6.4', 'GCC/6.4.0-2.28', 'GCC/7.3.0-2.30']
# ancient Tcl-only Environment Modules tool does an exact match on module name, others do prefix matching
if not isinstance(self.modtool, EnvironmentModulesTcl):
expected.extend(['GCCcore/12.3.0', 'GCCcore/6.2.0'])
self.assertEqual(ms, expected)
# test modules include one GCC/4.6.3 module
ms = self.modtool.available(mod_name='GCC/4.6.3')
self.assertEqual(ms, ['GCC/4.6.3'])
# all test modules are accounted for
ms = self.modtool.available()
version = LooseVersion(self.modtool.version)
if isinstance(self.modtool, Lmod) and version >= '5.7.5' and not version.is_prerelease('5.7.5', ['rc']):
# with recent versions of Lmod, also the hidden modules are included in the output of 'avail'
self.assertEqual(len(ms), TEST_MODULES_COUNT + 3)
self.assertIn('bzip2/.1.0.6', ms)
self.assertIn('toy/.0.0-deps', ms)
self.assertIn('OpenMPI/.2.1.2-GCC-6.4.0-2.28', ms)
elif (isinstance(self.modtool, EnvironmentModules)
and version >= '4.6.0' and not version.is_prerelease('4.6.0', ['-beta'])):
# bzip2/.1.0.6 is not there, since that's a module file in Lua syntax
self.assertEqual(len(ms), TEST_MODULES_COUNT + 2)
self.assertIn('toy/.0.0-deps', ms)
self.assertIn('OpenMPI/.2.1.2-GCC-6.4.0-2.28', ms)
else:
self.assertEqual(len(ms), TEST_MODULES_COUNT)
def test_exist(self):
"""Test if testing for module existence works."""
self.init_testmods()
self.assertEqual(self.modtool.exist(['OpenMPI/2.1.2-GCC-6.4.0-2.28']), [True])
self.assertEqual(self.modtool.exist(['OpenMPI/2.1.2-GCC-6.4.0-2.28'], skip_avail=True), [True])
self.assertEqual(self.modtool.exist(['foo/1.2.3']), [False])
self.assertEqual(self.modtool.exist(['foo/1.2.3'], skip_avail=True), [False])
# exist works on hidden modules
self.assertEqual(self.modtool.exist(['toy/.0.0-deps']), [True])
self.assertEqual(self.modtool.exist(['toy/.0.0-deps'], skip_avail=True), [True])
# also partial module names work
self.assertEqual(self.modtool.exist(['OpenMPI']), [True])
self.assertEqual(self.modtool.exist(['OpenMPI'], skip_avail=True), [True])
# but this doesn't...
self.assertEqual(self.modtool.exist(['OpenMPI/2.1.2']), [False])
self.assertEqual(self.modtool.exist(['OpenMPI/2.1.2'], skip_avail=True), [False])
# if we instruct modtool.exist not to consider partial module names, it doesn't
self.assertEqual(self.modtool.exist(['OpenMPI'], maybe_partial=False), [False])
self.assertEqual(self.modtool.exist(['OpenMPI'], maybe_partial=False, skip_avail=True), [False])
# exist works on hidden modules in Lua syntax (only with Lmod)
test_modules_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'modules'))
if isinstance(self.modtool, Lmod):
# make sure only the .lua module file is there, otherwise this test doesn't work as intended
self.assertExists(os.path.join(test_modules_path, 'bzip2', '.1.0.6.lua'))
self.assertNotExists(os.path.join(test_modules_path, 'bzip2', '.1.0.6'))
self.assertEqual(self.modtool.exist(['bzip2/.1.0.6']), [True])
# exist also works on lists of module names
# list should be sufficiently long, since for short lists 'show' is always used
mod_names = ['OpenMPI/2.1.2-GCC-6.4.0-2.28', 'foo/1.2.3', 'GCC',
'ScaLAPACK/2.0.2-gompi-2017b-OpenBLAS-0.2.20'
'ScaLAPACK/2.0.2-gompi-2018a-OpenBLAS-0.2.20',
'Compiler/GCC/6.4.0-2.28/OpenMPI/2.1.2', 'toy/.0.0-deps']
self.assertEqual(self.modtool.exist(mod_names), [True, False, True, False, True, True])
self.assertEqual(self.modtool.exist(mod_names, skip_avail=True), [True, False, True, False, True, True])
# verify whether checking for existence of a module wrapper works
self.modtool.unuse(test_modules_path)
self.modtool.use(self.test_prefix)
java_mod_dir = os.path.join(self.test_prefix, 'Java')
write_file(os.path.join(java_mod_dir, '1.8.0_181'), '#%Module')
write_file(os.path.join(self.test_prefix, 'toy', '42.1337'), '#%Module')
if self.modtool.__class__ == EnvironmentModulesC:
modulerc_tcl_txt = '\n'.join([
'#%Module',
'if {"Java/1.8" eq [module-info version Java/1.8]} {',
' module-version Java/1.8.0_181 1.8',
'}',
'if {"Java/site_default" eq [module-info version Java/site_default]} {',
' module-version Java/1.8.0_181 site_default',
'}',
])
else:
modulerc_tcl_txt = '\n'.join([
'#%Module',
'module-version Java/1.8.0_181 1.8',
'module-version Java/1.8.0_181 site_default',
'module-alias Java/Alias toy/42.1337',
# 'module-alias Java/NonExist non_existant/1', # (only) LMod has this in module avail, disable for now
'module-alias JavaAlias Java/1.8.0_181', # LMod 7+ only
])
write_file(os.path.join(java_mod_dir, '.modulerc'), modulerc_tcl_txt)
avail_mods = self.modtool.available()
self.assertIn('Java/1.8.0_181', avail_mods)
version = LooseVersion(self.modtool.version)
if isinstance(self.modtool, Lmod) and version >= '7.0' and not version.is_prerelease('7.0', ['rc']):
self.assertIn('Java/1.8', avail_mods)
self.assertIn('Java/site_default', avail_mods)
self.assertIn('JavaAlias', avail_mods)
self.assertEqual(self.modtool.exist(['JavaAlias']), [True])
self.assertEqual(self.modtool.exist(['Java/1.8', 'Java/1.8.0_181']), [True, True])
# module-version with different version suffix than the base module
self.assertEqual(self.modtool.exist(['Java/site_default']), [True])
# Check for aliases:
# - completely different nameTrue, True,
# - alias to non existant module
# Skipped for EnvironmentModulesC as module-alias not working correctly there
if self.modtool.__class__ != EnvironmentModulesC:
self.assertEqual(self.modtool.exist(['Java/Alias', 'Java/NonExist']), [True, False])
# set 'module avail' cache entries to empty lists,
# to enforce fallback to 'module show'
import easybuild.tools.modules
for key in easybuild.tools.modules.MODULE_AVAIL_CACHE:
easybuild.tools.modules.MODULE_AVAIL_CACHE[key] = []
# clear 'module show' cache, to keep control below
easybuild.tools.modules.MODULE_SHOW_CACHE.clear()
self.assertEqual(self.modtool.exist(['Java/1.8', 'Java/1.8.0_181']), [True, True])
# mimic "module-*" output produced by EnvironmentModulesC or EnvironmentModulesTcl
# mimic warning produced by Environment Modules when a symbol is defined multiple times
# see https://github.com/easybuilders/easybuild-framework/issues/3376
ml_show_java18_stderr = '\n'.join([
"module-version Java/1.8.0_181 1.8",
"WARNING: Symbolic version 'Java/1.8' already defined",
"module-version Java/1.8.0_181 1.8",
"-------------------------------------------------------------------",
"/modulefiles/lang/Java/1.8.0_181:",
"-------------------------------------------------------------------",
])
# overwrite 'module show' cache entries with output that includes extra lines
for key in easybuild.tools.modules.MODULE_SHOW_CACHE:
easybuild.tools.modules.MODULE_SHOW_CACHE[key] = ml_show_java18_stderr
self.assertEqual(self.modtool.exist(['Java/1.8', 'Java/1.8.0_181']), [True, True])
reset_module_caches()
# what if we're in an HMNS setting...
mkdir(os.path.join(self.test_prefix, 'Core'))
shutil.move(java_mod_dir, os.path.join(self.test_prefix, 'Core', 'Java'))
self.assertIn('Core/Java/1.8.0_181', self.modtool.available())
self.assertEqual(self.modtool.exist(['Core/Java/1.8.0_181']), [True])
# there's a workaround to ensure that module wrappers/aliases are recognized when they're
# being checked with the full module name (see https://github.com/TACC/Lmod/issues/446);
# that's necessary when using a hierarchical module naming scheme,
# see https://github.com/easybuilders/easybuild-framework/issues/3335
self.assertEqual(self.modtool.exist(['Core/Java/1.8', 'Core/Java/site_default']), [True, True])
# also check with .modulerc.lua for Lmod 7.8 or newer
if isinstance(self.modtool, Lmod) and version >= '7.8' and not version.is_prerelease('7.8', ['rc']):
shutil.move(os.path.join(self.test_prefix, 'Core', 'Java'), java_mod_dir)
reset_module_caches()
remove_file(os.path.join(java_mod_dir, '.modulerc'))
write_file(os.path.join(java_mod_dir, '.modulerc.lua'),
'\n'.join([
'module_version("Java/1.8.0_181", "1.8")',
'module_version("Java/1.8.0_181", "site_default")',
'module_alias("JavaAlias", "Java/1.8")',
]))
avail_mods = self.modtool.available()
self.assertIn('Java/1.8.0_181', avail_mods)
self.assertIn('Java/1.8', avail_mods)
self.assertEqual(self.modtool.exist(['Java/1.8', 'Java/1.8.0_181']), [True, True])
# check for an alias with a different version suffix than the base module
self.assertEqual(self.modtool.exist(['Java/site_default']), [True])
# And completely different name
self.assertEqual(self.modtool.exist(['JavaAlias']), [True])
reset_module_caches()
# back to HMNS setup
shutil.move(java_mod_dir, os.path.join(self.test_prefix, 'Core', 'Java'))
self.assertIn('Core/Java/1.8.0_181', self.modtool.available())
self.assertEqual(self.modtool.exist(['Core/Java/1.8.0_181']), [True])
self.assertEqual(self.modtool.exist(['Core/Java/1.8']), [True])
self.assertEqual(self.modtool.exist(['Core/Java/site_default']), [True])
# Test alias in home directory .modulerc
if isinstance(self.modtool, Lmod) and version >= '7.0' and not version.is_prerelease('7.0', ['rc']):
# Required or temporary HOME would be in MODULEPATH already
self.init_testmods()
# Sanity check: Module aliases don't exist yet
self.assertEqual(self.modtool.exist(['OpenMPI/99', 'OpenMPIAlias']), [False, False])
# Use a temporary dir, not the users HOME
os.environ['HOME'] = tempfile.mkdtemp()
reset_module_caches()
write_file(os.path.join(os.environ['HOME'], '.modulerc'), '\n'.join([
'#%Module',
'module-version OpenMPI/2.1.2-GCC-6.4.0-2.28 99',
'module-alias OpenMPIAlias OpenMPI/2.1.2-GCC-6.4.0-2.28',
]))
self.assertEqual(self.modtool.exist(['OpenMPI/99', 'OpenMPIAlias']), [True, True])
def test_load(self):
""" test if we load one module it is in the loaded_modules """
self.init_testmods()
ms = self.modtool.available()
# exclude modules not on the top level of a hierarchy
ms = [m for m in ms if not (m.startswith('Core') or m.startswith('Compiler/') or m.startswith('MPI/') or
m.startswith('CategorizedHMNS'))]
for m in ms:
self.modtool.load([m])
self.assertIn(m, self.modtool.loaded_modules())
self.modtool.purge()
# trying to load a module not on the top level of a hierarchy should fail
modnames = [
# module use on non-existent dir (Tcl-based env mods), or missing dep (Lmod)
'Compiler/GCC/6.4.0-2.28/OpenMPI/2.1.2',
# missing dep
'MPI/GCC/6.4.0-2.28/OpenMPI/2.1.2/ScaLAPACK/2.0.2-OpenBLAS-0.2.20',
]
for modname in modnames:
self.assertErrorRegex(EasyBuildError, '.*', self.modtool.load, [modname])
# by default, modules are always loaded, even if they are already loaded
self.modtool.load(['GCC/6.4.0-2.28', 'OpenMPI/2.1.2-GCC-6.4.0-2.28'])
# unset $EBROOTGCC, it should get set again later by loading GCC again
del os.environ['EBROOTGCC']
# GCC should be loaded, but should not be listed last (OpenMPI was loaded last)
loaded_modules = self.modtool.loaded_modules()
self.assertIn('GCC/6.4.0-2.28', loaded_modules)
self.assertFalse(loaded_modules[-1] == 'GCC/6.4.0-2.28')
# if GCC is loaded again, $EBROOTGCC should be set again, and GCC should be listed last
self.modtool.load(['GCC/6.4.0-2.28'])
# Environment Modules v4+ does not reload already loaded modules
if not isinstance(self.modtool, EnvironmentModules):
self.assertTrue(os.environ.get('EBROOTGCC'))
if isinstance(self.modtool, Lmod):
# order of loaded modules only changes with Lmod
self.assertEqual(self.modtool.loaded_modules()[-1], 'GCC/6.4.0-2.28')
# set things up for checking that GCC does *not* get reloaded when requested
os.environ.pop('EBROOTGCC', None)
self.modtool.load(['OpenMPI/2.1.2-GCC-6.4.0-2.28'])
if isinstance(self.modtool, Lmod):
# order of loaded modules only changes with Lmod
self.assertEqual(self.modtool.loaded_modules()[-1], 'OpenMPI/2.1.2-GCC-6.4.0-2.28')
# reloading can be disabled using allow_reload=False
self.modtool.load(['GCC/6.4.0-2.28'], allow_reload=False)
self.assertEqual(os.environ.get('EBROOTGCC'), None)
self.assertNotEqual(loaded_modules[-1], 'GCC/6.4.0-2.28')
def test_show(self):
"""Test for ModulesTool.show method."""
out = self.modtool.show('GCC/7.3.0-2.30')
patterns = [
# full path to module is included in output of 'show'
r"test/framework/modules/GCC/7.3.0-2.30:\s*$",
r"setenv\W+EBROOTGCC.+prefix/software/GCC/7.3.0-2.30",
r"^prepend[_-]path\W+PATH.+/prefix/software/GCC/7.3.0-2.30/bin",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(out), "Pattern '%s' should be found in: %s" % (regex.pattern, out))
# show method only returns user-facing output (obtained via stderr), not changes to the environment
regex = re.compile(r'^os\.environ\[', re.M)
self.assertFalse(regex.search(out), "Pattern '%s' should not be found in: %s" % (regex.pattern, out))
def test_curr_module_paths(self):
"""Test for curr_module_paths function."""
# first, create a couple of (empty) directories to use as entries in $MODULEPATH
test1 = os.path.join(self.test_prefix, 'test1')
mkdir(test1)
test2 = os.path.join(self.test_prefix, 'test2')
mkdir(test2)
test3 = os.path.join(self.test_prefix, 'test3')
mkdir(test3)
os.environ['MODULEPATH'] = ''
self.assertEqual(curr_module_paths(), [])
os.environ['MODULEPATH'] = '%s:%s:%s' % (test1, test2, test3)
self.assertEqual(curr_module_paths(), [test1, test2, test3])
# empty entries and non-existing directories are filtered out
os.environ['MODULEPATH'] = '/doesnotexist:%s::%s:' % (test2, test1)
self.assertEqual(curr_module_paths(), [test2, test1])
def test_check_module_path(self):
"""Test ModulesTool.check_module_path() method"""
# first, create a couple of (empty) directories to use as entries in $MODULEPATH
test1 = os.path.join(self.test_prefix, 'test1')
mkdir(test1)
test2 = os.path.join(self.test_prefix, 'test2')
mkdir(test2)
test3 = os.path.join(self.test_prefix, 'test3')
mkdir(test3)
os.environ['MODULEPATH'] = test1
modtool = modules_tool()
# directory where modules are installed based on current configuration is automatically added in front
mod_install_dir = os.path.join(self.test_installpath, 'modules', 'all')
self.assertEqual(modtool.mod_paths, [mod_install_dir, test1])
# if mod_paths is reset, it can be restored using check_module_path
modtool.mod_paths = None
modtool.check_module_path()
self.assertEqual(modtool.mod_paths, [mod_install_dir, test1])
# no harm done with multiple subsequent calls
modtool.check_module_path()
self.assertEqual(modtool.mod_paths, [mod_install_dir, test1])
# if $MODULEPATH is tweaked, mod_paths and $MODULEPATH can be corrected with check_module_path
os.environ['MODULEPATH'] = test2
modtool.check_module_path()
self.assertEqual(modtool.mod_paths, [mod_install_dir, test1, test2])
self.assertEqual(os.environ['MODULEPATH'], os.pathsep.join([mod_install_dir, test1, test2]))
# check behaviour if non-existing directories are included in $MODULEPATH
os.environ['MODULEPATH'] = '%s:/does/not/exist:%s' % (test3, test2)
modtool.check_module_path()
# non-existing dir is filtered from mod_paths, but stays in $MODULEPATH
self.assertEqual(modtool.mod_paths, [mod_install_dir, test1, test3, test2])
self.assertEqual(os.environ['MODULEPATH'],
os.pathsep.join([mod_install_dir, test1, test3, '/does/not/exist', test2]))
def test_check_module_path_hmns(self):
"""Test behaviour of check_module_path with HierarchicalMNS."""
# to verify that https://github.com/easybuilders/easybuild-framework/issues/3084 is fixed
# (see also https://github.com/easybuilders/easybuild-framework/issues/2226);
# this bug can be triggered by having at least one non-existing directory in $MODULEPATH,
# and using HierarchicalMNS
os.environ['EASYBUILD_MODULE_NAMING_SCHEME'] = 'HierarchicalMNS'
init_config()
top_mod_dir = os.path.join(self.test_installpath, 'modules', 'all')
core_mod_dir = os.path.join(top_mod_dir, 'Core')
mkdir(core_mod_dir, parents=True)
doesnotexist = os.path.join(self.test_prefix, 'doesnotexist')
self.assertNotExists(doesnotexist)
os.environ['MODULEPATH'] = '%s:%s' % (core_mod_dir, doesnotexist)
modtool = modules_tool()
self.assertEqual(modtool.mod_paths, [os.path.dirname(core_mod_dir), core_mod_dir])
self.assertEqual(os.environ['MODULEPATH'], '%s:%s:%s' % (top_mod_dir, core_mod_dir, doesnotexist))
# hack prepend_module_path to make sure it's not called again if check_module_path is called again;
# prepend_module_path is fairly expensive, so should be avoided,
# see https://github.com/easybuilders/easybuild-framework/issues/3084
def broken_prepend_module_path(*args, **kwargs):
raise EasyBuildError("broken prepend_module_path")
modtool.prepend_module_path = broken_prepend_module_path
# if this doesn't trigger a raised error from the hacked prepend_module_path, the bug is fixed
modtool.check_module_path()
self.assertEqual(modtool.mod_paths, [os.path.dirname(core_mod_dir), core_mod_dir])
self.assertEqual(os.environ['MODULEPATH'], '%s:%s:%s' % (top_mod_dir, core_mod_dir, doesnotexist))
def test_prepend_module_path(self):
"""Test prepend_module_path method."""
test_path = tempfile.mkdtemp(prefix=self.test_prefix)
self.modtool.prepend_module_path(test_path)
self.assertTrue(os.path.samefile(curr_module_paths()[0], test_path))
# prepending same path again is fine, no changes to $MODULEPATH
modulepath = curr_module_paths()
self.modtool.prepend_module_path(test_path)
self.assertEqual(modulepath, curr_module_paths())
# prepending path that is 'deeper down' in $MODULEPATH works, brings it back to front
test_mods_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modules')
self.assertTrue(any(os.path.samefile(test_mods_dir, p) for p in modulepath))
self.modtool.prepend_module_path(test_mods_dir)
self.assertTrue(os.path.samefile(curr_module_paths()[0], test_mods_dir))
# prepending path that is a symlink to the current head of $MODULEPATH is a no-op
modulepath = curr_module_paths()
symlink_path = os.path.join(self.test_prefix, 'symlink_modules')
os.symlink(modulepath[0], symlink_path)
self.modtool.prepend_module_path(symlink_path)
self.assertEqual(modulepath, curr_module_paths())
# test prepending with high priority
test_path_bis = tempfile.mkdtemp(prefix=self.test_prefix)
test_path_tris = tempfile.mkdtemp(prefix=self.test_prefix)
self.modtool.prepend_module_path(test_path_bis, priority=10000)
self.assertEqual(test_path_bis, curr_module_paths()[0])
# check whether prepend with priority actually works (only for Lmod)
if isinstance(self.modtool, Lmod):
self.modtool.prepend_module_path(test_path_tris)
modulepath = curr_module_paths()
self.assertEqual(test_path_bis, modulepath[0])
self.assertEqual(test_path_tris, modulepath[1])
def test_ld_library_path(self):
"""Make sure LD_LIBRARY_PATH is what it should be when loaded multiple modules."""
self.init_testmods()
testpath = '/this/is/just/a/test'
os.environ['LD_LIBRARY_PATH'] = testpath
# load module and check that previous LD_LIBRARY_PATH is still there, at the end
self.modtool.load(['GCC/4.6.3'])
self.assertTrue(re.search("%s$" % testpath, os.environ['LD_LIBRARY_PATH']))
self.modtool.purge()
# check that previous LD_LIBRARY_PATH is still there, at the end
self.assertTrue(re.search("%s$" % testpath, os.environ['LD_LIBRARY_PATH']))
self.modtool.purge()
def test_purge(self):
"""Test if purging of modules works."""
self.init_testmods()
ms = self.modtool.available()
self.modtool.load([ms[0]])
self.assertGreater(len(self.modtool.loaded_modules()), 0)
self.modtool.purge()
self.assertEqual(len(self.modtool.loaded_modules()), 0)
self.modtool.purge()
self.assertEqual(len(self.modtool.loaded_modules()), 0)
def test_get_software_root_version_libdir(self):
"""Test get_software_X functions."""
tmpdir = tempfile.mkdtemp()
test_cases = [
('GCC', 'GCC'),
('grib_api', 'GRIB_API'),
('netCDF-C++', 'NETCDFMINCPLUSPLUS'),
('Score-P', 'SCOREMINP'),
]
for (name, env_var_name) in test_cases:
# mock stuff that get_software_X functions rely on
root = os.path.join(tmpdir, name)
mkdir(os.path.join(root, 'lib'), parents=True)
os.environ['EBROOT%s' % env_var_name] = root
version = '0.0-%s' % root
os.environ['EBVERSION%s' % env_var_name] = version
self.assertEqual(get_software_root(name), root)
self.assertEqual(get_software_version(name), version)
self.assertEqual(get_software_libdir(name), 'lib')
self.assertEqual(get_software_libdir(name, full_path=True), os.path.join(root, 'lib'))
os.environ.pop('EBROOT%s' % env_var_name)
os.environ.pop('EBVERSION%s' % env_var_name)
# if only 'lib' has a library archive, use it
root = os.path.join(tmpdir, name)
mkdir(os.path.join(root, 'lib64'))
os.environ['EBROOT%s' % env_var_name] = root
def check_get_software_libdir(expected, **additional_args):
self.assertEqual(get_software_libdir(name, **additional_args), expected)
if isinstance(expected, list):
expected = [os.path.join(root, d) for d in expected]
elif expected:
expected = os.path.join(root, expected)
self.assertEqual(get_software_libdir(name, full_path=True, **additional_args), expected)
write_file(os.path.join(root, 'lib', 'libfoo.a'), 'foo')
check_get_software_libdir('lib')
remove_file(os.path.join(root, 'lib', 'libfoo.a'))
# also check vice versa with *shared* library in lib64
shlib_ext = get_shared_lib_ext()
write_file(os.path.join(root, 'lib64', 'libfoo.' + shlib_ext), 'foo')
check_get_software_libdir('lib64')
remove_file(os.path.join(root, 'lib64', 'libfoo.' + shlib_ext))
# check expected result of get_software_libdir with multiple lib subdirs
self.assertErrorRegex(EasyBuildError, "Multiple library subdirectories found.*", get_software_libdir, name)
check_get_software_libdir(only_one=False, expected=['lib', 'lib64'])
# only directories containing files in specified list should be retained
write_file(os.path.join(root, 'lib64', 'foo'), 'foo')
check_get_software_libdir(fs=['foo'], expected='lib64')
# duplicate paths due to symlink get filtered
remove_dir(os.path.join(root, 'lib64'))
symlink(os.path.join(root, 'lib'), os.path.join(root, 'lib64'))
check_get_software_libdir('lib')
# same goes for lib symlinked to lib64
remove_file(os.path.join(root, 'lib64'))
remove_dir(os.path.join(root, 'lib'))
mkdir(os.path.join(root, 'lib64'))
symlink(os.path.join(root, 'lib64'), os.path.join(root, 'lib'))
# still returns 'lib' because that's the first subdir considered
check_get_software_libdir('lib')
# clean up for previous tests
os.environ.pop('EBROOT%s' % env_var_name)
# if root/version for specified software package can not be found, these functions should return None
self.assertEqual(get_software_root(name), None)
self.assertEqual(get_software_version(name), None)
check_get_software_libdir(None)
# if no library subdir is found, get_software_libdir should return None
os.environ['EBROOTFOO'] = tmpdir
self.assertEqual(get_software_libdir('foo'), None)
self.assertEqual(get_software_libdir('foo', full_path=True), None)
os.environ.pop('EBROOTFOO')
shutil.rmtree(tmpdir)
def test_wrong_modulepath(self):
"""Test whether modules tool can deal with a broken $MODULEPATH."""
test_modules_path = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modules'))
modules_test_installpath = os.path.join(self.test_installpath, 'modules', 'all')
os.environ['MODULEPATH'] = '/some/non-existing/path:/this/doesnt/exists/anywhere:%s' % test_modules_path
init_config()
# purposely *not* using self.modtool here;
# need to check whether creating new ModulesTool instance doesn't break when $MODULEPATH contains faulty paths
modtool = modules_tool()
self.assertEqual(len(modtool.mod_paths), 2)
self.assertTrue(os.path.samefile(modtool.mod_paths[0], modules_test_installpath))
self.assertEqual(modtool.mod_paths[1], test_modules_path)
self.assertTrue(len(modtool.available()) > 0)
def test_modulefile_path(self):
"""Test modulefile_path method"""
test_dir = os.path.abspath(os.path.dirname(__file__))
gcc_mod_file = os.path.join(test_dir, 'modules', 'GCC', '6.4.0-2.28')
modtool = modules_tool()
res = modtool.modulefile_path('GCC/6.4.0-2.28')
self.assertTrue(os.path.samefile(res, gcc_mod_file))
if isinstance(self.modtool, Lmod):
res = modtool.modulefile_path('bzip2/.1.0.6')
self.assertTrue(os.path.samefile(res, os.path.join(test_dir, 'modules', 'bzip2', '.1.0.6.lua')))
res = modtool.modulefile_path('bzip2/.1.0.6', strip_ext=True)
self.assertTrue(res.endswith('test/framework/modules/bzip2/.1.0.6'))
reset_module_caches()
def test_path_to_top_of_module_tree(self):
"""Test function to determine path to top of the module tree."""
deps = ['GCC/6.4.0-2.28', 'OpenMPI/2.1.2-GCC-6.4.0-2.28']
path = self.modtool.path_to_top_of_module_tree([], 'gompi/2018a', '', deps)
self.assertEqual(path, [])
path = self.modtool.path_to_top_of_module_tree([], 'toy/.0.0-deps', '', ['gompi/2018a'])
self.assertEqual(path, [])
path = self.modtool.path_to_top_of_module_tree([], 'toy/0.0', '', [])
self.assertEqual(path, [])
def test_path_to_top_of_module_tree_hierarchical_mns(self):
"""Test function to determine path to top of the module tree for a hierarchical module naming scheme."""
ecs_dir = os.path.join(os.path.dirname(__file__), 'easyconfigs')
all_stops = [x[0] for x in EasyBlock.get_steps()]
build_options = {
'check_osdeps': False,
'robot_path': [ecs_dir],
'valid_stops': all_stops,
'validate': False,
}
os.environ['EASYBUILD_MODULE_NAMING_SCHEME'] = 'HierarchicalMNS'
init_config(build_options=build_options)
self.setup_hierarchical_modules()
mod_prefix = os.path.join(self.test_installpath, 'modules', 'all')
core = os.path.join(mod_prefix, 'Core')
init_modpaths = [core]
deps = ['GCC/6.4.0-2.28', 'OpenMPI/2.1.2', 'FFTW/3.3.7', 'OpenBLAS/0.2.20',
'ScaLAPACK/2.0.2-OpenBLAS-0.2.20']
path = self.modtool.path_to_top_of_module_tree(init_modpaths, 'foss/2018a', core, deps)
self.assertEqual(path, [])
path = self.modtool.path_to_top_of_module_tree(init_modpaths, 'GCC/6.4.0-2.28', core, [])
self.assertEqual(path, [])
# toolchain module must be loaded to determine path to top of module tree for non-Core modules
self.modtool.load(['GCC/6.4.0-2.28'])
full_mod_subdir = os.path.join(mod_prefix, 'Compiler', 'GCC', '6.4.0-2.28')
deps = ['GCC/6.4.0-2.28', 'hwloc/1.11.8']
path = self.modtool.path_to_top_of_module_tree(init_modpaths, 'OpenMPI/2.1.2', full_mod_subdir, deps)
self.assertEqual(path, ['GCC/6.4.0-2.28'])
self.modtool.load(['gompi/2018a'])
full_mod_subdir = os.path.join(mod_prefix, 'MPI', 'GCC', '6.4.0-2.28', 'OpenMPI', '2.1.2')
deps = ['GCC/6.4.0-2.28', 'OpenMPI/2.1.2']
path = self.modtool.path_to_top_of_module_tree(init_modpaths, 'FFTW/3.3.7', full_mod_subdir, deps)
self.assertEqual(path, ['OpenMPI/2.1.2', 'GCC/6.4.0-2.28'])
def test_path_to_top_of_module_tree_lua(self):
"""Test path_to_top_of_module_tree function on modules in Lua syntax."""
if isinstance(self.modtool, Lmod):
orig_modulepath = os.environ.get('MODULEPATH')
self.modtool.unuse(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modules'))
curr_modulepath = os.environ.get('MODULEPATH')
error_msg = "Incorrect $MODULEPATH value after unuse: %s (orig: %s)" % (curr_modulepath, orig_modulepath)
self.assertEqual(curr_modulepath, None, error_msg)
top_moddir = os.path.join(self.test_prefix, 'test_modules')
core_dir = os.path.join(top_moddir, 'Core')
mkdir(core_dir, parents=True)
self.modtool.use(core_dir)
self.assertTrue(os.path.samefile(os.environ.get('MODULEPATH'), core_dir))
# install toy modules in Lua syntax that are sufficient to test path_to_top_of_module_tree with
intel_mod_dir = os.path.join(top_moddir, 'Compiler', 'intel', '2016')
intel_mod = 'prepend_path("MODULEPATH", "%s")\n' % intel_mod_dir
write_file(os.path.join(core_dir, 'intel', '2016.lua'), intel_mod)
impi_mod_dir = os.path.join(top_moddir, 'MPI', 'intel', '2016', 'impi', '2016')
impi_mod = 'prepend_path("MODULEPATH", "%s")\n' % impi_mod_dir
write_file(os.path.join(intel_mod_dir, 'impi', '2016.lua'), impi_mod)
imkl_mod = 'io.stderr:write("Hi from the imkl module")\n'
write_file(os.path.join(impi_mod_dir, 'imkl', '2016.lua'), imkl_mod)
self.assertEqual(self.modtool.available(), ['intel/2016'])
imkl_deps = ['intel/2016', 'impi/2016']
# modules that compose toolchain are expected to be loaded
self.modtool.load(imkl_deps)
res = self.modtool.path_to_top_of_module_tree(core_dir, 'imkl/2016', impi_mod_dir, imkl_deps)
self.assertEqual(res, ['impi/2016', 'intel/2016'])
else:
print("Skipping test_path_to_top_of_module_tree_lua, requires Lmod as modules tool")
def test_interpret_raw_path_lua(self):
"""Test interpret_raw_path_lua method"""
self.assertEqual(self.modtool.interpret_raw_path_lua('"test"'), "test")
self.assertEqual(self.modtool.interpret_raw_path_lua('"just/a/path"'), "just/a/path")
os.environ['TEST_VAR'] = 'test123'
self.assertEqual(self.modtool.interpret_raw_path_lua('os.getenv("TEST_VAR")'), 'test123')
self.assertEqual(self.modtool.interpret_raw_path_lua('os.getenv("NO_SUCH_ENVIRONMENT_VARIABLE")'), '')
lua_str = 'pathJoin(os.getenv("TEST_VAR"), "bar")'
self.assertEqual(self.modtool.interpret_raw_path_lua(lua_str), 'test123/bar')
lua_str = 'pathJoin("foo", os.getenv("TEST_VAR"), "bar", os.getenv("TEST_VAR"))'
self.assertEqual(self.modtool.interpret_raw_path_lua(lua_str), 'foo/test123/bar/test123')
def test_interpret_raw_path_tcl(self):
"""Test interpret_raw_path_tcl method"""
self.assertEqual(self.modtool.interpret_raw_path_tcl('"test"'), "test")
self.assertEqual(self.modtool.interpret_raw_path_tcl('"just/a/path"'), "just/a/path")
os.environ['TEST_VAR'] = 'test123'
self.assertEqual(self.modtool.interpret_raw_path_tcl('$env(TEST_VAR)'), 'test123')
self.assertEqual(self.modtool.interpret_raw_path_tcl('$env(NO_SUCH_ENVIRONMENT_VARIABLE)'), '')
self.assertEqual(self.modtool.interpret_raw_path_tcl('$env(TEST_VAR)/bar'), 'test123/bar')
tcl_str = 'foo/$env(TEST_VAR)/bar/$env(TEST_VAR)'
self.assertEqual(self.modtool.interpret_raw_path_tcl(tcl_str), 'foo/test123/bar/test123')
tcl_str = '[ file join $env(TEST_VAR) "foo/bar" ]'
self.assertEqual(self.modtool.interpret_raw_path_tcl(tcl_str), 'test123/foo/bar')
def test_modpath_extensions_for(self):
"""Test modpath_extensions_for method."""
self.setup_hierarchical_modules()
mod_dir = os.path.join(self.test_installpath, 'modules', 'all')
expected = {
'GCC/6.4.0-2.28': [os.path.join(mod_dir, 'Compiler', 'GCC', '6.4.0-2.28')],
'OpenMPI/2.1.2': [os.path.join(mod_dir, 'MPI', 'GCC', '6.4.0-2.28', 'OpenMPI', '2.1.2')],
'FFTW/3.3.7': [],
}
res = self.modtool.modpath_extensions_for(['GCC/6.4.0-2.28', 'OpenMPI/2.1.2', 'FFTW/3.3.7'])
self.assertEqual(res, expected)
intel_mod_dir = os.path.join(mod_dir, 'Compiler', 'intel')
expected = {
'icc/2016.1.150-GCC-4.9.3-2.25': [os.path.join(intel_mod_dir, '2016.1.150-GCC-4.9.3-2.25')],
'ifort/2016.1.150-GCC-4.9.3-2.25': [os.path.join(intel_mod_dir, '2016.1.150-GCC-4.9.3-2.25')],
}
res = self.modtool.modpath_extensions_for(['icc/2016.1.150-GCC-4.9.3-2.25', 'ifort/2016.1.150-GCC-4.9.3-2.25'])
self.assertEqual(res, expected)
# error for non-existing modules
error_pattern = "Can't get value from a non-existing module"
self.assertErrorRegex(EasyBuildError, error_pattern, self.modtool.modpath_extensions_for, ['nosuchmodule/1.2'])
# make sure $HOME/$USER is set to something we can easily check
os.environ['HOME'] = os.path.join(self.test_prefix, 'HOME')
os.environ['USER'] = 'testuser'
mkdir(os.path.join(self.test_prefix, os.environ['USER'], 'test'), parents=True)
# test result in case conditional loads are used
test_mod = 'test-modpaths/1.2.3.4'
test_modfile = os.path.join(mod_dir, test_mod)
# only prepend-path entries for MODULEPATH and 'module use' statements are really relevant
test_modtxt = '\n'.join([
'#%Module',
'prepend-path PATH /example/bin',
" module use %s/Compiler/intel/2016.1.150-GCC-4.9.3-2.25" % mod_dir, # indented without guard
# quoted path
'module use "%s/Compiler/GCC/6.4.0-2.28"' % mod_dir,
# using prepend-path & quoted
' prepend-path MODULEPATH [ file join %s "MPI/GCC/6.4.0-2.28/OpenMPI/2.1.2" ]' % mod_dir,
# conditional 'use' on subdirectory in $HOME, e.g. when --subdir-user-modules is used
"if { [ file isdirectory $env(HOME)/modules/Compiler/GCC/6.4.0-2.28 ] } {",
' module use [ file join $env(HOME) "modules/Compiler/GCC/6.4.0-2.28" ]',
"}",
"setenv EXAMPLE example",
# more (fictional) extensions that use os.getenv
'prepend-path MODULEPATH "$env(HOME)"',
'module use "%s/$env(USER)/test"' % self.test_prefix,
])
write_file(test_modfile, test_modtxt)
expected = {
test_mod: [
os.path.join(mod_dir, 'Compiler', 'intel', '2016.1.150-GCC-4.9.3-2.25'),
os.path.join(mod_dir, 'Compiler', 'GCC', '6.4.0-2.28'),
os.path.join(mod_dir, 'MPI', 'GCC', '6.4.0-2.28', 'OpenMPI', '2.1.2'),
os.path.join(os.environ['HOME'], 'modules', 'Compiler', 'GCC', '6.4.0-2.28'),
os.environ['HOME'],
os.path.join(self.test_prefix, os.environ['USER'], 'test'),
]
}
self.assertEqual(self.modtool.modpath_extensions_for([test_mod]), expected)
# also test with module file in Lua syntax if Lmod is used as modules tool
if isinstance(self.modtool, Lmod):
test_mod = 'test-modpaths-lua/1.2.3.4'
test_modfile = os.path.join(mod_dir, test_mod + '.lua')
# only prepend_path entries for MODULEPATH are really relevant
test_modtxt = '\n'.join([
'prepend_path("PATH", "/example/bin")',
# indented without guard
' prepend_path("MODULEPATH", "%s/Compiler/intel/2016.1.150-GCC-4.9.3-2.25")' % mod_dir,
'prepend_path("MODULEPATH","%s/Compiler/GCC/6.4.0-2.28")' % mod_dir,
'prepend_path("MODULEPATH", "%s/MPI/GCC/6.4.0-2.28/OpenMPI/2.1.2")' % mod_dir,
# conditional 'use' on subdirectory in $HOME, e.g. when --subdir-user-modules is used
'if isDir(pathJoin(os.getenv("HOME"), "modules/Compiler/GCC/6.4.0-2.28")) then',
' prepend_path("MODULEPATH", pathJoin(os.getenv("HOME"), "modules/Compiler/GCC/6.4.0-2.28"))',
'end',
'setenv("EXAMPLE", "example")',
# more (fictional) extensions that use os.getenv
'prepend_path("MODULEPATH", os.getenv("HOME"))',
'prepend_path("MODULEPATH", pathJoin("%s", os.getenv("USER"), "test"))' % self.test_prefix,
])