summaryrefslogtreecommitdiff
path: root/tests/unit/dockertypes_test.py
blob: 2be05784bb934f3dfd44df8ba65a98bbb794c750 (plain)
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
# -*- coding: utf-8 -*-

import unittest

import pytest

from docker.constants import DEFAULT_DOCKER_API_VERSION
from docker.errors import InvalidArgument, InvalidVersion
from docker.types import (
    ContainerSpec, EndpointConfig, HostConfig, IPAMConfig,
    IPAMPool, LogConfig, Mount, ServiceMode, Ulimit,
)
from docker.types.services import convert_service_ports

try:
    from unittest import mock
except:
    import mock


def create_host_config(*args, **kwargs):
    return HostConfig(*args, **kwargs)


class HostConfigTest(unittest.TestCase):
    def test_create_host_config_no_options_newer_api_version(self):
        config = create_host_config(version='1.21')
        assert config['NetworkMode'] == 'default'

    def test_create_host_config_invalid_cpu_cfs_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.21', cpu_quota='0')

        with pytest.raises(TypeError):
            create_host_config(version='1.21', cpu_period='0')

        with pytest.raises(TypeError):
            create_host_config(version='1.21', cpu_quota=23.11)

        with pytest.raises(TypeError):
            create_host_config(version='1.21', cpu_period=1999.0)

    def test_create_host_config_with_cpu_quota(self):
        config = create_host_config(version='1.21', cpu_quota=1999)
        assert config.get('CpuQuota') == 1999

    def test_create_host_config_with_cpu_period(self):
        config = create_host_config(version='1.21', cpu_period=1999)
        assert config.get('CpuPeriod') == 1999

    def test_create_host_config_with_blkio_constraints(self):
        blkio_rate = [{"Path": "/dev/sda", "Rate": 1000}]
        config = create_host_config(
            version='1.22', blkio_weight=1999, blkio_weight_device=blkio_rate,
            device_read_bps=blkio_rate, device_write_bps=blkio_rate,
            device_read_iops=blkio_rate, device_write_iops=blkio_rate
        )

        assert config.get('BlkioWeight') == 1999
        assert config.get('BlkioWeightDevice') is blkio_rate
        assert config.get('BlkioDeviceReadBps') is blkio_rate
        assert config.get('BlkioDeviceWriteBps') is blkio_rate
        assert config.get('BlkioDeviceReadIOps') is blkio_rate
        assert config.get('BlkioDeviceWriteIOps') is blkio_rate
        assert blkio_rate[0]['Path'] == "/dev/sda"
        assert blkio_rate[0]['Rate'] == 1000

    def test_create_host_config_with_shm_size(self):
        config = create_host_config(version='1.22', shm_size=67108864)
        assert config.get('ShmSize') == 67108864

    def test_create_host_config_with_shm_size_in_mb(self):
        config = create_host_config(version='1.22', shm_size='64M')
        assert config.get('ShmSize') == 67108864

    def test_create_host_config_with_oom_kill_disable(self):
        config = create_host_config(version='1.21', oom_kill_disable=True)
        assert config.get('OomKillDisable') is True

    def test_create_host_config_with_userns_mode(self):
        config = create_host_config(version='1.23', userns_mode='host')
        assert config.get('UsernsMode') == 'host'
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.22', userns_mode='host')
        with pytest.raises(ValueError):
            create_host_config(version='1.23', userns_mode='host12')

    def test_create_host_config_with_oom_score_adj(self):
        config = create_host_config(version='1.22', oom_score_adj=100)
        assert config.get('OomScoreAdj') == 100
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.21', oom_score_adj=100)
        with pytest.raises(TypeError):
            create_host_config(version='1.22', oom_score_adj='100')

    def test_create_host_config_with_dns_opt(self):

        tested_opts = ['use-vc', 'no-tld-query']
        config = create_host_config(version='1.21', dns_opt=tested_opts)
        dns_opts = config.get('DnsOptions')

        assert 'use-vc' in dns_opts
        assert 'no-tld-query' in dns_opts

    def test_create_host_config_with_mem_reservation(self):
        config = create_host_config(version='1.21', mem_reservation=67108864)
        assert config.get('MemoryReservation') == 67108864

    def test_create_host_config_with_kernel_memory(self):
        config = create_host_config(version='1.21', kernel_memory=67108864)
        assert config.get('KernelMemory') == 67108864

    def test_create_host_config_with_pids_limit(self):
        config = create_host_config(version='1.23', pids_limit=1024)
        assert config.get('PidsLimit') == 1024

        with pytest.raises(InvalidVersion):
            create_host_config(version='1.22', pids_limit=1024)
        with pytest.raises(TypeError):
            create_host_config(version='1.23', pids_limit='1024')

    def test_create_host_config_with_isolation(self):
        config = create_host_config(version='1.24', isolation='hyperv')
        assert config.get('Isolation') == 'hyperv'

        with pytest.raises(InvalidVersion):
            create_host_config(version='1.23', isolation='hyperv')
        with pytest.raises(TypeError):
            create_host_config(
                version='1.24', isolation={'isolation': 'hyperv'}
            )

    def test_create_host_config_pid_mode(self):
        with pytest.raises(ValueError):
            create_host_config(version='1.23', pid_mode='baccab125')

        config = create_host_config(version='1.23', pid_mode='host')
        assert config.get('PidMode') == 'host'
        config = create_host_config(version='1.24', pid_mode='baccab125')
        assert config.get('PidMode') == 'baccab125'

    def test_create_host_config_invalid_mem_swappiness(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.24', mem_swappiness='40')

    def test_create_host_config_with_volume_driver(self):
        config = create_host_config(version='1.21', volume_driver='local')
        assert config.get('VolumeDriver') == 'local'

    def test_create_host_config_invalid_cpu_count_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.25', cpu_count='1')

    def test_create_host_config_with_cpu_count(self):
        config = create_host_config(version='1.25', cpu_count=2)
        assert config.get('CpuCount') == 2
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.24', cpu_count=1)

    def test_create_host_config_invalid_cpu_percent_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.25', cpu_percent='1')

    def test_create_host_config_with_cpu_percent(self):
        config = create_host_config(version='1.25', cpu_percent=15)
        assert config.get('CpuPercent') == 15
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.24', cpu_percent=10)

    def test_create_host_config_invalid_nano_cpus_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.25', nano_cpus='0')

    def test_create_host_config_with_nano_cpus(self):
        config = create_host_config(version='1.25', nano_cpus=1000)
        assert config.get('NanoCpus') == 1000
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.24', nano_cpus=1)

    def test_create_host_config_with_cpu_rt_period_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.25', cpu_rt_period='1000')

    def test_create_host_config_with_cpu_rt_period(self):
        config = create_host_config(version='1.25', cpu_rt_period=1000)
        assert config.get('CPURealtimePeriod') == 1000
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.24', cpu_rt_period=1000)

    def test_ctrate_host_config_with_cpu_rt_runtime_types(self):
        with pytest.raises(TypeError):
            create_host_config(version='1.25', cpu_rt_runtime='1000')

    def test_create_host_config_with_cpu_rt_runtime(self):
        config = create_host_config(version='1.25', cpu_rt_runtime=1000)
        assert config.get('CPURealtimeRuntime') == 1000
        with pytest.raises(InvalidVersion):
            create_host_config(version='1.24', cpu_rt_runtime=1000)


class ContainerSpecTest(unittest.TestCase):
    def test_parse_mounts(self):
        spec = ContainerSpec(
            image='scratch', mounts=[
                '/local:/container',
                '/local2:/container2:ro',
                Mount(target='/target', source='/source')
            ]
        )

        assert 'Mounts' in spec
        assert len(spec['Mounts']) == 3
        for mount in spec['Mounts']:
            assert isinstance(mount, Mount)


class UlimitTest(unittest.TestCase):
    def test_create_host_config_dict_ulimit(self):
        ulimit_dct = {'name': 'nofile', 'soft': 8096}
        config = create_host_config(
            ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
        )
        assert 'Ulimits' in config
        assert len(config['Ulimits']) == 1
        ulimit_obj = config['Ulimits'][0]
        assert isinstance(ulimit_obj, Ulimit)
        assert ulimit_obj.name == ulimit_dct['name']
        assert ulimit_obj.soft == ulimit_dct['soft']
        assert ulimit_obj['Soft'] == ulimit_obj.soft

    def test_create_host_config_dict_ulimit_capitals(self):
        ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4}
        config = create_host_config(
            ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
        )
        assert 'Ulimits' in config
        assert len(config['Ulimits']) == 1
        ulimit_obj = config['Ulimits'][0]
        assert isinstance(ulimit_obj, Ulimit)
        assert ulimit_obj.name == ulimit_dct['Name']
        assert ulimit_obj.soft == ulimit_dct['Soft']
        assert ulimit_obj.hard == ulimit_dct['Hard']
        assert ulimit_obj['Soft'] == ulimit_obj.soft

    def test_create_host_config_obj_ulimit(self):
        ulimit_dct = Ulimit(name='nofile', soft=8096)
        config = create_host_config(
            ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
        )
        assert 'Ulimits' in config
        assert len(config['Ulimits']) == 1
        ulimit_obj = config['Ulimits'][0]
        assert isinstance(ulimit_obj, Ulimit)
        assert ulimit_obj == ulimit_dct

    def test_ulimit_invalid_type(self):
        with pytest.raises(ValueError):
            Ulimit(name=None)
        with pytest.raises(ValueError):
            Ulimit(name='hello', soft='123')
        with pytest.raises(ValueError):
            Ulimit(name='hello', hard='456')


