-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
test_cli.py
1993 lines (1842 loc) · 87.3 KB
/
test_cli.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
# pylint: disable=line-too-long,missing-function-docstring,redefined-outer-name,too-few-public-methods,too-many-arguments,too-many-lines,too-many-positional-arguments,too-many-public-methods # noqa
#
# This file is part of Slurm-Mail.
#
# Slurm-Mail is a drop in replacement for Slurm's e-mails to give users
# much more information about their jobs compared to the standard Slurm
# e-mails.
#
# Copyright (C) 2018-2024 Neil Munday ([email protected])
#
# Slurm-Mail 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, either version 3 of the License, or (at
# your option) any later version.
#
# Slurm-Mail 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 Slurm-Mail. If not, see <http://www.gnu.org/licenses/>.
#
"""
Unit tests for Slurm-Mail.
"""
import configparser
import logging
import pathlib
from os import access
import smtplib
from typing import Dict, List, Union
from unittest.mock import MagicMock, mock_open, patch
import sys
import pytest # type: ignore
import slurmmail.cli
DUMMY_PATH = pathlib.Path("/tmp")
CONF_DIR = pathlib.Path(__file__).parents[2] / "etc/slurm-mail"
CONF_FILE = CONF_DIR / "slurm-mail.conf"
TEMPLATES_DIR = CONF_DIR / "templates"
HTML_TEMPLATES_DIR = TEMPLATES_DIR / "html"
TEXT_TEMPLATES_DIR = TEMPLATES_DIR / "text"
#
# Fixtures
#
@pytest.fixture
def clear_sys_argv():
"""
Ensure that sys.argv is empty.
Note: when pytest is executed from vscode sys.argv will contain
arguments to pytest which confuses the ArgumentParser instance
used by the CLI main methods.
"""
sys.argv = [""]
@pytest.fixture
def mock_get_file_contents():
with patch("slurmmail.cli.get_file_contents", wraps=slurmmail.cli.get_file_contents) as the_mock:
yield the_mock
@pytest.fixture
def mock_json_dump():
with patch("json.dump") as the_mock:
yield the_mock
@pytest.fixture
def mock_os_setegid():
with patch("os.setegid") as the_mock:
yield the_mock
@pytest.fixture
def mock_os_seteuid():
with patch("os.seteuid") as the_mock:
yield the_mock
@pytest.fixture
def mock_path_glob():
with patch("pathlib.Path.glob") as the_mock:
the_mock.return_value = ["1_1673384400.mail", "2_1673384500.mail"]
yield the_mock
@pytest.fixture
def mock_path_open():
with patch("pathlib.Path.open", new_callable=mock_open) as the_mock:
yield the_mock
@pytest.fixture
def mock_raw_config_parser():
with patch("configparser.RawConfigParser") as mock_config_parser:
mock_config_parser.side_effect = MockRawConfigParser
MockRawConfigParser.add_mock_value("slurm-send-mail", "logFile", None)
yield mock_config_parser
MockRawConfigParser.reset_mock()
@pytest.fixture
def mock_raw_config_parser_missing_section():
with patch(
"configparser.RawConfigParser.has_section", return_value=False
) as the_mock:
yield the_mock
@pytest.fixture
def mock_sys_argv_job_began():
with patch(
"sys.argv",
["spool_mail_main", "-s", "Slurm Job_id=1000 Began", "[email protected]"],
) as the_mock:
yield the_mock
#
# slurmmail.cli fixtures
#
@pytest.fixture
def mock_slurmmail_cli__process_spool_file():
with patch("slurmmail.cli.__process_spool_file") as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_check_dir():
with patch("slurmmail.cli.check_dir", return_value=True) as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_check_file():
with patch("slurmmail.cli.check_file", return_value=True) as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_check_job_output_file_path():
with patch("slurmmail.cli.check_job_output_file_path") as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_delete_spool_file():
with patch("slurmmail.cli.delete_spool_file") as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_process_spool_file_options():
options = slurmmail.cli.ProcessSpoolFileOptions()
options.array_max_notifications = 0
options.datetime_format = "%d/%m/%Y %H:%M:%S"
options.email_from_address = "root"
options.email_from_name = "Slurm Admin"
options.email_subject = "Job $CLUSTER.$JOB_ID: $STATE"
options.sacct_exe = pathlib.Path("/tmp/sacct")
options.scontrol_exe = pathlib.Path("/tmp/scontrol")
options.smtp_server = "localhost"
options.smtp_port = 25
options.retry_on_failure = True
options.tail_lines = 0
options.html_templates = {}
options.html_templates["array_ended"] = HTML_TEMPLATES_DIR / "ended-array.tpl"
options.html_templates["array_started"] = HTML_TEMPLATES_DIR / "started-array.tpl"
options.html_templates["array_summary_started"] = (
HTML_TEMPLATES_DIR / "started-array-summary.tpl"
)
options.html_templates["array_summary_ended"] = HTML_TEMPLATES_DIR / "ended-array-summary.tpl"
options.html_templates["ended"] = HTML_TEMPLATES_DIR / "ended.tpl"
options.html_templates["hetjob_started"] = HTML_TEMPLATES_DIR / "started-hetjob.tpl"
options.html_templates["hetjob_ended"] = HTML_TEMPLATES_DIR / "ended-hetjob.tpl"
options.html_templates["invalid_dependency"] = HTML_TEMPLATES_DIR / "invalid-dependency.tpl"
options.html_templates["job_output"] = HTML_TEMPLATES_DIR / "job-output.tpl"
options.html_templates["job_table"] = HTML_TEMPLATES_DIR / "job-table.tpl"
options.html_templates["never_ran"] = HTML_TEMPLATES_DIR / "never-ran.tpl"
options.html_templates["signature"] = HTML_TEMPLATES_DIR / "signature.tpl"
options.html_templates["staged_out"] = HTML_TEMPLATES_DIR / "staged-out.tpl"
options.html_templates["started"] = HTML_TEMPLATES_DIR / "started.tpl"
options.html_templates["time"] = HTML_TEMPLATES_DIR / "time.tpl"
options.html_templates["tres"] = HTML_TEMPLATES_DIR / "tres.tpl"
options.text_templates = {}
options.text_templates["array_ended"] = HTML_TEMPLATES_DIR / "ended-array.tpl"
options.text_templates["array_started"] = HTML_TEMPLATES_DIR / "started-array.tpl"
options.text_templates["array_summary_started"] = (
HTML_TEMPLATES_DIR / "started-array-summary.tpl"
)
options.text_templates["array_summary_ended"] = TEXT_TEMPLATES_DIR / "ended-array-summary.tpl"
options.text_templates["ended"] = TEXT_TEMPLATES_DIR / "ended.tpl"
options.text_templates["hetjob_started"] = TEXT_TEMPLATES_DIR / "started-hetjob.tpl"
options.text_templates["hetjob_ended"] = TEXT_TEMPLATES_DIR / "ended-hetjob.tpl"
options.text_templates["invalid_dependency"] = TEXT_TEMPLATES_DIR / "invalid-dependency.tpl"
options.text_templates["job_output"] = TEXT_TEMPLATES_DIR / "job-output.tpl"
options.text_templates["job_table"] = TEXT_TEMPLATES_DIR / "job-table.tpl"
options.text_templates["never_ran"] = TEXT_TEMPLATES_DIR / "never-ran.tpl"
options.text_templates["signature"] = TEXT_TEMPLATES_DIR / "signature.tpl"
options.text_templates["staged_out"] = TEXT_TEMPLATES_DIR / "staged-out.tpl"
options.text_templates["started"] = TEXT_TEMPLATES_DIR / "started.tpl"
options.text_templates["time"] = TEXT_TEMPLATES_DIR / "time.tpl"
options.text_templates["tres"] = TEXT_TEMPLATES_DIR / "tres.tpl"
options.validate_email = False
yield options
@pytest.fixture
def mock_slurmmail_cli_run_command():
with patch("slurmmail.cli.run_command") as the_mock:
yield the_mock
@pytest.fixture
def mock_slurmmail_cli_tail_file():
with patch("slurmmail.cli.tail_file") as the_mock:
yield the_mock
@pytest.fixture
def set_slurmmail_cli_values():
with patch("slurmmail.cli.conf_dir", CONF_DIR):
with patch("slurmmail.cli.conf_file", CONF_FILE):
with patch("slurmmail.cli.html_tpl_dir", HTML_TEMPLATES_DIR):
with patch("slurmmail.cli.text_tpl_dir", TEXT_TEMPLATES_DIR):
yield
#
# smtplib.SMTP fixtures
#
@pytest.fixture
def mock_smtp():
with patch("smtplib.SMTP") as the_mock:
yield the_mock
@pytest.fixture
def mock_smtp_ssl():
with patch("smtplib.SMTP_SSL") as the_mock:
yield the_mock
@pytest.fixture
def mock_smtp_sendmail():
with patch("smtplib.SMTP.sendmail") as the_mock:
yield the_mock
#
# Helpers
#
def check_message_logged(caplog, log_level: int, message: str, partial_match: bool = False) -> bool:
for record in caplog.records:
if record.levelno == log_level:
if not partial_match and record.message == message:
return True
if partial_match and message in record.message:
return True
return False
def check_template_used(the_mock: MagicMock, template_name: str):
call_found = False
for call in the_mock.mock_calls:
_, args, _ = call
if args[0].name == template_name:
call_found = True
break
assert call_found, f"{template_name} not used"
def check_templates_used(the_mock: MagicMock, template_names: List[str]):
for template_name in template_names:
check_template_used(the_mock, template_name)
#
# Test classes
#
class TestProcessSpoolFileOptions:
"""
Test ProcessSpoolFileOptions class.
"""
def test_create(self):
slurmmail.cli.ProcessSpoolFileOptions()
class TestCli:
"""
Test slurmmail.cli helper functions
"""
def test_get_scontrol_values(self):
scontrol_output = (
"JobId=1 JobName=test UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901759 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1 Reboot=0"
" ExitCode=0:0 RunTime=00:00:03 TimeLimit=UNLIMITED TimeMin=N/A"
" SubmitTime=2023-01-08T16:01:33 EligibleTime=2023-01-08T16:01:33"
" AccrueTime=2023-01-08T16:01:33 StartTime=2023-01-08T16:01:33"
" EndTime=2023-01-08T16:01:36 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-08T16:01:33 Scheduler=Main"
" Partition=all AllocNode:Sid=631cc24917ee:218 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1 NumCPUs=1"
" NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:* TRES=cpu=1,node=1,billing=1"
" Socks/Node=* NtasksPerN:B:S:C=0:0:*:* CoreSpec=* MinCPUsNode=1"
" MinMemoryNode=0 MinTmpDiskNode=0 Features=(null) DelayBoot=00:00:00"
" OverSubscribe=OK Contiguous=0 Licenses=(null) Network=(null)"
" Command=/root/test.jcf WorkDir=/root StdErr=/root/slurm-1.out"
" StdIn=/dev/null StdOut=/root/slurm-1.out Power="
)
scontrol_dict = slurmmail.cli.get_scontrol_values(scontrol_output)
assert "JobState" in scontrol_dict
assert scontrol_dict["JobState"] == "COMPLETED"
assert "JobName" in scontrol_dict
assert scontrol_dict["JobName"] == "test"
assert "JobId" in scontrol_dict
assert scontrol_dict["JobId"] == "1"
class MockRawConfigParser(configparser.RawConfigParser):
"""
Mock RawConfigParser class.
"""
# pylint: disable=redefined-builtin
__mock_values: Dict[str, Dict[str, Union[str, int, bool, None]]] = {}
_UNSET = object()
@staticmethod
def add_mock_value(
section: str, option: str, value: Union[str, int, bool, None]
) -> None:
if section not in MockRawConfigParser.__mock_values:
MockRawConfigParser.__mock_values[section] = {}
MockRawConfigParser.__mock_values[section][option] = value
@staticmethod
def reset_mock() -> None:
MockRawConfigParser.__mock_values = {}
def get( # type: ignore
self,
section: str,
option: str,
*,
raw=False, # type: ignore
vars=None,
fallback=_UNSET
) -> str:
if (
section in MockRawConfigParser.__mock_values
and option in MockRawConfigParser.__mock_values[section]
):
return str(MockRawConfigParser.__mock_values[section][option])
return super().get(section, option)
def getboolean(
self,
section: str,
option: str,
*,
raw=False,
vars=None,
fallback=_UNSET,
**kwargs
) -> bool:
if (
section in MockRawConfigParser.__mock_values
and option in MockRawConfigParser.__mock_values[section]
):
return bool(MockRawConfigParser.__mock_values[section][option])
return super().getboolean(section, option)
def has_option(self, section: str, option: str) -> bool:
if (
section in MockRawConfigParser.__mock_values
and option in MockRawConfigParser.__mock_values[section]
and MockRawConfigParser.__mock_values[section][option] is None
):
return False
if (
section in MockRawConfigParser.__mock_values
and option in MockRawConfigParser.__mock_values[section]
and MockRawConfigParser.__mock_values[section][option] is not None
):
return True
return super().has_option(section, option)
class TestProcessSpoolFile:
"""
Test __process_spool_file
"""
def test_bad_json(
self,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
):
with patch("pathlib.Path.open", new_callable=mock_open, read_data="bad_json"):
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
None,
mock_slurmmail_cli_process_spool_file_options,
)
mock_slurmmail_cli_delete_spool_file.assert_called_once()
def test_missing_json_fields(
self,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
):
with patch("pathlib.Path.open", new_callable=mock_open, read_data="{}"):
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
None,
mock_slurmmail_cli_process_spool_file_options,
)
mock_slurmmail_cli_delete_spool_file.assert_called_once()
def test_validate_unknown_state(
self,
caplog,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Foo",
"array_summary": false
}
""",
):
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
None,
mock_slurmmail_cli_process_spool_file_options,
)
assert check_message_logged(
caplog,
logging.WARNING,
"Unsupported job state: Foo - no emails will be generated"
)
mock_slurmmail_cli_delete_spool_file.assert_called_once()
def test_validate_email_fail(
self,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
mock_slurmmail_cli_process_spool_file_options.validate_email = True
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
None,
mock_slurmmail_cli_process_spool_file_options,
)
mock_slurmmail_cli_delete_spool_file.assert_called_once()
def test_sacct_failure(
self,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
mock_slurmmail_cli_run_command.return_value = (1, "", "")
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
None,
mock_slurmmail_cli_process_spool_file_options,
)
mock_slurmmail_cli_delete_spool_file.assert_called_once()
def test_job_began(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
sacct_output = "1|root|root|all|1674333232|Unknown|RUNNING|500M||1|0|00:00:00|1|/|00:00:11|0:0|||test|node01|01:00:00|60|1|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "1.batch||||1674333232|Unknown|RUNNING|||1|0|00:00:00|1||00:00:11|0:0|||test|node01|||1.batch|cpu=1,mem=0,node=1|batch" # noqa
mock_slurmmail_cli_run_command.side_effect = [(0, sacct_output, "")]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 1
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(mock_get_file_contents, ["started.tpl", "job-table.tpl", "signature.tpl"])
def test_job_began_additonal_email_headers(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
email_headers = {
"Precedence": "bulk",
"X-Auto-Response-Suppress": "DR, OOF, AutoReply"
}
sacct_output = "1|root|root|all|1674333232|Unknown|RUNNING|500M||1|0|00:00:00|1|/|00:00:11|0:0|||test|node01|01:00:00|60|1|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "1.batch||||1674333232|Unknown|RUNNING|||1|0|00:00:00|1||00:00:11|0:0|||test|node01|||1.batch|cpu=1,mem=0,node=1|batch" # noqa
mock_slurmmail_cli_run_command.side_effect = [(0, sacct_output, "")]
mock_slurmmail_cli_process_spool_file_options.email_headers = email_headers
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 1
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
# check e-mail headers were set
for header_name, header_value in email_headers.items():
assert f"{header_name}: {header_value}" in mock_smtp_sendmail.call_args[0][2]
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(mock_get_file_contents, ["started.tpl", "job-table.tpl", "signature.tpl"])
def test_job_began_sendmail_fail_retry_on_failure(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
sacct_output = "1|root|root|all|1674333232|Unknown|RUNNING|500M||1|0|00:00:00|1|/|00:00:11|0:0|||test|node01|01:00:00|60|1|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "1.batch||||1674333232|Unknown|RUNNING|||1|0|00:00:00|1||00:00:11|0:0|||test|node01|||1.batch|cpu=1,mem=0,node=1|batch" # noqa
mock_slurmmail_cli_run_command.side_effect = [(0, sacct_output, "")]
mock_smtp_sendmail.side_effect = smtplib.SMTPSenderRefused(503, b'Error', 'root')
with pytest.raises(smtplib.SMTPSenderRefused):
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 1
mock_slurmmail_cli_delete_spool_file.assert_not_called()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(mock_get_file_contents, ["started.tpl", "job-table.tpl", "signature.tpl"])
def test_job_began_sendmail_fail_no_retry_failure(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 1,
"email": "root",
"state": "Began",
"array_summary": false
}
""",
):
sacct_output = "1|root|root|all|1674333232|Unknown|RUNNING|500M||1|0|00:00:00|1|/|00:00:11|0:0|||test|node01|01:00:00|60|1|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "1.batch||||1674333232|Unknown|RUNNING|||1|0|00:00:00|1||00:00:11|0:0|||test|node01|||1.batch|cpu=1,mem=0,node=1|batch" # noqa
mock_slurmmail_cli_run_command.side_effect = [(0, sacct_output, "")]
mock_slurmmail_cli_process_spool_file_options.retry_on_failure = False
mock_smtp_sendmail.side_effect = smtplib.SMTPSenderRefused(503, b'Error', 'root')
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 1
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(mock_get_file_contents, ["started.tpl", "job-table.tpl", "signature.tpl"])
def test_job_ended(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 2,
"email": "root",
"state": "Ended",
"array_summary": false
}
""",
):
sacct_output = "2|root|root|all|1674340451|1674340571|COMPLETED|500M||1|1|00:00.010|1|/root|00:02:00|0:0|||test|node01|01:00:00|60|2|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "2.batch||||1674340451|1674340571|COMPLETED||4880K|1|1|00:00.010|1||00:02:00|0:0|||test|node01|||2.batch|cpu=1,mem=0,node=1|batch" # noqa
scontrol_output = (
"JobId=2 JobName=test.jcf UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901758 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1"
" Reboot=0 ExitCode=0:0 RunTime=00:02:00 TimeLimit=01:00:00 TimeMin=N/A"
" SubmitTime=2023-01-21T22:34:11 EligibleTime=2023-01-21T22:34:11"
" AccrueTime=2023-01-21T22:34:11 StartTime=2023-01-21T22:34:11"
" EndTime=2023-01-21T22:36:11 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-21T22:34:11 Scheduler=Main"
" Partition=all AllocNode:Sid=ac2c384f02af:204 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1"
" NumCPUs=1 NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:*"
" TRES=cpu=1,node=1,billing=1 Socks/Node=* NtasksPerN:B:S:C=0:0:*:*"
" CoreSpec=* MinCPUsNode=1 MinMemoryNode=0 MinTmpDiskNode=0"
" Features=(null) DelayBoot=00:00:00 OverSubscribe=OK Contiguous=0"
" Licenses=(null) Network=(null) Command=/root/test.jcf WorkDir=/root"
" StdErr=/root/slurm-2.out StdIn=/dev/null StdOut=/root/slurm-2.out"
" Power= MailUser=root"
" MailType=INVALID_DEPEND,BEGIN,END,FAIL,REQUEUE,STAGE_OUT"
)
mock_slurmmail_cli_run_command.side_effect = [
(0, sacct_output, ""),
(0, scontrol_output, ""),
]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 2
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(
mock_get_file_contents,
["ended.tpl", "job-table.tpl", "tres.tpl", "signature.tpl"]
)
def test_interactive_job_ended(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 2,
"email": "root",
"state": "Ended",
"array_summary": false
}
""",
):
sacct_output = "2|root|root|all|1674340451|1674340571|COMPLETED|500M||1|1|00:00.010|1|/root|00:02:00|0:0|||test|node01|01:00:00|60|2|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "2.batch||||1674340451|1674340571|COMPLETED||4880K|1|1|00:00.010|1||00:02:00|0:0|||test|node01|||2.batch|cpu=1,mem=0,node=1|batch" # noqa
scontrol_output = (
"JobId=2 JobName=test.jcf UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901758 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1"
" Reboot=0 ExitCode=0:0 RunTime=00:02:00 TimeLimit=01:00:00 TimeMin=N/A"
" SubmitTime=2023-01-21T22:34:11 EligibleTime=2023-01-21T22:34:11"
" AccrueTime=2023-01-21T22:34:11 StartTime=2023-01-21T22:34:11"
" EndTime=2023-01-21T22:36:11 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-21T22:34:11 Scheduler=Main"
" Partition=all AllocNode:Sid=ac2c384f02af:204 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1"
" NumCPUs=1 NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:*"
" TRES=cpu=1,node=1,billing=1 Socks/Node=* NtasksPerN:B:S:C=0:0:*:*"
" CoreSpec=* MinCPUsNode=1 MinMemoryNode=0 MinTmpDiskNode=0"
" Features=(null) DelayBoot=00:00:00 OverSubscribe=OK Contiguous=0"
" Licenses=(null) Network=(null) Command=/root/test.jcf WorkDir=/root"
" StdIn=/dev/null Power= MailUser=root"
" MailType=INVALID_DEPEND,BEGIN,END,FAIL,REQUEUE,STAGE_OUT"
)
mock_slurmmail_cli_run_command.side_effect = [
(0, sacct_output, ""),
(0, scontrol_output, ""),
]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 2
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(
mock_get_file_contents,
["ended.tpl", "job-table.tpl", "tres.tpl", "signature.tpl"]
)
def test_job_ended_mem_per_node_slurm_less_than_v21(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 2,
"email": "root",
"state": "Ended",
"array_summary": false
}
""",
):
sacct_output = "2|root|root|all|1674340451|1674340571|COMPLETED|500n||1|1|00:00.010|1|/root|00:02:00|0:0|||test|node01|01:00:00|60|2|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "2.batch||||1674340451|1674340571|COMPLETED||500n|1|1|00:00.010|1||00:02:00|0:0|||test|node01|||2.batch|cpu=1,mem=0,node=1|batch" # noqa
scontrol_output = (
"JobId=2 JobName=test.jcf UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901758 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1"
" Reboot=0 ExitCode=0:0 RunTime=00:02:00 TimeLimit=01:00:00 TimeMin=N/A"
" SubmitTime=2023-01-21T22:34:11 EligibleTime=2023-01-21T22:34:11"
" AccrueTime=2023-01-21T22:34:11 StartTime=2023-01-21T22:34:11"
" EndTime=2023-01-21T22:36:11 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-21T22:34:11 Scheduler=Main"
" Partition=all AllocNode:Sid=ac2c384f02af:204 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1"
" NumCPUs=1 NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:*"
" TRES=cpu=1,node=1,billing=1 Socks/Node=* NtasksPerN:B:S:C=0:0:*:*"
" CoreSpec=* MinCPUsNode=1 MinMemoryNode=0 MinTmpDiskNode=0"
" Features=(null) DelayBoot=00:00:00 OverSubscribe=OK Contiguous=0"
" Licenses=(null) Network=(null) Command=/root/test.jcf WorkDir=/root"
" StdErr=/root/slurm-2.out StdIn=/dev/null StdOut=/root/slurm-2.out"
" Power= MailUser=root"
" MailType=INVALID_DEPEND,BEGIN,END,FAIL,REQUEUE,STAGE_OUT"
)
mock_slurmmail_cli_run_command.side_effect = [
(0, sacct_output, ""),
(0, scontrol_output, ""),
]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 2
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(
mock_get_file_contents,
["ended.tpl", "job-table.tpl", "tres.tpl", "signature.tpl"]
)
def test_job_ended_mem_per_core_slurm_less_than_v21(
self,
mock_get_file_contents,
mock_slurmmail_cli_delete_spool_file,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 2,
"email": "root",
"state": "Ended",
"array_summary": false
}
""",
):
sacct_output = "2|root|root|all|1674340451|1674340571|COMPLETED|500c||1|1|00:00.010|1|/root|00:02:00|0:0|||test|node01|01:00:00|60|2|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "2.batch||||1674340451|1674340571|COMPLETED||500c|1|1|00:00.010|1||00:02:00|0:0|||test|node01|||2.batch|cpu=1,mem=0,node=1|batch" # noqa
scontrol_output = (
"JobId=2 JobName=test.jcf UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901758 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1"
" Reboot=0 ExitCode=0:0 RunTime=00:02:00 TimeLimit=01:00:00 TimeMin=N/A"
" SubmitTime=2023-01-21T22:34:11 EligibleTime=2023-01-21T22:34:11"
" AccrueTime=2023-01-21T22:34:11 StartTime=2023-01-21T22:34:11"
" EndTime=2023-01-21T22:36:11 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-21T22:34:11 Scheduler=Main"
" Partition=all AllocNode:Sid=ac2c384f02af:204 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1"
" NumCPUs=1 NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:*"
" TRES=cpu=1,node=1,billing=1 Socks/Node=* NtasksPerN:B:S:C=0:0:*:*"
" CoreSpec=* MinCPUsNode=1 MinMemoryNode=0 MinTmpDiskNode=0"
" Features=(null) DelayBoot=00:00:00 OverSubscribe=OK Contiguous=0"
" Licenses=(null) Network=(null) Command=/root/test.jcf WorkDir=/root"
" StdErr=/root/slurm-2.out StdIn=/dev/null StdOut=/root/slurm-2.out"
" Power= MailUser=root"
" MailType=INVALID_DEPEND,BEGIN,END,FAIL,REQUEUE,STAGE_OUT"
)
mock_slurmmail_cli_run_command.side_effect = [
(0, sacct_output, ""),
(0, scontrol_output, ""),
]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 2
mock_slurmmail_cli_delete_spool_file.assert_called_once()
mock_smtp_sendmail.assert_called_once()
assert (
mock_smtp_sendmail.call_args[0][0]
== mock_slurmmail_cli_process_spool_file_options.email_from_address
)
assert mock_smtp_sendmail.call_args[0][1] == ["root"]
check_templates_used(
mock_get_file_contents,
["ended.tpl", "job-table.tpl", "tres.tpl", "signature.tpl"]
)
def test_job_ended_tail_file(
self,
mock_get_file_contents,
mock_slurmmail_cli_check_job_output_file_path,
mock_slurmmail_cli_delete_spool_file,
mock_os_setegid,
mock_os_seteuid,
mock_slurmmail_cli_process_spool_file_options,
mock_slurmmail_cli_run_command,
mock_smtp_sendmail,
mock_slurmmail_cli_tail_file,
):
with patch(
"pathlib.Path.open",
new_callable=mock_open,
read_data="""{
"job_id": 2,
"email": "root",
"state": "Ended",
"array_summary": false
}
""",
):
mock_slurmmail_cli_check_job_output_file_path.return_value = True
mock_slurmmail_cli_process_spool_file_options.tail_lines = 10
mock_slurmmail_cli_process_spool_file_options.tail_exe = pathlib.Path(
"/usr/bin/tail"
)
sacct_output = "2|root|root|all|1674340451|1674340571|COMPLETED|500M||1|1|00:00.010|1|/root|00:02:00|0:0|||test|node01|01:00:00|60|2|billing=1,cpu=1,node=1|test.jcf\n" # noqa
sacct_output += "2.batch||||1674340451|1674340571|COMPLETED||4880K|1|1|00:00.010|1||00:02:00|0:0|||test|node01|||2.batch|cpu=1,mem=0,node=1|batch" # noqa
scontrol_output = (
"JobId=2 JobName=test.jcf UserId=root(0) GroupId=root(0) MCS_label=N/A"
" Priority=4294901758 Nice=0 Account=root QOS=normal JobState=COMPLETED"
" Reason=None Dependency=(null) Requeue=1 Restarts=0 BatchFlag=1"
" Reboot=0 ExitCode=0:0 RunTime=00:02:00 TimeLimit=01:00:00 TimeMin=N/A"
" SubmitTime=2023-01-21T22:34:11 EligibleTime=2023-01-21T22:34:11"
" AccrueTime=2023-01-21T22:34:11 StartTime=2023-01-21T22:34:11"
" EndTime=2023-01-21T22:36:11 Deadline=N/A SuspendTime=None"
" SecsPreSuspend=0 LastSchedEval=2023-01-21T22:34:11 Scheduler=Main"
" Partition=all AllocNode:Sid=ac2c384f02af:204 ReqNodeList=(null)"
" ExcNodeList=(null) NodeList=node01 BatchHost=node01 NumNodes=1"
" NumCPUs=1 NumTasks=1 CPUs/Task=1 ReqB:S:C:T=0:0:*:*"
" TRES=cpu=1,node=1,billing=1 Socks/Node=* NtasksPerN:B:S:C=0:0:*:*"
" CoreSpec=* MinCPUsNode=1 MinMemoryNode=0 MinTmpDiskNode=0"
" Features=(null) DelayBoot=00:00:00 OverSubscribe=OK Contiguous=0"
" Licenses=(null) Network=(null) Command=/root/test.jcf WorkDir=/root"
" StdErr=/root/slurm-2.out StdIn=/dev/null StdOut=/root/slurm-2.out"
" Power= MailUser=root"
" MailType=INVALID_DEPEND,BEGIN,END,FAIL,REQUEUE,STAGE_OUT"
)
mock_slurmmail_cli_run_command.side_effect = [
(0, sacct_output, ""),
(0, scontrol_output, ""),
]
slurmmail.cli.__dict__["__process_spool_file"](
pathlib.Path("/tmp/foo"),
smtplib.SMTP(),
mock_slurmmail_cli_process_spool_file_options,
)
assert mock_slurmmail_cli_run_command.call_count == 2
assert mock_os_setegid.call_count == 2
assert mock_os_seteuid.call_count == 2
mock_slurmmail_cli_tail_file.assert_called_once()