forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
2270 lines (1898 loc) · 93.2 KB
/
run.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
# #
# -*- coding: utf-8 -*-
# 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 run.py
@author: Toon Willems (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Stijn De Weirdt (Ghent University)
"""
import contextlib
import glob
import os
import re
import signal
import string
import stat
import subprocess
import sys
import tempfile
import textwrap
import time
from concurrent.futures import ThreadPoolExecutor
from test.framework.utilities import EnhancedTestCase, TestLoaderFiltered, init_config
from unittest import TextTestRunner, mock
from easybuild.base.fancylogger import setLogLevelDebug
import easybuild.tools.asyncprocess as asyncprocess
import easybuild.tools.utilities
from easybuild.tools.build_log import EasyBuildError, init_logging, stop_logging
from easybuild.tools.config import update_build_option
from easybuild.tools.filetools import adjust_permissions, change_dir, mkdir, read_file, remove_dir, write_file
from easybuild.tools.modules import EnvironmentModules, Lmod
from easybuild.tools.run import RunShellCmdResult, RunShellCmdError, check_async_cmd, check_log_for_errors
from easybuild.tools.run import complete_cmd, fileprefix_from_cmd, get_output_from_process, parse_log_for_error
from easybuild.tools.run import run_cmd, run_cmd_qa, run_shell_cmd, subprocess_terminate
from easybuild.tools.config import ERROR, IGNORE, WARN
class RunTest(EnhancedTestCase):
""" Testcase for run module """
def setUp(self):
"""Set up test."""
super(RunTest, self).setUp()
self.orig_experimental = easybuild.tools.utilities._log.experimental
def tearDown(self):
"""Test cleanup."""
super(RunTest, self).tearDown()
# restore log.experimental
easybuild.tools.utilities._log.experimental = self.orig_experimental
def test_get_output_from_process(self):
"""Test for get_output_from_process utility function."""
# use of get_output_from_process is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
@contextlib.contextmanager
def get_proc(cmd, asynchronous=False):
if asynchronous:
proc = asyncprocess.Popen(cmd, shell=True, stdout=asyncprocess.PIPE, stderr=asyncprocess.STDOUT,
stdin=asyncprocess.PIPE, close_fds=True, executable='/bin/bash')
else:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
stdin=subprocess.PIPE, close_fds=True, executable='/bin/bash')
try:
yield proc
finally:
# Make sure to close the process and its pipes
subprocess_terminate(proc, timeout=1)
# get all output at once
with self.mocked_stdout_stderr():
with get_proc("echo hello") as proc:
out = get_output_from_process(proc)
self.assertEqual(out, 'hello\n')
# first get 100 bytes, then get the rest all at once
with self.mocked_stdout_stderr():
with get_proc("echo hello") as proc:
out = get_output_from_process(proc, read_size=100)
self.assertEqual(out, 'hello\n')
out = get_output_from_process(proc)
self.assertEqual(out, '')
# get output in small bits, keep trying to get output (which shouldn't fail)
with self.mocked_stdout_stderr():
with get_proc("echo hello") as proc:
out = get_output_from_process(proc, read_size=1)
self.assertEqual(out, 'h')
out = get_output_from_process(proc, read_size=3)
self.assertEqual(out, 'ell')
out = get_output_from_process(proc, read_size=2)
self.assertEqual(out, 'o\n')
out = get_output_from_process(proc, read_size=1)
self.assertEqual(out, '')
out = get_output_from_process(proc, read_size=10)
self.assertEqual(out, '')
out = get_output_from_process(proc)
self.assertEqual(out, '')
# can also get output asynchronously (read_size is *ignored* in that case)
async_cmd = "echo hello; read reply; echo $reply"
with self.mocked_stdout_stderr():
with get_proc(async_cmd, asynchronous=True) as proc:
out = get_output_from_process(proc, asynchronous=True)
self.assertEqual(out, 'hello\n')
asyncprocess.send_all(proc, 'test123\n')
out = get_output_from_process(proc)
self.assertEqual(out, 'test123\n')
with self.mocked_stdout_stderr():
with get_proc(async_cmd, asynchronous=True) as proc:
out = get_output_from_process(proc, asynchronous=True, read_size=1)
# read_size is ignored when getting output asynchronously, we're getting more than 1 byte!
self.assertEqual(out, 'hello\n')
asyncprocess.send_all(proc, 'test123\n')
out = get_output_from_process(proc, read_size=3)
self.assertEqual(out, 'tes')
out = get_output_from_process(proc, read_size=2)
self.assertEqual(out, 't1')
out = get_output_from_process(proc)
self.assertEqual(out, '23\n')
def test_run_cmd(self):
"""Basic test for run_cmd function."""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
with self.mocked_stdout_stderr():
(out, ec) = run_cmd("echo hello")
self.assertEqual(out, "hello\n")
# no reason echo hello could fail
self.assertEqual(ec, 0)
self.assertEqual(type(out), str)
# test running command that emits non-UTF-8 characters
# this is constructed to reproduce errors like:
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2
# UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018'
for text in [b"foo \xe2 bar", "foo \u2018 bar"]:
test_file = os.path.join(self.test_prefix, 'foo.txt')
write_file(test_file, text)
cmd = "cat %s" % test_file
with self.mocked_stdout_stderr():
(out, ec) = run_cmd(cmd)
self.assertEqual(ec, 0)
self.assertTrue(out.startswith('foo ') and out.endswith(' bar'))
self.assertEqual(type(out), str)
def test_run_shell_cmd_basic(self):
"""Basic test for run_shell_cmd function."""
os.environ['FOOBAR'] = 'foobar'
cwd = change_dir(self.test_prefix)
with self.mocked_stdout_stderr():
res = run_shell_cmd("echo hello")
self.assertEqual(res.output, "hello\n")
# no reason echo hello could fail
self.assertEqual(res.cmd, "echo hello")
self.assertEqual(res.exit_code, 0)
self.assertTrue(isinstance(res.output, str))
self.assertEqual(res.stderr, None)
self.assertTrue(res.work_dir and isinstance(res.work_dir, str))
change_dir(cwd)
del os.environ['FOOBAR']
# check on helper scripts that were generated for this command
paths = glob.glob(os.path.join(self.test_prefix, 'eb-*', 'run-shell-cmd-output', 'echo-*'))
self.assertEqual(len(paths), 1)
cmd_tmpdir = paths[0]
# check on env.sh script that can be used to set up environment in which command was run
env_script = os.path.join(cmd_tmpdir, 'env.sh')
self.assertExists(env_script)
env_script_txt = read_file(env_script)
self.assertIn("export FOOBAR=foobar", env_script_txt)
self.assertIn("history -s 'echo hello'", env_script_txt)
with self.mocked_stdout_stderr():
res = run_shell_cmd(f"source {env_script}; echo $USER; echo $FOOBAR; history")
self.assertEqual(res.exit_code, 0)
user = os.getenv('USER')
self.assertTrue(res.output.startswith(f'{user}\nfoobar\n'))
self.assertTrue(res.output.endswith("echo hello\n"))
# check on cmd.sh script that can be used to create interactive shell environment for command
cmd_script = os.path.join(cmd_tmpdir, 'cmd.sh')
self.assertExists(cmd_script)
cmd = f"{cmd_script} -c 'echo pwd: $PWD; echo $FOOBAR; echo $EB_CMD_OUT_FILE; cat $EB_CMD_OUT_FILE'"
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, fail_on_error=False)
self.assertEqual(res.exit_code, 0)
regex = re.compile("pwd: .*\nfoobar\n.*/echo-.*/out.txt\nhello$")
self.assertTrue(regex.search(res.output), f"Pattern '{regex.pattern}' should be found in {res.output}")
# check whether working directory is what's expected
regex = re.compile('^pwd: .*', re.M)
res = regex.findall(res.output)
self.assertEqual(len(res), 1)
pwd = res[0].strip()[5:]
self.assertTrue(os.path.samefile(pwd, self.test_prefix))
cmd = f"{cmd_script} -c 'module --version'"
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, fail_on_error=False)
self.assertEqual(res.exit_code, 0)
if isinstance(self.modtool, Lmod):
regex = re.compile("^Modules based on Lua: Version [0-9]", re.M)
elif isinstance(self.modtool, EnvironmentModules):
regex = re.compile("^Modules Release [0-9]", re.M)
else:
self.fail("Unknown modules tool used!")
self.assertTrue(regex.search(res.output), f"Pattern '{regex.pattern}' should be found in {res.output}")
# test running command that emits non-UTF-8 characters
# this is constructed to reproduce errors like:
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2
# UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018'
# (such errors are ignored by the 'run' implementation)
for text in [b"foo \xe2 bar", "foo \u2018 bar"]:
test_file = os.path.join(self.test_prefix, 'foo.txt')
write_file(test_file, text)
cmd = "cat %s" % test_file
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd)
self.assertEqual(res.cmd, cmd)
self.assertEqual(res.exit_code, 0)
self.assertTrue(res.output.startswith('foo ') and res.output.endswith(' bar'))
self.assertTrue(isinstance(res.output, str))
self.assertTrue(res.work_dir and isinstance(res.work_dir, str))
def test_run_shell_cmd_perl(self):
"""
Test running of Perl script via run_shell_cmd that detects type of shell
"""
perl_script = os.path.join(self.test_prefix, 'test.pl')
perl_script_txt = """#!/usr/bin/perl
# wait for input, see what happens (should not hang)
print STDOUT "foo:\n";
STDOUT->autoflush(1);
my $stdin = <STDIN>;
print "stdin: $stdin\n";
# conditional print statements below should *not* be triggered
print "stdin+stdout are terminals\n" if -t STDIN && -t STDOUT;
print "stdin is terminal\n" if -t STDIN;
print "stdout is terminal\n" if -t STDOUT;
my $ISA_TTY = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ;
print "ISA_TTY" if $ISA_TTY;
print "PS1 is set\n" if $ENV{PS1};
print "tty -s returns 0\n" if system("tty -s") == 0;
# check if parent process is a shell
my $ppid = getppid();
my $parent_cmd = `ps -p $ppid -o comm=`;
print "parent process is bash\n" if ($parent_cmd =~ '/bash$');
"""
write_file(perl_script, perl_script_txt)
adjust_permissions(perl_script, stat.S_IXUSR)
def handler(signum, _):
raise RuntimeError(f"Test for running Perl script via run_shell_cmd took too long, signal {signum}")
orig_sigalrm_handler = signal.getsignal(signal.SIGALRM)
try:
# set the signal handler and a 3-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
res = run_shell_cmd(perl_script, hidden=True)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'foo:\nstdin: \n')
res = run_shell_cmd(perl_script, hidden=True, stdin="test")
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'foo:\nstdin: test\n')
res = run_shell_cmd(perl_script, hidden=True, qa_patterns=[('foo:', 'bar')], qa_timeout=1)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'foo:\nstdin: bar\n\n')
error_pattern = "No matching questions found for current command output"
self.assertErrorRegex(EasyBuildError, error_pattern, run_shell_cmd, perl_script,
hidden=True, qa_patterns=[('bleh', 'blah')], qa_timeout=1)
finally:
# cleanup: disable the alarm + reset signal handler for SIGALRM
signal.signal(signal.SIGALRM, orig_sigalrm_handler)
signal.alarm(0)
def test_run_shell_cmd_env(self):
"""Test env option in run_shell_cmd."""
# use 'env' to define environment in which command should be run;
# with a few exceptions (like $_, $PWD) no other environment variables will be defined,
# so $HOME and $USER will not be set
cmd = "env | sort"
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, env={'FOOBAR': 'foobar', 'PATH': os.getenv('PATH')})
self.assertEqual(res.cmd, cmd)
self.assertEqual(res.exit_code, 0)
self.assertIn("FOOBAR=foobar\n", res.output)
self.assertTrue(re.search("^_=.*/env$", res.output, re.M))
for var in ('HOME', 'USER'):
self.assertFalse(re.search('^' + var + '=.*', res.output, re.M))
# check on helper scripts that were generated for this command
paths = glob.glob(os.path.join(self.test_prefix, 'eb-*', 'run-shell-cmd-output', 'env-*'))
self.assertEqual(len(paths), 1)
cmd_tmpdir = paths[0]
# set environment variable in current environment,
# this should not be set in shell environment produced by scripts
os.environ['TEST123'] = 'test123'
env_script = os.path.join(cmd_tmpdir, 'env.sh')
self.assertExists(env_script)
env_script_txt = read_file(env_script)
self.assertIn('unset "$var"', env_script_txt)
self.assertIn('unset -f "$func"', env_script_txt)
self.assertIn('\nexport FOOBAR=foobar\nexport PATH', env_script_txt)
cmd_script = os.path.join(cmd_tmpdir, 'cmd.sh')
self.assertExists(cmd_script)
with self.mocked_stdout_stderr():
res = run_shell_cmd(f"{cmd_script} -c 'echo $FOOBAR; echo TEST123:$TEST123'", fail_on_error=False)
self.assertEqual(res.exit_code, 0)
self.assertTrue(res.output.endswith('\nfoobar\nTEST123:\n'))
def test_fileprefix_from_cmd(self):
"""test simplifications from fileprefix_from_cmd."""
cmds = {
'abd123': 'abd123',
'ab"a': 'aba',
'a{:$:S@"a': 'aSa',
'cmd-with-dash': 'cmd-with-dash',
'cmd_with_underscore': 'cmd_with_underscore',
}
for cmd, expected_simplification in cmds.items():
self.assertEqual(fileprefix_from_cmd(cmd), expected_simplification)
cmds = {
'abd123': 'abd',
'ab"a': 'aba',
'0a{:$:2@"a': 'aa',
}
for cmd, expected_simplification in cmds.items():
self.assertEqual(fileprefix_from_cmd(cmd, allowed_chars=string.ascii_letters), expected_simplification)
def test_run_cmd_log(self):
"""Test logging of executed commands."""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
fd, logfile = tempfile.mkstemp(suffix='.log', prefix='eb-test-')
os.close(fd)
regex = re.compile('cmd "echo hello" exited with exit code [0-9]* and output:')
# command output is not logged by default without debug logging
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
self.assertTrue(run_cmd("echo hello"))
stop_logging(logfile)
self.assertEqual(len(regex.findall(read_file(logfile))), 0)
write_file(logfile, '')
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
self.assertTrue(run_cmd("echo hello", log_all=True))
stop_logging(logfile)
self.assertEqual(len(regex.findall(read_file(logfile))), 1)
write_file(logfile, '')
# with debugging enabled, exit code and output of command should only get logged once
setLogLevelDebug()
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
self.assertTrue(run_cmd("echo hello"))
stop_logging(logfile)
self.assertEqual(len(regex.findall(read_file(logfile))), 1)
write_file(logfile, '')
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
self.assertTrue(run_cmd("echo hello", log_all=True))
stop_logging(logfile)
self.assertEqual(len(regex.findall(read_file(logfile))), 1)
write_file(logfile, '')
# Test that we can set the directory for the logfile
log_path = os.path.join(self.test_prefix, 'chicken')
mkdir(log_path)
logfile = None
init_logging(logfile, silent=True, tmp_logdir=log_path)
logfiles = os.listdir(log_path)
self.assertEqual(len(logfiles), 1)
self.assertTrue(logfiles[0].startswith("easybuild"))
self.assertTrue(logfiles[0].endswith("log"))
def test_run_shell_cmd_log(self):
"""Test logging of executed commands with run_shell_cmd function."""
fd, logfile = tempfile.mkstemp(suffix='.log', prefix='eb-test-')
os.close(fd)
regex_start_cmd = re.compile("Running shell command 'echo hello' in /")
regex_cmd_exit = re.compile(r"Shell command completed successfully \(see output above\): echo hello")
# command output is always logged
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
res = run_shell_cmd("echo hello")
stop_logging(logfile)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'hello\n')
logtxt = read_file(logfile)
self.assertEqual(len(regex_start_cmd.findall(logtxt)), 1)
self.assertEqual(len(regex_cmd_exit.findall(logtxt)), 1)
write_file(logfile, '')
# with debugging enabled, exit code and output of command should only get logged once
setLogLevelDebug()
init_logging(logfile, silent=True)
with self.mocked_stdout_stderr():
res = run_shell_cmd("echo hello")
stop_logging(logfile)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(len(regex_start_cmd.findall(read_file(logfile))), 1)
self.assertEqual(len(regex_cmd_exit.findall(read_file(logfile))), 1)
write_file(logfile, '')
def test_run_cmd_negative_exit_code(self):
"""Test run_cmd function with command that has negative exit code."""
# use of run_cmd/run_cmd_qa is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
# define signal handler to call in case run_cmd takes too long
def handler(signum, _):
raise RuntimeError("Signal handler called with signal %s" % signum)
orig_sigalrm_handler = signal.getsignal(signal.SIGALRM)
try:
# set the signal handler and a 3-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
with self.mocked_stdout_stderr():
(_, ec) = run_cmd("kill -9 $$", log_ok=False)
self.assertEqual(ec, -9)
# reset the alarm
signal.alarm(0)
signal.alarm(3)
with self.mocked_stdout_stderr():
(_, ec) = run_cmd_qa("kill -9 $$", {}, log_ok=False)
self.assertEqual(ec, -9)
finally:
# cleanup: disable the alarm + reset signal handler for SIGALRM
signal.signal(signal.SIGALRM, orig_sigalrm_handler)
signal.alarm(0)
def test_run_shell_cmd_fail(self):
"""Test run_shell_cmd function with command that has negative exit code."""
# define signal handler to call in case run takes too long
def handler(signum, _):
raise RuntimeError("Signal handler called with signal %s" % signum)
# disable trace output for this test (so stdout remains empty)
update_build_option('trace', False)
orig_sigalrm_handler = signal.getsignal(signal.SIGALRM)
try:
# set the signal handler and a 3-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
# command to kill parent shell
cmd = "kill -9 $$"
work_dir = os.path.realpath(self.test_prefix)
change_dir(work_dir)
try:
run_shell_cmd(cmd)
self.assertFalse("This should never be reached, RunShellCmdError should occur!")
except RunShellCmdError as err:
self.assertEqual(str(err), "Shell command 'kill' failed!")
self.assertEqual(err.cmd, "kill -9 $$")
self.assertEqual(err.cmd_name, 'kill')
self.assertEqual(err.exit_code, -9)
self.assertEqual(err.work_dir, work_dir)
self.assertEqual(err.output, '')
self.assertEqual(err.stderr, None)
self.assertTrue(isinstance(err.caller_info, tuple))
self.assertEqual(len(err.caller_info), 3)
self.assertEqual(err.caller_info[0], __file__)
self.assertTrue(isinstance(err.caller_info[1], int)) # line number of calling site
self.assertEqual(err.caller_info[2], 'test_run_shell_cmd_fail')
with self.mocked_stdout_stderr() as (_, stderr):
err.print()
# check error reporting output
stderr = stderr.getvalue()
patterns = [
r"ERROR: Shell command failed!",
r"\s+full command\s* -> kill -9 \$\$",
r"\s+exit code\s* -> -9",
r"\s+working directory\s* -> " + work_dir,
r"\s+called from\s* -> 'test_run_shell_cmd_fail' function in "
r"(.|\n)*/test/(.|\n)*/run.py \(line [0-9]+\)",
r"\s+output \(stdout \+ stderr\)\s* -> (.|\n)*/run-shell-cmd-output/kill-(.|\n)*/out.txt",
r"\s+interactive shell script\s* -> (.|\n)*/run-shell-cmd-output/kill-(.|\n)*/cmd.sh",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(stderr), "Pattern '%s' should be found in: %s" % (pattern, stderr))
# check error reporting output when stdout/stderr are collected separately
try:
run_shell_cmd(cmd, split_stderr=True)
self.assertFalse("This should never be reached, RunShellCmdError should occur!")
except RunShellCmdError as err:
self.assertEqual(str(err), "Shell command 'kill' failed!")
self.assertEqual(err.cmd, "kill -9 $$")
self.assertEqual(err.cmd_name, 'kill')
self.assertEqual(err.exit_code, -9)
self.assertEqual(err.work_dir, work_dir)
self.assertEqual(err.output, '')
self.assertEqual(err.stderr, '')
self.assertTrue(isinstance(err.caller_info, tuple))
self.assertEqual(len(err.caller_info), 3)
self.assertEqual(err.caller_info[0], __file__)
self.assertTrue(isinstance(err.caller_info[1], int)) # line number of calling site
self.assertEqual(err.caller_info[2], 'test_run_shell_cmd_fail')
with self.mocked_stdout_stderr() as (_, stderr):
err.print()
# check error reporting output
stderr = stderr.getvalue()
patterns = [
r"ERROR: Shell command failed!",
r"\s+full command\s+ -> kill -9 \$\$",
r"\s+exit code\s+ -> -9",
r"\s+working directory\s+ -> " + work_dir,
r"\s+called from\s+ -> 'test_run_shell_cmd_fail' function in "
r"(.|\n)*/test/(.|\n)*/run.py \(line [0-9]+\)",
r"\s+output \(stdout\)\s+ -> (.|\n)*/run-shell-cmd-output/kill-(.|\n)*/out.txt",
r"\s+error/warnings \(stderr\)\s+ -> (.|\n)*/run-shell-cmd-output/kill-(.|\n)*/err.txt",
r"\s+interactive shell script\s* -> (.|\n)*/run-shell-cmd-output/kill-(.|\n)*/cmd.sh",
]
for pattern in patterns:
regex = re.compile(pattern, re.M)
self.assertTrue(regex.search(stderr), "Pattern '%s' should be found in: %s" % (pattern, stderr))
# no error reporting when fail_on_error is disabled
with self.mocked_stdout_stderr() as (_, stderr):
res = run_shell_cmd(cmd, fail_on_error=False)
self.assertEqual(res.exit_code, -9)
self.assertEqual(stderr.getvalue(), '')
finally:
# cleanup: disable the alarm + reset signal handler for SIGALRM
signal.signal(signal.SIGALRM, orig_sigalrm_handler)
signal.alarm(0)
def test_run_cmd_bis(self):
"""More 'complex' test for run_cmd function."""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
# a more 'complex' command to run, make sure all required output is there
with self.mocked_stdout_stderr():
(out, ec) = run_cmd("for j in `seq 1 3`; do for i in `seq 1 100`; do echo hello; done; sleep 1.4; done")
self.assertTrue(out.startswith('hello\nhello\n'))
self.assertEqual(len(out), len("hello\n" * 300))
self.assertEqual(ec, 0)
def test_run_shell_cmd_bis(self):
"""More 'complex' test for run_shell_cmd function."""
# a more 'complex' command to run, make sure all required output is there
with self.mocked_stdout_stderr():
res = run_shell_cmd("for j in `seq 1 3`; do for i in `seq 1 100`; do echo hello; done; sleep 1.4; done")
self.assertTrue(res.output.startswith('hello\nhello\n'))
self.assertEqual(len(res.output), len("hello\n" * 300))
self.assertEqual(res.exit_code, 0)
def test_run_cmd_work_dir(self):
"""
Test running command in specific directory with run_cmd function.
"""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
orig_wd = os.getcwd()
self.assertFalse(os.path.samefile(orig_wd, self.test_prefix))
test_dir = os.path.join(self.test_prefix, 'test')
for fn in ('foo.txt', 'bar.txt'):
write_file(os.path.join(test_dir, fn), 'test')
with self.mocked_stdout_stderr():
(out, ec) = run_cmd("ls | sort", path=test_dir)
self.assertEqual(ec, 0)
self.assertEqual(out, 'bar.txt\nfoo.txt\n')
self.assertTrue(os.path.samefile(orig_wd, os.getcwd()))
def test_run_shell_cmd_work_dir(self):
"""
Test running shell command in specific directory with run_shell_cmd function.
"""
test_dir = os.path.join(self.test_prefix, 'test')
test_workdir = os.path.join(self.test_prefix, 'test', 'workdir')
for fn in ('foo.txt', 'bar.txt'):
write_file(os.path.join(test_workdir, fn), 'test')
os.chdir(test_dir)
orig_wd = os.getcwd()
self.assertFalse(os.path.samefile(orig_wd, self.test_prefix))
cmd = "ls | sort"
# working directory is not explicitly defined
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd)
self.assertEqual(res.cmd, cmd)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'workdir\n')
self.assertEqual(res.stderr, None)
self.assertEqual(res.work_dir, orig_wd)
self.assertTrue(os.path.samefile(orig_wd, os.getcwd()))
# working directory is explicitly defined
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, work_dir=test_workdir)
self.assertEqual(res.cmd, cmd)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.output, 'bar.txt\nfoo.txt\n')
self.assertEqual(res.stderr, None)
self.assertEqual(res.work_dir, test_workdir)
self.assertTrue(os.path.samefile(orig_wd, os.getcwd()))
def test_run_cmd_log_output(self):
"""Test run_cmd with log_output enabled"""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
with self.mocked_stdout_stderr():
(out, ec) = run_cmd("seq 1 100", log_output=True)
self.assertEqual(ec, 0)
self.assertEqual(type(out), str)
self.assertTrue(out.startswith("1\n2\n"))
self.assertTrue(out.endswith("99\n100\n"))
run_cmd_logs = glob.glob(os.path.join(self.test_prefix, '*', 'easybuild-run_cmd*.log'))
self.assertEqual(len(run_cmd_logs), 1)
run_cmd_log_txt = read_file(run_cmd_logs[0])
self.assertTrue(run_cmd_log_txt.startswith("# output for command: seq 1 100\n\n"))
run_cmd_log_lines = run_cmd_log_txt.split('\n')
self.assertEqual(run_cmd_log_lines[2:5], ['1', '2', '3'])
self.assertEqual(run_cmd_log_lines[-4:-1], ['98', '99', '100'])
# test running command that emits non-UTF-8 characters
# this is constructed to reproduce errors like:
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2
# UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' (‘)
for text in [b"foo \xe2 bar", "foo ‘ bar"]:
test_file = os.path.join(self.test_prefix, 'foo.txt')
write_file(test_file, text)
cmd = "cat %s" % test_file
with self.mocked_stdout_stderr():
(out, ec) = run_cmd(cmd, log_output=True)
self.assertEqual(ec, 0)
self.assertTrue(out.startswith('foo ') and out.endswith(' bar'))
self.assertEqual(type(out), str)
def test_run_shell_cmd_split_stderr(self):
"""Test getting split stdout/stderr output from run_shell_cmd function."""
cmd = ';'.join([
"echo ok",
"echo warning >&2",
])
# by default, output contains both stdout + stderr
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd)
self.assertEqual(res.exit_code, 0)
output_lines = res.output.split('\n')
self.assertTrue("ok" in output_lines)
self.assertTrue("warning" in output_lines)
self.assertEqual(res.stderr, None)
# cleanup of artifacts in between calls to run_shell_cmd
remove_dir(self.test_prefix)
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, split_stderr=True)
self.assertEqual(res.exit_code, 0)
self.assertEqual(res.stderr, "warning\n")
self.assertEqual(res.output, "ok\n")
# check whether environment variables that point to stdout/stderr output files
# are set in environment defined by cmd.sh script
paths = glob.glob(os.path.join(self.test_prefix, 'eb-*', 'run-shell-cmd-output', 'echo-*'))
self.assertEqual(len(paths), 1)
cmd_tmpdir = paths[0]
cmd_script = os.path.join(cmd_tmpdir, 'cmd.sh')
self.assertExists(cmd_script)
cmd_cmd = '; '.join([
"echo $EB_CMD_OUT_FILE",
"cat $EB_CMD_OUT_FILE",
"echo $EB_CMD_ERR_FILE",
"cat $EB_CMD_ERR_FILE",
])
cmd = f"{cmd_script} -c '{cmd_cmd}'"
with self.mocked_stdout_stderr():
res = run_shell_cmd(cmd, fail_on_error=False)
regex = re.compile(".*/echo-.*/out.txt\nok\n.*/echo-.*/err.txt\nwarning$")
self.assertTrue(regex.search(res.output), f"Pattern '{regex.pattern}' should be found in {res.output}")
def test_run_cmd_trace(self):
"""Test run_cmd in trace mode, and with tracing disabled."""
# use of run_cmd is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
pattern = [
r"^ >> running command:",
r"\t\[started at: .*\]",
r"\t\[working dir: .*\]",
r"\t\[output logged in .*\]",
r"\techo hello",
r" >> command completed: exit 0, ran in .*",
]
# trace output is enabled by default (since EasyBuild v5.0)
self.mock_stdout(True)
self.mock_stderr(True)
(out, ec) = run_cmd("echo hello")
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(out, 'hello\n')
self.assertEqual(ec, 0)
self.assertTrue(stderr.strip().startswith("WARNING: Deprecated functionality"))
regex = re.compile('\n'.join(pattern))
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
init_config(build_options={'trace': False})
self.mock_stdout(True)
self.mock_stderr(True)
(out, ec) = run_cmd("echo hello")
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(out, 'hello\n')
self.assertEqual(ec, 0)
self.assertTrue(stderr.strip().startswith("WARNING: Deprecated functionality"))
self.assertEqual(stdout, '')
init_config(build_options={'trace': True})
# also test with command that is fed input via stdin
self.mock_stdout(True)
self.mock_stderr(True)
(out, ec) = run_cmd('cat', inp='hello')
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(out, 'hello')
self.assertEqual(ec, 0)
self.assertTrue(stderr.strip().startswith("WARNING: Deprecated functionality"))
pattern.insert(3, r"\t\[input: hello\]")
pattern[-2] = "\tcat"
regex = re.compile('\n'.join(pattern))
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
init_config(build_options={'trace': False})
self.mock_stdout(True)
self.mock_stderr(True)
(out, ec) = run_cmd('cat', inp='hello')
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(out, 'hello')
self.assertEqual(ec, 0)
self.assertTrue(stderr.strip().startswith("WARNING: Deprecated functionality"))
self.assertEqual(stdout, '')
# trace output can be disabled on a per-command basis
for trace in (True, False):
init_config(build_options={'trace': trace})
self.mock_stdout(True)
self.mock_stderr(True)
(out, ec) = run_cmd("echo hello", trace=False)
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(out, 'hello\n')
self.assertEqual(ec, 0)
self.assertEqual(stdout, '')
self.assertTrue(stderr.strip().startswith("WARNING: Deprecated functionality"))
def test_run_shell_cmd_trace(self):
"""Test run_shell_cmd function in trace mode, and with tracing disabled."""
pattern = [
r"^ >> running shell command:",
r"\techo hello",
r"\t\[started at: .*\]",
r"\t\[working dir: .*\]",
r"\t\[output and state saved to .*\]",
r" >> command completed: exit 0, ran in .*",
]
# trace output is enabled by default (since EasyBuild v5.0)
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd("echo hello")
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stderr, '')
regex = re.compile('\n'.join(pattern))
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
init_config(build_options={'trace': False})
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd("echo hello")
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stderr, '')
self.assertEqual(stdout, '')
init_config(build_options={'trace': True})
# trace output can be disabled on a per-command basis via 'hidden' option
for trace in (True, False):
init_config(build_options={'trace': trace})
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd("echo hello", hidden=True)
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stdout, '')
self.assertEqual(stderr, '')
def test_run_shell_cmd_trace_stdin(self):
"""Test run_shell_cmd function under --trace + passing stdin input."""
init_config(build_options={'trace': True})
pattern = [
r"^ >> running shell command:",
r"\techo hello",
r"\t\[started at: [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\]",
r"\t\[working dir: .*\]",
r"\t\[output and state saved to .*\]",
r" >> command completed: exit 0, ran in .*",
]
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd("echo hello")
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stderr, '')
regex = re.compile('\n'.join(pattern))
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
# also test with command that is fed input via stdin
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd('cat', stdin='hello')
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stderr, '')
pattern.insert(4, r"\t\[input: hello\]")
pattern[1] = "\tcat"
regex = re.compile('\n'.join(pattern))
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
# trace output can be disabled on a per-command basis by enabling 'hidden'
self.mock_stdout(True)
self.mock_stderr(True)
res = run_shell_cmd("echo hello", hidden=True)
stdout = self.get_stdout()
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertEqual(res.output, 'hello\n')
self.assertEqual(res.exit_code, 0)
self.assertEqual(stdout, '')
self.assertEqual(stderr, '')
def test_run_cmd_qa(self):
"""Basic test for run_cmd_qa function."""
# use of run_cmd_qa is deprecated, so we need to allow it here
self.allow_deprecated_behaviour()
cmd = "echo question; read x; echo $x"
qa = {'question': 'answer'}
with self.mocked_stdout_stderr():
(out, ec) = run_cmd_qa(cmd, qa)
self.assertEqual(out, "question\nanswer\n")