~andrewjbeach/juju-ci-tools/make-local-patcher

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
from argparse import (
    ArgumentParser,
    Namespace,
)
from datetime import (
    datetime,
    timedelta,
    )
from contextlib import contextmanager
import logging
import os
import socket
from StringIO import StringIO
from time import time
from unittest import TestCase

from mock import (
    call,
    patch,
    )

from utility import (
    add_basic_testing_arguments,
    extract_deb,
    find_candidates,
    get_auth_token,
    get_candidates_path,
    get_deb_arch,
    get_winrm_certs,
    quote,
    run_command,
    temp_dir,
    until_timeout,
    wait_for_port,
    )


class TestUntilTimeout(TestCase):

    def test_no_timeout(self):

        iterator = until_timeout(0)

        def now_iter():
            yield iterator.start
            yield iterator.start
            assert False

        with patch.object(iterator, 'now', now_iter().next):
            for x in iterator:
                self.assertIs(None, x)
                break

    @contextmanager
    def patched_until(self, timeout, deltas):
        iterator = until_timeout(timeout)

        def now_iter():
            for d in deltas:
                yield iterator.start + d
            assert False
        with patch.object(iterator, 'now', now_iter().next):
            yield iterator

    def test_timeout(self):
        with self.patched_until(
                5, [timedelta(), timedelta(0, 4), timedelta(0, 5)]) as until:
            results = list(until)
        self.assertEqual([5, 1], results)

    def test_long_timeout(self):
        deltas = [timedelta(), timedelta(4, 0), timedelta(5, 0)]
        with self.patched_until(86400 * 5, deltas) as until:
            self.assertEqual([86400 * 5, 86400], list(until))

    def test_start(self):
        now = datetime.now() + timedelta(days=1)
        now_iter = iter([now, now, now + timedelta(10)])
        with patch('utility.until_timeout.now', side_effect=now_iter.next):
            self.assertEqual(list(until_timeout(10, now - timedelta(10))), [])


def write_config(root, job_name, token):
    job_dir = os.path.join(root, 'jobs', job_name)
    os.makedirs(job_dir)
    job_config = os.path.join(job_dir, 'config.xml')
    with open(job_config, 'w') as config:
        config.write(
            '<config><authToken>{}</authToken></config>'.format(token))


@contextmanager
def parse_error(test_case):
    stderr = StringIO()
    with test_case.assertRaises(SystemExit):
        with patch('sys.stderr', stderr):
            yield stderr


class TestGetAuthToken(TestCase):

    def test_get_auth_token(self):
        with temp_dir() as root:
            write_config(root, 'job-name', 'foo')
            self.assertEqual(get_auth_token(root, 'job-name'), 'foo')


class TestFindCandidates(TestCase):

    def test_find_candidates(self):
        with temp_dir() as root:
            candidates_path = get_candidates_path(root)
            os.mkdir(candidates_path)
            self.assertEqual(list(find_candidates(root)), [])
            master_path = os.path.join(candidates_path, 'master')
            os.mkdir(master_path)
            self.assertEqual(list(find_candidates(root)), [])
            open(os.path.join(master_path, 'buildvars.json'), 'w')
            self.assertEqual(list(find_candidates(root)), [master_path])

    def test_find_candidates_old_buildvars(self):
        with temp_dir() as root:
            _, buildvars_path = self.make_candidates_dir(root, 'master')
            a_week_ago = time() - timedelta(days=7, seconds=1).total_seconds()
            os.utime(buildvars_path, (time(), a_week_ago))
            self.assertEqual(list(find_candidates(root)), [])

    def test_find_candidates_artifacts(self):
        with temp_dir() as root:
            self.make_candidates_dir(root, 'master-artifacts')
            self.assertEqual(list(find_candidates(root)), [])

    def test_find_candidates_find_all(self):
        with temp_dir() as root:
            master_path, buildvars_path = self.make_candidates_dir(
                root, '1.23')
            master_path_2, _ = self.make_candidates_dir(root, '1.24')
            a_week_ago = time() - timedelta(days=7, seconds=1).total_seconds()
            os.utime(buildvars_path, (time(), a_week_ago))
            self.assertItemsEqual(list(find_candidates(root)), [master_path_2])
            self.assertItemsEqual(list(find_candidates(root, find_all=True)),
                                  [master_path, master_path_2])

    def make_candidates_dir(self, root, master_name):
        candidates_path = get_candidates_path(root)
        if not os.path.isdir(candidates_path):
            os.mkdir(candidates_path)
        master_path = os.path.join(candidates_path, master_name)
        os.mkdir(master_path)
        buildvars_path = os.path.join(master_path, 'buildvars.json')
        open(buildvars_path, 'w')
        return master_path, buildvars_path


