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
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import random
from unittest import mock
import jinja2
import oslotest.base
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_config import fixture as cfg_fixture
from oslo_utils import timeutils
from designate import exceptions
from designate import utils
from designate.tests import fixtures
CONF = cfg.CONF
class TestUtils(oslotest.base.BaseTestCase):
def setUp(self):
super(TestUtils, self).setUp()
self.stdlog = fixtures.StandardLogging()
self.useFixture(cfg_fixture.Config(CONF))
self.useFixture(self.stdlog)
@mock.patch('os.path.exists')
@mock.patch('os.path.abspath')
def test_find_config(self, mock_abspath, mock_path_exists):
CONF.set_override('pybasedir', '/tmp/workspace/designate')
mock_path_exists.side_effect = [True, False, False, False, False]
mock_abspath.return_value = '/tmp/designate/designate.conf'
config_files = utils.find_config('designate.conf')
self.assertEqual(['/tmp/designate/designate.conf'], config_files)
mock_abspath.assert_called_once()
@mock.patch.object(processutils, 'execute')
def test_execute(self, mock_execute):
mock_execute.return_value = ('designate.conf\npools.yaml\n', '')
out, err = utils.execute(
'/bin/ls', '/etc/designate/',
run_as_root=False
)
mock_execute.assert_called_once_with(
'/bin/ls', '/etc/designate/',
root_helper='sudo designate-rootwrap /etc/designate/rootwrap.conf',
run_as_root=False
)
self.assertEqual('designate.conf\npools.yaml\n', out)
self.assertFalse(err)
@mock.patch.object(processutils, 'execute')
def test_execute_with_rootwrap(self, mock_execute):
CONF.set_override('root_helper', 'sudo designate-test')
mock_execute.return_value = ('designate.conf\npools.yaml\n', '')
out, err = utils.execute(
'/bin/ls', '/etc/designate/',
run_as_root=True
)
mock_execute.assert_called_once_with(
'/bin/ls', '/etc/designate/',
root_helper='sudo designate-test',
run_as_root=True
)
self.assertEqual('designate.conf\npools.yaml\n', out)
self.assertFalse(err)
def test_deep_dict_merge(self):
a = {
'a': {'dns': 'record'},
'b': 'b',
'c': 'c',
}
b = {
'a': {'domain': 'zone'},
'c': 1,
'd': 'd',
}
self.assertEqual(
{
'a': {
'dns': 'record', 'domain': 'zone'
},
'b': 'b', 'c': 1, 'd': 'd'
},
utils.deep_dict_merge(a, b)
)
def test_deep_dict_merge_not_dict(self):
result = utils.deep_dict_merge(dict(), list())
self.assertIsInstance(result, list)
def test_get_proxies(self):
CONF.set_override('no_proxy', 'example.com', 'proxy')
CONF.set_override('http_proxy', 'example.org', 'proxy')
CONF.set_override('https_proxy', 'example.net', 'proxy')
result = utils.get_proxies()
self.assertEqual(['example.com'], result.get('no_proxy'))
self.assertEqual('example.org', result.get('http'))
self.assertEqual('example.net', result.get('https'))
def test_get_proxies_default_values(self):
result = utils.get_proxies()
self.assertIsNone(result.get('no_proxy'))
self.assertIsNone(result.get('http'))
self.assertIsNone(result.get('https'))
def test_get_proxies_with_no_proxy(self):
CONF.set_override('no_proxy', 'example.org', 'proxy')
result = utils.get_proxies()
self.assertEqual(['example.org'], result.get('no_proxy'))
self.assertIsNone(result.get('http'))
self.assertIsNone(result.get('https'))
def test_get_proxies_with_http_proxy(self):
CONF.set_override('http_proxy', 'example.org', 'proxy')
result = utils.get_proxies()
self.assertIsNone(result.get('no_proxy'))
self.assertEqual('example.org', result.get('http'))
self.assertEqual('example.org', result.get('https'))
def test_get_proxies_with_https_proxy(self):
CONF.set_override('https_proxy', 'example.org', 'proxy')
result = utils.get_proxies()
self.assertIsNone(result.get('no_proxy'))
self.assertIsNone(result.get('http'))
self.assertEqual('example.org', result.get('https'))
def test_resource_string(self):
resource_string = utils.resource_string(
'templates', 'bind9-zone.jinja2'
)
self.assertIsNotNone(resource_string)
def test_resource_string_missing(self):
self.assertRaisesRegex(
exceptions.ResourceNotFound,
'Could not find the requested resource',
utils.resource_string, 'invalid.jinja2'
)
def test_resource_string_empty_args(self):
self.assertRaises(
ValueError,
utils.resource_string
)
def test_load_schema_missing(self):
self.assertRaisesRegex(
exceptions.ResourceNotFound,
'Could not find the requested resource',
utils.load_schema, 'v1', 'missing'
)
@mock.patch.object(utils, 'resource_string')
def test_load_template(self, mock_resource_string):
mock_resource_string.return_value = 'Hello {{name}}'.encode('utf-8')
template = utils.load_template('bind9-zone.jinja2')
self.assertIsInstance(template, jinja2.Template)
@mock.patch.object(utils, 'resource_string')
def test_load_template_keep_trailing_newline(self, mock_resource_string):
mock_resource_string.return_value = 'Hello {{name}}'.encode('utf-8')
template = utils.load_template('bind9-zone.jinja2')
self.assertTrue(template.environment.keep_trailing_newline)
def test_load_template_missing(self):
self.assertRaises(
exceptions.ResourceNotFound,
utils.load_template, 'invalid.jinja2'
)
def test_render_template(self):
template = jinja2.Template('Hello {{name}}')
result = utils.render_template(template, name='World')
self.assertEqual('Hello World', result)
@mock.patch('builtins.open', new_callable=mock.mock_open)
@mock.patch('os.path.exists')
def test_render_template_to_file(self, mock_exists, mock_open):
mock_exists.return_value = True
output_path = '/tmp/designate/resources/templates/hello.jinja2'
template = jinja2.Template('Hello {{name}}')
utils.render_template_to_file(
template, makedirs=False, output_path=output_path, name='World'
)
mock_open.assert_called_once_with(output_path, 'w')
mock_open().write.assert_called_once_with('Hello World')
@mock.patch('builtins.open', new_callable=mock.mock_open)
@mock.patch('os.path.exists')
@mock.patch('os.makedirs')
def test_render_template_to_file_with_makedirs(self, mock_makedirs,
mock_exists,
mock_open):
mock_exists.return_value = False
output_path = '/tmp/designate/resources/templates/hello.jinja2'
template = jinja2.Template('Hello {{name}}')
utils.render_template_to_file(
template, makedirs=True, output_path=output_path, name='World'
)
mock_makedirs.assert_called_once_with(
'/tmp/designate/resources/templates'
)
mock_open.assert_called_once_with(output_path, 'w')
mock_open().write.assert_called_once_with('Hello World')
@mock.patch.object(timeutils, 'utcnow_ts')
def test_increment_serial_lower_than_ts(self, mock_utcnow_ts):
mock_utcnow_ts.return_value = 1561698354
ret_serial = utils.increment_serial(serial=1)
self.assertEqual(1561698354, ret_serial)
@mock.patch.object(timeutils, 'utcnow_ts')
def test_increment_serial_higher_than_ts(self, mock_utcnow_ts):
mock_utcnow_ts.return_value = 1561698354
ret_serial = utils.increment_serial(serial=1561698354 * 2)
self.assertEqual(1561698354 * 2 + 1, ret_serial)
def test_is_uuid_like(self):
self.assertTrue(
utils.is_uuid_like('ce9fcd6b-d546-4397-8a49-8ceaec37cb64')
)
def test_is_not_uuid_like(self):
self.assertFalse(utils.is_uuid_like('678'))
def test_split_host_port(self):
host, port = utils.split_host_port('abc:25')
self.assertEqual(('abc', 25), (host, port))
def test_split_host_port_with_invalid_port(self):
host, port = utils.split_host_port('abc:abc')
self.assertEqual(('abc:abc', 53), (host, port))
def test_get_paging_params(self):
CONF.set_override('default_limit_v2', 100, 'service:api')
context = mock.Mock()
params = {
'updated_at': None,
'created_at': '2019-06-28T04:17:34.000000',
'pattern': 'blacklisted.com.',
'id': 'f6663a98-281e-4cea-b0c3-3bc425e086ea',
}
marker, limit, sort_key, sort_dir = utils.get_paging_params(
context, params, ['created_at', 'id', 'updated_at', 'pattern']
)
self.assertIsNone(marker)
self.assertEqual(100, limit)
self.assertIsNone(sort_key)
self.assertIsNone(sort_dir)
def test_get_paging_params_without_sort_keys(self):
CONF.set_override('default_limit_v2', 0, 'service:api')
context = mock.Mock()
params = {
'updated_at': None,
'created_at': '2019-06-28T04:17:34.000000',
'pattern': 'blacklisted.com.',
'id': 'f6663a98-281e-4cea-b0c3-3bc425e086ea',
}
marker, limit, sort_key, sort_dir = utils.get_paging_params(
context, params, sort_keys=None
)
self.assertIsNone(marker)
self.assertEqual(0, limit)
self.assertIsNone(sort_key)
self.assertIsNone(sort_dir)
def test_get_paging_params_sort_by_tenant_id(self):
CONF.set_override('default_limit_v2', 100, 'service:api')
context = mock.Mock()
context.all_tenants = True
params = {
'updated_at': None,
'created_at': '2019-06-28T04:17:34.000000',
'pattern': 'blacklisted.com.',
'id': 'f6663a98-281e-4cea-b0c3-3bc425e086ea',
'sort_key': 'tenant_id',
}
marker, limit, sort_key, sort_dir = utils.get_paging_params(
context, params,
['created_at', 'id', 'updated_at', 'pattern', 'tenant_id']
)
self.assertIsNone(marker)
self.assertEqual(100, limit)
self.assertEqual('tenant_id', sort_key)
self.assertIsNone(sort_dir)
def test_get_paging_params_sort_tenant_without_all_tenants(self):
CONF.set_override('default_limit_v2', 100, 'service:api')
context = mock.Mock()
context.all_tenants = False
params = {
'updated_at': None,
'created_at': '2019-06-28T04:17:34.000000',
'pattern': 'blacklisted.com.',
'id': 'f6663a98-281e-4cea-b0c3-3bc425e086ea',
'sort_key': 'tenant_id',
}
marker, limit, sort_key, sort_dir = utils.get_paging_params(
context, params,
['created_at', 'id', 'updated_at', 'pattern', 'tenant_id']
)
self.assertIsNone(marker)
self.assertEqual(100, limit)
self.assertIsNone(sort_key)
self.assertIsNone(sort_dir)
def test_get_paging_params_invalid_limit(self):
context = mock.Mock()
self.assertRaises(
exceptions.InvalidLimit,
utils.get_paging_params,
context, {'limit': 9223372036854775809}, []
)
self.assertRaises(
exceptions.InvalidLimit,
utils.get_paging_params,
context, {'limit': -1}, []
)
def test_get_paging_params_max_limit(self):
CONF.set_override('max_limit_v2', 1000, 'service:api')
context = mock.Mock()
result = utils.get_paging_params(context, {'limit': 'max'}, [])
self.assertEqual(result[1], 1000)
def test_get_paging_params_invalid_sort_dir(self):
context = mock.Mock()
self.assertRaisesRegex(
exceptions.InvalidSortDir,
'Unknown sort direction, must be',
utils.get_paging_params, context, {'sort_dir': 'dsc'}, []
)
def test_get_paging_params_invalid_sort_key(self):
context = mock.Mock()
self.assertRaisesRegex(
exceptions.InvalidSortKey,
'sort key must be one of',
utils.get_paging_params, context, {'sort_key': 'dsc'},
['asc', 'desc']
)
@mock.patch('socket.socket')
def test_bind_tcp(self, mock_sock_impl):
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
utils.bind_tcp('127.0.0.1', 53, 100, 1)
mock_sock.settimeout.assert_called_once_with(1)
mock_sock.bind.assert_called_once_with(('127.0.0.1', 53))
mock_sock.listen.assert_called_once_with(100)
self.assertIn(
'Opening TCP Listening Socket on 127.0.0.1:53',
self.stdlog.logger.output
)
@mock.patch('socket.socket')
def test_bind_tcp_without_port(self, mock_sock_impl):
random_port = random.randint(1024, 65535)
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
mock_sock.getsockname.return_value = ('127.0.0.1', random_port)
utils.bind_tcp('127.0.0.1', 0, 100, 1)
self.assertIn(
'Listening on TCP port %(port)d' % {'port': random_port},
self.stdlog.logger.output
)
@mock.patch('socket.socket')
def test_bind_tcp_without_reuse_port(self, mock_sock_impl):
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
mock_sock.setsockopt.side_effect = [None, None, AttributeError, None]
utils.bind_tcp('127.0.0.1', 53, 100, 1)
self.assertIn(
'SO_REUSEPORT not available, ignoring.',
self.stdlog.logger.output
)
@mock.patch('socket.socket')
def test_bind_udp(self, mock_sock_impl):
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
utils.bind_udp('127.0.0.1', 53)
mock_sock.settimeout.assert_called_once_with(1)
mock_sock.bind.assert_called_once_with(('127.0.0.1', 53))
self.assertIn(
'Opening UDP Listening Socket on 127.0.0.1:53',
self.stdlog.logger.output
)
@mock.patch('socket.socket')
def test_bind_udp_without_port(self, mock_sock_impl):
random_port = random.randint(1024, 65535)
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
mock_sock.getsockname.return_value = ('127.0.0.1', random_port)
utils.bind_udp('127.0.0.1', 0)
self.assertIn(
'Listening on UDP port %(port)d' % {'port': random_port},
self.stdlog.logger.output
)
@mock.patch('socket.socket')
def test_bind_udp_without_reuse_port(self, mock_sock_impl):
mock_sock = mock.MagicMock()
mock_sock_impl.return_value = mock_sock
mock_sock.setsockopt.side_effect = [None, AttributeError]
utils.bind_udp('127.0.0.1', 53)
self.assertIn(
'SO_REUSEPORT not available, ignoring.',
self.stdlog.logger.output
)
|