Completed
Pull Request — master (#167)
by
unknown
30s
created

TestSmartdispatcher.test_main_launch()   A

Complexity

Conditions 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
dl 0
loc 12
rs 9.4285
c 1
b 0
f 1
1
import os
2
import unittest
3
import tempfile
4
import shutil
5
from os.path import join as pjoin, abspath
6
from mock import patch
7
from subprocess import call
8
import subprocess
9
from nose.tools import assert_true, assert_equal
10
from smartdispatch import smartdispatch_script
11
import six
12
import sys
13
14
class TestSmartdispatcher(unittest.TestCase):
15
16
    def setUp(self):
17
        self.testing_dir = tempfile.mkdtemp()
18
        self.logs_dir = os.path.join(self.testing_dir, 'SMART_DISPATCH_LOGS')
19
20
        self.folded_commands = 'echo "[1 2 3 4]" "[6 7 8]" "[9 0]"'
21
        self.commands = ["echo 1 6 9", "echo 1 6 0", "echo 1 7 9", "echo 1 7 0", "echo 1 8 9", "echo 1 8 0",
22
                         "echo 2 6 9", "echo 2 6 0", "echo 2 7 9", "echo 2 7 0", "echo 2 8 9", "echo 2 8 0",
23
                         "echo 3 6 9", "echo 3 6 0", "echo 3 7 9", "echo 3 7 0", "echo 3 8 9", "echo 3 8 0",
24
                         "echo 4 6 9", "echo 4 6 0", "echo 4 7 9", "echo 4 7 0", "echo 4 8 9", "echo 4 8 0"]
25
        self.nb_commands = len(self.commands)
26
27
        scripts_path = abspath(pjoin(os.path.dirname(__file__), os.pardir, "scripts"))
28
        self.smart_dispatch_command = '{} -C 1 -G 1 -q test -t 5:00 -x'.format(pjoin(scripts_path, 'smart-dispatch'))
29
        self.launch_command = "{0} launch {1}".format(self.smart_dispatch_command, self.folded_commands)
30
        self.resume_command = "{0} resume {{0}}".format(self.smart_dispatch_command)
31
32
        self.smart_dispatch_launcher_command = '{} -C 1 -G 1 -q test -t 5:00'.format(pjoin(scripts_path, 'smart-dispatch'))
33
        self.launcher_command = "{0} launch {1}".format(self.smart_dispatch_launcher_command, self.folded_commands)
34
35
        smart_dispatch_command_with_pool = '{} --pool 10 -C 1 -G 1 -q test -t 5:00 -x {{0}}'.format(pjoin(scripts_path, 'smart-dispatch'))
36
        self.launch_command_with_pool = smart_dispatch_command_with_pool.format('launch ' + self.folded_commands)
37
        self.nb_workers = 10
38
39
        smart_dispatch_command_with_cores = '{} -C 1 -G 1 -c {{cores}} -q test -t 5:00 -x {{0}}'.format(pjoin(scripts_path, 'smart-dispatch'))
40
        self.launch_command_with_cores = smart_dispatch_command_with_cores.format('launch ' + self.folded_commands, cores='{cores}')
41
42
        smart_dispatch_command_with_gpus = '{} -C 1 -G 1 -g {{gpus}} -q test -t 5:00 -x {{0}}'.format(pjoin(scripts_path, 'smart-dispatch'))
43
        self.launch_command_with_gpus = smart_dispatch_command_with_gpus.format('launch ' + self.folded_commands, gpus='{gpus}')
44
45
        self._cwd = os.getcwd()
46
        os.chdir(self.testing_dir)
47
48
    def tearDown(self):
49
        os.chdir(self._cwd)
50
        shutil.rmtree(self.testing_dir)
51
52
    def test_main_launch(self):
53
        # Actual test
54
        exit_status = call(self.launch_command, shell=True)
55
56
        # Test validation
57
        assert_equal(exit_status, 0)
58
        assert_true(os.path.isdir(self.logs_dir))
59
        assert_equal(len(os.listdir(self.logs_dir)), 1)
60
61
        batch_uid = os.listdir(self.logs_dir)[0]
62
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
63
        assert_equal(len(os.listdir(path_job_commands)), self.nb_commands + 1)
64
65
    def test_launch_using_commands_file(self):
66
        # Actual test
67
        commands_filename = "commands_to_run.txt"
68
        open(commands_filename, 'w').write("\n".join(self.commands))
69
70
        launch_command = self.smart_dispatch_command + " -f {0} launch".format(commands_filename)
71
        exit_status = call(launch_command, shell=True)
72
73
        # Test validation
74
        assert_equal(exit_status, 0)
75
        assert_true(os.path.isdir(self.logs_dir))
76
        assert_equal(len(os.listdir(self.logs_dir)), 1)
77
78
        batch_uid = os.listdir(self.logs_dir)[0]
79
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
80
        assert_equal(len(os.listdir(path_job_commands)), self.nb_commands + 1)
81
        assert_equal(open(pjoin(path_job_commands, 'commands.txt')).read(), "\n".join(self.commands) + "\n")
82
83
    def test_main_launch_with_pool_of_workers(self):
84
        # Actual test
85
        exit_status = call(self.launch_command_with_pool, shell=True)
86
87
        # Test validation
88
        assert_equal(exit_status, 0)
89
        assert_true(os.path.isdir(self.logs_dir))
90
        assert_equal(len(os.listdir(self.logs_dir)), 1)
91
92
        batch_uid = os.listdir(self.logs_dir)[0]
93
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
94
        assert_equal(len(os.listdir(path_job_commands)), self.nb_workers + 1)
95
96
    def test_main_launch_with_cores_command(self):
97
        # Actual test
98
        exit_status_0 = call(self.launch_command_with_cores.format(cores=0), shell=True)
99
        exit_status_100 = call(self.launch_command_with_cores.format(cores=100), shell=True)
100
101
        # Test validation
102
        assert_equal(exit_status_0, 2)
103
        assert_equal(exit_status_100, 2)        
104
        assert_true(os.path.isdir(self.logs_dir))
105
106
    def test_main_launch_with_gpus_command(self):
107
        # Actual test
108
        exit_status_0 = call(self.launch_command_with_gpus.format(gpus=0), shell=True)
109
        exit_status_100 = call(self.launch_command_with_gpus.format(gpus=100), shell=True)
110
111
        # Test validation
112
        assert_equal(exit_status_0, 0)
113
        assert_equal(exit_status_100, 2)
114
        assert_true(os.path.isdir(self.logs_dir))
115
116 View Code Duplication
    @patch('subprocess.check_output')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
117
    def test_launch_job_check(self, mock_check_output):
118
119
        #For this test, we won't call the script directly, since we want to mock subprocess.check_output
120
        argv = ['-t', '0:0:1', '-G', '1', '-C', '1', '-q', 'random', 'launch', 'echo', 'testing123']
121
122
        # Test if the test pass (i.e the script run normaly)
123
        mock_check_output.side_effect = None
124
        mock_check_output.return_value = ""
125
126
        try:
127
            smartdispatch_script.main(argv=argv)
128
        except SystemExit as e:
129
            self.fail("The launcher had no problem, but the script failed nonetheless.")
130
131
        # Test if the check fail
132
        mock_check_output.side_effect = subprocess.CalledProcessError(1, 1, "A wild error appeared!")
133
        
134
        try:
135
            with self.assertRaises(SystemExit) as context:
136
                smartdispatch_script.main(argv=argv)
137
138
                self.assertTrue(context.exception.code, 2)
139
        
140
        except subprocess.CalledProcessError:
141
            # Rerasing the exception
142
            orig_exc_type, orig_exc_value, orig_exc_traceback = sys.exc_info()
143
144
            new_exc = Exception("smartdispatch_script.main() raised subprocess.CalledProcessError unexpectedly")
145
            new_exc.reraised = True
146
            six.reraise(type(new_exc), new_exc, orig_exc_traceback)
147
148
    def test_main_resume(self):
149
        # Setup
150
        call(self.launch_command, shell=True)
151
        batch_uid = os.listdir(self.logs_dir)[0]
152
153
        # Simulate that some commands are in the running state.
154
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
155
        pending_commands_file = pjoin(path_job_commands, "commands.txt")
156
        running_commands_file = pjoin(path_job_commands, "running_commands.txt")
157
        commands = open(pending_commands_file).read().strip().split("\n")
158
        with open(running_commands_file, 'w') as running_commands:
159
            running_commands.write("\n".join(commands[::2]) + "\n")
160
        with open(pending_commands_file, 'w') as pending_commands:
161
            pending_commands.write("\n".join(commands[1::2]) + "\n")
162
163
        # Actual test (should move running commands back to pending).
164
        exit_status = call(self.resume_command.format(batch_uid), shell=True)
165
166
        # Test validation
167
        assert_equal(exit_status, 0)
168
        assert_true(os.path.isdir(self.logs_dir))
169
        assert_equal(len(os.listdir(self.logs_dir)), 1)
170
        assert_equal(len(open(running_commands_file).readlines()), 0)
171
        assert_equal(len(open(pending_commands_file).readlines()), len(commands))
172
173
        # Test when batch_uid is a path instead of a jobname.
174
        # Setup
175
        batch_uid = os.path.join(self.logs_dir, os.listdir(self.logs_dir)[0])
176
177
        # Simulate that some commands are in the running state.
178
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
179
        pending_commands_file = pjoin(path_job_commands, "commands.txt")
180
        running_commands_file = pjoin(path_job_commands, "running_commands.txt")
181
        commands = open(pending_commands_file).read().strip().split("\n")
182
        with open(running_commands_file, 'w') as running_commands:
183
            running_commands.write("\n".join(commands[::2]) + "\n")
184
        with open(pending_commands_file, 'w') as pending_commands:
185
            pending_commands.write("\n".join(commands[1::2]) + "\n")
186
187
        # Actual test (should move running commands back to pending).
188
        exit_status = call(self.resume_command.format(batch_uid), shell=True)
189
190
        # Test validation
191
        assert_equal(exit_status, 0)
192
        assert_true(os.path.isdir(self.logs_dir))
193
        assert_equal(len(os.listdir(self.logs_dir)), 1)
194
        assert_equal(len(open(running_commands_file).readlines()), 0)
195
        assert_equal(len(open(pending_commands_file).readlines()), len(commands))
196
197 View Code Duplication
    def test_main_resume_by_expanding_pool_default(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
198
        # Create SMART_DISPATCH_LOGS structure.
199
        call(self.launch_command, shell=True)
200
        batch_uid = os.listdir(self.logs_dir)[0]
201
202
        # Simulate that some commands are in the running state.
203
        nb_commands_files = 2  # 'commands.txt' and 'running_commands.txt'
204
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
205
        pending_commands_file = pjoin(path_job_commands, "commands.txt")
206
        running_commands_file = pjoin(path_job_commands, "running_commands.txt")
207
        commands = open(pending_commands_file).read().strip().split("\n")
208
        with open(running_commands_file, 'w') as running_commands:
209
            running_commands.write("\n".join(commands[::2]) + "\n")
210
        with open(pending_commands_file, 'w') as pending_commands:
211
            pending_commands.write("\n".join(commands[1::2]) + "\n")
212
213
        # Remove PBS files so we can check that new ones are going to be created.
214
        for f in os.listdir(path_job_commands):
215
            if f.startswith('job_commands_') and f.endswith('.sh'):
216
                os.remove(pjoin(path_job_commands, f))
217
218
        # Should NOT move running commands back to pending but should add new workers.
219
        command_line = self.resume_command.format(batch_uid)
220
        command_line += " --expandPool"
221
        exit_status = call(command_line, shell=True)
222
223
        # Test validation
224
        assert_equal(exit_status, 0)
225
        assert_equal(len(open(running_commands_file).readlines()), len(commands[::2]))
226
        assert_equal(len(open(pending_commands_file).readlines()), len(commands[1::2]))
227
228
        nb_job_commands_files = len(os.listdir(path_job_commands))
229
        assert_equal(nb_job_commands_files-nb_commands_files, len(commands[1::2]))
230
231 View Code Duplication
    def test_main_resume_by_expanding_pool(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
232
        # Create SMART_DISPATCH_LOGS structure.
233
        call(self.launch_command, shell=True)
234
        batch_uid = os.listdir(self.logs_dir)[0]
235
236
        # Simulate that some commands are in the running state.
237
        nb_commands_files = 2  # 'commands.txt' and 'running_commands.txt'
238
        path_job_commands = os.path.join(self.logs_dir, batch_uid, "commands")
239
        pending_commands_file = pjoin(path_job_commands, "commands.txt")
240
        running_commands_file = pjoin(path_job_commands, "running_commands.txt")
241
        commands = open(pending_commands_file).read().strip().split("\n")
242
        with open(running_commands_file, 'w') as running_commands:
243
            running_commands.write("\n".join(commands[::2]) + "\n")
244
        with open(pending_commands_file, 'w') as pending_commands:
245
            pending_commands.write("\n".join(commands[1::2]) + "\n")
246
247
        # Remove PBS files so we can check that new ones are going to be created.
248
        for f in os.listdir(path_job_commands):
249
            if f.startswith('job_commands_') and f.endswith('.sh'):
250
                os.remove(pjoin(path_job_commands, f))
251
252
        # Should NOT move running commands back to pending but should add new workers.
253
        nb_workers_to_add = 3
254
        command_line = self.resume_command.format(batch_uid)
255
        command_line += " --expandPool {}".format(nb_workers_to_add)
256
        exit_status = call(command_line, shell=True)
257
258
        # Test validation
259
        assert_equal(exit_status, 0)
260
        assert_equal(len(open(running_commands_file).readlines()), len(commands[::2]))
261
        assert_equal(len(open(pending_commands_file).readlines()), len(commands[1::2]))
262
263
        nb_job_commands_files = len(os.listdir(path_job_commands))
264
        assert_equal(nb_job_commands_files-nb_commands_files, nb_workers_to_add)
265