class LogConfigTest(unittest.TestCase):
    def test_create_host_config_dict_logconfig(self):
        dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}}
        config = create_host_config(
            version=DEFAULT_DOCKER_API_VERSION, log_config=dct
        )
        assert 'LogConfig' in config
        assert isinstance(config['LogConfig'], LogConfig)
        assert dct['type'] == config['LogConfig'].type

    def test_create_host_config_obj_logconfig(self):
        obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'})
        config = create_host_config(
            version=DEFAULT_DOCKER_API_VERSION, log_config=obj
        )
        assert 'LogConfig' in config
        assert isinstance(config['LogConfig'], LogConfig)
        assert obj == config['LogConfig']

    def test_logconfig_invalid_config_type(self):
        with pytest.raises(ValueError):
            LogConfig(type=LogConfig.types.JSON, config='helloworld')


class EndpointConfigTest(unittest.TestCase):
    def test_create_endpoint_config_with_aliases(self):
        config = EndpointConfig(version='1.22', aliases=['foo', 'bar'])
        assert config == {'Aliases': ['foo', 'bar']}

        with pytest.raises(InvalidVersion):
            EndpointConfig(version='1.21', aliases=['foo', 'bar'])


class IPAMConfigTest(unittest.TestCase):
    def test_create_ipam_config(self):
        ipam_pool = IPAMPool(subnet='192.168.52.0/24',
                             gateway='192.168.52.254')

        ipam_config = IPAMConfig(pool_configs=[ipam_pool])
        assert ipam_config == {
            'Driver': 'default',
            'Config': [{
                'Subnet': '192.168.52.0/24',
                'Gateway': '192.168.52.254',
                'AuxiliaryAddresses': None,
                'IPRange': None,
            }]
        }