class TestWaitForPort(TestCase):

    def test_wait_for_port_0000_closed(self):
        with patch(
                'socket.getaddrinfo', autospec=True,
                return_value=[('foo', 'bar', 'baz', 'qux', ('0.0.0.0', 27))]
                ) as gai_mock:
            with patch('socket.socket', autospec=True) as socket_mock:
                wait_for_port('asdf', 26, closed=True)
        gai_mock.assert_called_once_with('asdf', 26, socket.AF_INET,
                                         socket.SOCK_STREAM)
        self.assertEqual(socket_mock.call_count, 0)

    def test_wait_for_port_0000_open(self):
        stub_called = False
        loc = locals()

        def gai_stub(host, port, family, socktype):
            if loc['stub_called']:
                raise ValueError()
            loc['stub_called'] = True
            return [('foo', 'bar', 'baz', 'qux', ('0.0.0.0', 27))]

        with patch('socket.getaddrinfo', autospec=True, side_effect=gai_stub,
                   ) as gai_mock:
            with patch('socket.socket', autospec=True) as socket_mock:
                with self.assertRaises(ValueError):
                    wait_for_port('asdf', 26, closed=False)
        self.assertEqual(gai_mock.mock_calls, [
            call('asdf', 26, socket.AF_INET, socket.SOCK_STREAM),
            call('asdf', 26, socket.AF_INET, socket.SOCK_STREAM),
            ])
        self.assertEqual(socket_mock.call_count, 0)

    def test_wait_for_port(self):
        with patch(
                'socket.getaddrinfo', autospec=True, return_value=[
                    ('foo', 'bar', 'baz', 'qux', ('192.168.8.3', 27))
                    ]) as gai_mock:
            with patch('socket.socket', autospec=True) as socket_mock:
                wait_for_port('asdf', 26, closed=False)
        gai_mock.assert_called_once_with(
            'asdf', 26, socket.AF_INET, socket.SOCK_STREAM),
        socket_mock.assert_called_once_with('foo', 'bar', 'baz')
        connect_mock = socket_mock.return_value.connect
        connect_mock.assert_called_once_with(('192.168.8.3', 27))

    def test_wait_for_port_no_address_closed(self):
        with patch('socket.getaddrinfo', autospec=True,
                   side_effect=socket.error(-5, None)) as gai_mock:
            with patch('socket.socket', autospec=True) as socket_mock:
                wait_for_port('asdf', 26, closed=True)
        gai_mock.assert_called_once_with('asdf', 26, socket.AF_INET,
                                         socket.SOCK_STREAM)
        self.assertEqual(socket_mock.call_count, 0)

    def test_wait_for_port_no_address_open(self):
        stub_called = False
        loc = locals()

        def gai_stub(host, port, family, socktype):
            if loc['stub_called']:
                raise ValueError()
            loc['stub_called'] = True
            raise socket.error(-5, None)

        with patch('socket.getaddrinfo', autospec=True, side_effect=gai_stub,
                   ) as gai_mock:
            with patch('socket.socket', autospec=True) as socket_mock:
                with self.assertRaises(ValueError):
                    wait_for_port('asdf', 26, closed=False)
        self.assertEqual(gai_mock.mock_calls, [
            call('asdf', 26, socket.AF_INET, socket.SOCK_STREAM),
            call('asdf', 26, socket.AF_INET, socket.SOCK_STREAM),
            ])
        self.assertEqual(socket_mock.call_count, 0)


class TestExtractDeb(TestCase):

    def test_extract_deb(self):
        with patch('subprocess.check_call', autospec=True) as cc_mock:
            extract_deb('foo', 'bar')
        cc_mock.assert_called_once_with(['dpkg', '-x', 'foo', 'bar'])


class TestGetDebArch(TestCase):

    def test_get_deb_arch(self):
        with patch('subprocess.check_output',
                   return_value=' amd42 \n') as co_mock:
            arch = get_deb_arch()
        co_mock.assert_called_once_with(['dpkg', '--print-architecture'])
        self.assertEqual(arch, 'amd42')


class TestAddBasicTestingArguments(TestCase):

    def test_positional_args(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        expected = Namespace(
            agent_url=None, debug=False, env='local', temp_env_name='testtest',
            juju_bin='/foo/juju', logs='/tmp/logs', series=None,
            verbose=logging.INFO, agent_stream=None, keep_env=False,
            upload_tools=False, bootstrap_host=None, machine=[])
        self.assertEqual(args, expected)

    def test_debug(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest', '--debug']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.debug, True)

    def test_verbose_logging(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest', '--verbose']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.verbose, logging.DEBUG)

    def test_agent_url(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--agent-url', 'http://example.org']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.agent_url, 'http://example.org')

    def test_agent_stream(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--agent-stream', 'testing']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.agent_stream, 'testing')

    def test_series(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest', '--series',
                    'vivid']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.series, 'vivid')

    def test_upload_tools(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--upload-tools']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertTrue(args.upload_tools)

    def test_bootstrap_host(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--bootstrap-host', 'bar']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.bootstrap_host, 'bar')

    def test_machine(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--machine', 'bar', '--machine', 'baz']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertEqual(args.machine, ['bar', 'baz'])

    def test_keep_env(self):
        cmd_line = ['local', '/foo/juju', '/tmp/logs', 'testtest',
                    '--keep-env']
        parser = add_basic_testing_arguments(ArgumentParser())
        args = parser.parse_args(cmd_line)
        self.assertTrue(args.keep_env)


class TestRunCommand(TestCase):

    def test_run_command_args(self):
        with patch('subprocess.check_output') as co_mock:
            run_command(['foo', 'bar'])
        args, kwargs = co_mock.call_args
        self.assertEqual((['foo', 'bar'], ), args)

    def test_run_command_dry_run(self):
        with patch('subprocess.check_output') as co_mock:
            run_command(['foo', 'bar'], dry_run=True)
            self.assertEqual(0, co_mock.call_count)

    def test_run_command_verbose(self):
        with patch('subprocess.check_output'):
            with patch('utility.print_now') as p_mock:
                run_command(['foo', 'bar'], verbose=True)
                self.assertEqual(2, p_mock.call_count)


class TestQuote(TestCase):

    def test_quote(self):
        self.assertEqual(quote("arg"), "arg")
        self.assertEqual(quote("/a/file name"), "'/a/file name'")
        self.assertEqual(quote("bob's"), "'bob'\"'\"'s'")


class TestGetWinRmCerts(TestCase):

    def test_get_certs(self):
        with patch.dict(os.environ, {"HOME": "/fake/home"}):
            certs = get_winrm_certs()
        self.assertEqual(certs, (
            "/fake/home/cloud-city/winrm_client_cert.key",
            "/fake/home/cloud-city/winrm_client_cert.pem",
        ))