class ServiceModeTest(unittest.TestCase):
    def test_replicated_simple(self):
        mode = ServiceMode('replicated')
        assert mode == {'replicated': {}}
        assert mode.mode == 'replicated'
        assert mode.replicas is None

    def test_global_simple(self):
        mode = ServiceMode('global')
        assert mode == {'global': {}}
        assert mode.mode == 'global'
        assert mode.replicas is None

    def test_global_replicas_error(self):
        with pytest.raises(InvalidArgument):
            ServiceMode('global', 21)

    def test_replicated_replicas(self):
        mode = ServiceMode('replicated', 21)
        assert mode == {'replicated': {'Replicas': 21}}
        assert mode.mode == 'replicated'
        assert mode.replicas == 21

    def test_replicated_replicas_0(self):
        mode = ServiceMode('replicated', 0)
        assert mode == {'replicated': {'Replicas': 0}}
        assert mode.mode == 'replicated'
        assert mode.replicas == 0

    def test_invalid_mode(self):
        with pytest.raises(InvalidArgument):
            ServiceMode('foobar')


class MountTest(unittest.TestCase):
    def test_parse_mount_string_ro(self):
        mount = Mount.parse_mount_string("/foo/bar:/baz:ro")
        assert mount['Source'] == "/foo/bar"
        assert mount['Target'] == "/baz"
        assert mount['ReadOnly'] is True

    def test_parse_mount_string_rw(self):
        mount = Mount.parse_mount_string("/foo/bar:/baz:rw")
        assert mount['Source'] == "/foo/bar"
        assert mount['Target'] == "/baz"
        assert not mount['ReadOnly']

    def test_parse_mount_string_short_form(self):
        mount = Mount.parse_mount_string("/foo/bar:/baz")
        assert mount['Source'] == "/foo/bar"
        assert mount['Target'] == "/baz"
        assert not mount['ReadOnly']

    def test_parse_mount_string_no_source(self):
        mount = Mount.parse_mount_string("foo/bar")
        assert mount['Source'] is None
        assert mount['Target'] == "foo/bar"
        assert not mount['ReadOnly']

    def test_parse_mount_string_invalid(self):
        with pytest.raises(InvalidArgument):
            Mount.parse_mount_string("foo:bar:baz:rw")

    def test_parse_mount_named_volume(self):
        mount = Mount.parse_mount_string("foobar:/baz")
        assert mount['Source'] == 'foobar'
        assert mount['Target'] == '/baz'
        assert mount['Type'] == 'volume'

    def test_parse_mount_bind(self):
        mount = Mount.parse_mount_string('/foo/bar:/baz')
        assert mount['Source'] == "/foo/bar"
        assert mount['Target'] == "/baz"
        assert mount['Type'] == 'bind'

    @pytest.mark.xfail
    def test_parse_mount_bind_windows(self):
        with mock.patch('docker.types.services.IS_WINDOWS_PLATFORM', True):
            mount = Mount.parse_mount_string('C:/foo/bar:/baz')
        assert mount['Source'] == "C:/foo/bar"
        assert mount['Target'] == "/baz"
        assert mount['Type'] == 'bind'


class ServicePortsTest(unittest.TestCase):
    def test_convert_service_ports_simple(self):
        ports = {8080: 80}
        assert convert_service_ports(ports) == [{
            'Protocol': 'tcp',
            'PublishedPort': 8080,
            'TargetPort': 80,
        }]

    def test_convert_service_ports_with_protocol(self):
        ports = {8080: (80, 'udp')}

        assert convert_service_ports(ports) == [{
            'Protocol': 'udp',
            'PublishedPort': 8080,
            'TargetPort': 80,
        }]

    def test_convert_service_ports_with_protocol_and_mode(self):
        ports = {8080: (80, 'udp', 'ingress')}

        assert convert_service_ports(ports) == [{
            'Protocol': 'udp',
            'PublishedPort': 8080,
            'TargetPort': 80,
            'PublishMode': 'ingress',
        }]

    def test_convert_service_ports_invalid(self):
        ports = {8080: ('way', 'too', 'many', 'items', 'here')}

        with pytest.raises(ValueError):
            convert_service_ports(ports)

    def test_convert_service_ports_no_protocol_and_mode(self):
        ports = {8080: (80, None, 'host')}

        assert convert_service_ports(ports) == [{
            'Protocol': 'tcp',
            'PublishedPort': 8080,
            'TargetPort': 80,
            'PublishMode': 'host',
        }]

    def test_convert_service_ports_multiple(self):
        ports = {
            8080: (80, None, 'host'),
            9999: 99,
            2375: (2375,)
        }

        converted_ports = convert_service_ports(ports)
        assert {
            'Protocol': 'tcp',
            'PublishedPort': 8080,
            'TargetPort': 80,
            'PublishMode': 'host',
        } in converted_ports

        assert {
            'Protocol': 'tcp',
            'PublishedPort': 9999,
            'TargetPort': 99,
        } in converted_ports

        assert {
            'Protocol': 'tcp',
            'PublishedPort': 2375,
            'TargetPort': 2375,
        } in converted_ports

        assert len(converted_ports) == 3