Move tests: unit/common
[yardstick.git] / yardstick / tests / unit / common / test_utils.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 # Unittest for yardstick.common.utils
11
12 from __future__ import absolute_import
13
14 from copy import deepcopy
15 import errno
16 import ipaddress
17 from itertools import product, chain
18 import mock
19 import os
20 import six
21 from six.moves import configparser
22 import unittest
23
24 import yardstick
25 from yardstick.common import utils
26 from yardstick.common import constants
27
28
29 class IterSubclassesTestCase(unittest.TestCase):
30     # Disclaimer: this class is a modified copy from
31     # rally/tests/unit/common/plugin/test_discover.py
32     # Copyright 2015: Mirantis Inc.
33
34     def test_itersubclasses(self):
35         class A(object):
36             pass
37
38         class B(A):
39             pass
40
41         class C(A):
42             pass
43
44         class D(C):
45             pass
46
47         self.assertEqual([B, C, D], list(utils.itersubclasses(A)))
48
49
50 class ImportModulesFromPackageTestCase(unittest.TestCase):
51
52     @mock.patch('yardstick.common.utils.os.walk')
53     def test_import_modules_from_package_no_mod(self, mock_walk):
54         yardstick_root = os.path.dirname(os.path.dirname(yardstick.__file__))
55         mock_walk.return_value = ([
56             (os.path.join(yardstick_root, 'foo'), ['bar'], ['__init__.py']),
57             (os.path.join(yardstick_root, 'foo', 'bar'), [], ['baz.txt', 'qux.rst'])
58         ])
59
60         utils.import_modules_from_package('foo.bar')
61
62     @mock.patch('yardstick.common.utils.os.walk')
63     @mock.patch('yardstick.common.utils.importutils')
64     def test_import_modules_from_package(self, mock_importutils, mock_walk):
65
66         yardstick_root = os.path.dirname(os.path.dirname(yardstick.__file__))
67         mock_walk.return_value = ([
68             (os.path.join(yardstick_root, 'foo', os.pardir, 'bar'), [], ['baz.py'])
69         ])
70
71         utils.import_modules_from_package('foo.bar')
72         mock_importutils.import_module.assert_called_with('bar.baz')
73
74
75 class GetParaFromYaml(unittest.TestCase):
76
77     @mock.patch('yardstick.common.utils.os.environ.get')
78     def test_get_param_para_not_found(self, get_env):
79         file_path = 'config_sample.yaml'
80         get_env.return_value = self._get_file_abspath(file_path)
81         args = 'releng.file'
82         default = 'hello'
83         self.assertTrue(constants.get_param(args, default), default)
84
85     @mock.patch('yardstick.common.utils.os.environ.get')
86     def test_get_param_para_exists(self, get_env):
87         file_path = 'config_sample.yaml'
88         get_env.return_value = self._get_file_abspath(file_path)
89         args = 'releng.dir'
90         para = '/home/opnfv/repos/releng'
91         self.assertEqual(para, constants.get_param(args))
92
93     def _get_file_abspath(self, filename):
94         curr_path = os.path.dirname(os.path.abspath(__file__))
95         file_path = os.path.join(curr_path, filename)
96         return file_path
97
98
99 class CommonUtilTestCase(unittest.TestCase):
100
101     def setUp(self):
102         self.data = {
103             "benchmark": {
104                 "data": {
105                     "mpstat": {
106                         "cpu0": {
107                             "%sys": "0.00",
108                             "%idle": "99.00"
109                         },
110                         "loadavg": [
111                             "1.09",
112                             "0.29"
113                         ]
114                     },
115                     "rtt": "1.03"
116                 }
117             }
118         }
119
120     def test__dict_key_flatten(self):
121         line = 'mpstat.loadavg1=0.29,rtt=1.03,mpstat.loadavg0=1.09,' \
122                'mpstat.cpu0.%idle=99.00,mpstat.cpu0.%sys=0.00'
123         # need to sort for assert to work
124         line = ",".join(sorted(line.split(',')))
125         flattened_data = utils.flatten_dict_key(
126             self.data['benchmark']['data'])
127         result = ",".join(
128             ("=".join(item) for item in sorted(flattened_data.items())))
129         self.assertEqual(result, line)
130
131
132 class TestMacAddressToHex(unittest.TestCase):
133
134     def test_mac_address_to_hex_list(self):
135         self.assertEqual(utils.mac_address_to_hex_list("ea:3e:e1:9a:99:e8"),
136                          ['0xea', '0x3e', '0xe1', '0x9a', '0x99', '0xe8'])
137
138
139 class TranslateToStrTestCase(unittest.TestCase):
140
141     def test_translate_to_str_unicode(self):
142         input_str = u'hello'
143         output_str = utils.translate_to_str(input_str)
144
145         result = 'hello'
146         self.assertEqual(result, output_str)
147
148     def test_translate_to_str_dict_list_unicode(self):
149         input_str = {
150             u'hello': {u'hello': [u'world']}
151         }
152         output_str = utils.translate_to_str(input_str)
153
154         result = {
155             'hello': {'hello': ['world']}
156         }
157         self.assertEqual(result, output_str)
158
159     def test_translate_to_str_non_string(self):
160         input_value = object()
161         result = utils.translate_to_str(input_value)
162         self.assertIs(input_value, result)
163
164
165 class TestParseCpuInfo(unittest.TestCase):
166
167     def test_single_socket_no_hyperthread(self):
168         cpuinfo = """\
169 processor       : 2
170 vendor_id       : GenuineIntel
171 cpu family      : 6
172 model           : 60
173 model name      : Intel Core Processor (Haswell, no TSX)
174 stepping        : 1
175 microcode       : 0x1
176 cpu MHz         : 2294.684
177 cache size      : 4096 KB
178 physical id     : 0
179 siblings        : 5
180 core id         : 2
181 cpu cores       : 5
182 apicid          : 2
183 initial apicid  : 2
184 fpu             : yes
185 fpu_exception   : yes
186 cpuid level     : 13
187 wp              : yes
188 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
189 bugs            :
190 bogomips        : 4589.36
191 clflush size    : 64
192 cache_alignment : 64
193 address sizes   : 46 bits physical, 48 bits virtual
194 power management:
195
196 processor       : 3
197 vendor_id       : GenuineIntel
198 cpu family      : 6
199 model           : 60
200 model name      : Intel Core Processor (Haswell, no TSX)
201 stepping        : 1
202 microcode       : 0x1
203 cpu MHz         : 2294.684
204 cache size      : 4096 KB
205 physical id     : 0
206 siblings        : 5
207 core id         : 3
208 cpu cores       : 5
209 apicid          : 3
210 initial apicid  : 3
211 fpu             : yes
212 fpu_exception   : yes
213 cpuid level     : 13
214 wp              : yes
215 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
216 bugs            :
217 bogomips        : 4589.36
218 clflush size    : 64
219 cache_alignment : 64
220 address sizes   : 46 bits physical, 48 bits virtual
221 power management:
222
223 processor       : 4
224 vendor_id       : GenuineIntel
225 cpu family      : 6
226 model           : 60
227 model name      : Intel Core Processor (Haswell, no TSX)
228 stepping        : 1
229 microcode       : 0x1
230 cpu MHz         : 2294.684
231 cache size      : 4096 KB
232 physical id     : 0
233 siblings        : 5
234 core id         : 4
235 cpu cores       : 5
236 apicid          : 4
237 initial apicid  : 4
238 fpu             : yes
239 fpu_exception   : yes
240 cpuid level     : 13
241 wp              : yes
242 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
243 bugs            :
244 bogomips        : 4589.36
245 clflush size    : 64
246 cache_alignment : 64
247 address sizes   : 46 bits physical, 48 bits virtual
248 power management:
249
250 """
251         socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
252         assert sorted(socket_map.keys()) == [0]
253         assert sorted(socket_map[0].keys()) == [2, 3, 4]
254
255     def test_single_socket_hyperthread(self):
256         cpuinfo = """\
257 processor       : 5
258 vendor_id       : GenuineIntel
259 cpu family      : 6
260 model           : 60
261 model name      : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
262 stepping        : 3
263 microcode       : 0x1d
264 cpu MHz         : 3501.708
265 cache size      : 8192 KB
266 physical id     : 0
267 siblings        : 8
268 core id         : 1
269 cpu cores       : 4
270 apicid          : 3
271 initial apicid  : 3
272 fpu             : yes
273 fpu_exception   : yes
274 cpuid level     : 13
275 wp              : yes
276 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
277 bugs            :
278 bogomips        : 6987.36
279 clflush size    : 64
280 cache_alignment : 64
281 address sizes   : 39 bits physical, 48 bits virtual
282 power management:
283
284 processor       : 6
285 vendor_id       : GenuineIntel
286 cpu family      : 6
287 model           : 60
288 model name      : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
289 stepping        : 3
290 microcode       : 0x1d
291 cpu MHz         : 3531.829
292 cache size      : 8192 KB
293 physical id     : 0
294 siblings        : 8
295 core id         : 2
296 cpu cores       : 4
297 apicid          : 5
298 initial apicid  : 5
299 fpu             : yes
300 fpu_exception   : yes
301 cpuid level     : 13
302 wp              : yes
303 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
304 bugs            :
305 bogomips        : 6987.36
306 clflush size    : 64
307 cache_alignment : 64
308 address sizes   : 39 bits physical, 48 bits virtual
309 power management:
310
311 processor       : 7
312 vendor_id       : GenuineIntel
313 cpu family      : 6
314 model           : 60
315 model name      : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
316 stepping        : 3
317 microcode       : 0x1d
318 cpu MHz         : 3500.213
319 cache size      : 8192 KB
320 physical id     : 0
321 siblings        : 8
322 core id         : 3
323 cpu cores       : 4
324 apicid          : 7
325 initial apicid  : 7
326 fpu             : yes
327 fpu_exception   : yes
328 cpuid level     : 13
329 wp              : yes
330 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
331 bugs            :
332 bogomips        : 6987.24
333 clflush size    : 64
334 cache_alignment : 64
335 address sizes   : 39 bits physical, 48 bits virtual
336 power management:
337
338 """
339         socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
340         assert sorted(socket_map.keys()) == [0]
341         assert sorted(socket_map[0].keys()) == [1, 2, 3]
342         assert sorted(socket_map[0][1]) == [5]
343         assert sorted(socket_map[0][2]) == [6]
344         assert sorted(socket_map[0][3]) == [7]
345
346     def test_dual_socket_hyperthread(self):
347         cpuinfo = """\
348 processor       : 1
349 vendor_id       : GenuineIntel
350 cpu family      : 6
351 model           : 79
352 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
353 stepping        : 1
354 microcode       : 0xb00001f
355 cpu MHz         : 1200.976
356 cache size      : 56320 KB
357 physical id     : 0
358 siblings        : 44
359 core id         : 1
360 cpu cores       : 22
361 apicid          : 2
362 initial apicid  : 2
363 fpu             : yes
364 fpu_exception   : yes
365 cpuid level     : 20
366 wp              : yes
367 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
368 bugs            :
369 bogomips        : 4401.07
370 clflush size    : 64
371 cache_alignment : 64
372 address sizes   : 46 bits physical, 48 bits virtual
373 power management:
374
375 processor       : 2
376 vendor_id       : GenuineIntel
377 cpu family      : 6
378 model           : 79
379 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
380 stepping        : 1
381 microcode       : 0xb00001f
382 cpu MHz         : 1226.892
383 cache size      : 56320 KB
384 physical id     : 0
385 siblings        : 44
386 core id         : 2
387 cpu cores       : 22
388 apicid          : 4
389 initial apicid  : 4
390 fpu             : yes
391 fpu_exception   : yes
392 cpuid level     : 20
393 wp              : yes
394 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
395 bugs            :
396 bogomips        : 4400.84
397 clflush size    : 64
398 cache_alignment : 64
399 address sizes   : 46 bits physical, 48 bits virtual
400 power management:
401
402 processor       : 43
403 vendor_id       : GenuineIntel
404 cpu family      : 6
405 model           : 79
406 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
407 stepping        : 1
408 microcode       : 0xb00001f
409 cpu MHz         : 1200.305
410 cache size      : 56320 KB
411 physical id     : 1
412 siblings        : 44
413 core id         : 28
414 cpu cores       : 22
415 apicid          : 120
416 initial apicid  : 120
417 fpu             : yes
418 fpu_exception   : yes
419 cpuid level     : 20
420 wp              : yes
421 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
422 bugs            :
423 bogomips        : 4411.31
424 clflush size    : 64
425 cache_alignment : 64
426 address sizes   : 46 bits physical, 48 bits virtual
427 power management:
428
429 processor       : 44
430 vendor_id       : GenuineIntel
431 cpu family      : 6
432 model           : 79
433 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
434 stepping        : 1
435 microcode       : 0xb00001f
436 cpu MHz         : 1200.305
437 cache size      : 56320 KB
438 physical id     : 0
439 siblings        : 44
440 core id         : 0
441 cpu cores       : 22
442 apicid          : 1
443 initial apicid  : 1
444 fpu             : yes
445 fpu_exception   : yes
446 cpuid level     : 20
447 wp              : yes
448 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
449 bugs            :
450 bogomips        : 4410.61
451 clflush size    : 64
452 cache_alignment : 64
453 address sizes   : 46 bits physical, 48 bits virtual
454 power management:
455
456 processor       : 85
457 vendor_id       : GenuineIntel
458 cpu family      : 6
459 model           : 79
460 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
461 stepping        : 1
462 microcode       : 0xb00001f
463 cpu MHz         : 1200.573
464 cache size      : 56320 KB
465 physical id     : 1
466 siblings        : 44
467 core id         : 26
468 cpu cores       : 22
469 apicid          : 117
470 initial apicid  : 117
471 fpu             : yes
472 fpu_exception   : yes
473 cpuid level     : 20
474 wp              : yes
475 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
476 bugs            :
477 bogomips        : 4409.07
478 clflush size    : 64
479 cache_alignment : 64
480 address sizes   : 46 bits physical, 48 bits virtual
481 power management:
482
483 processor       : 86
484 vendor_id       : GenuineIntel
485 cpu family      : 6
486 model           : 79
487 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
488 stepping        : 1
489 microcode       : 0xb00001f
490 cpu MHz         : 1200.305
491 cache size      : 56320 KB
492 physical id     : 1
493 siblings        : 44
494 core id         : 27
495 cpu cores       : 22
496 apicid          : 119
497 initial apicid  : 119
498 fpu             : yes
499 fpu_exception   : yes
500 cpuid level     : 20
501 wp              : yes
502 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
503 bugs            :
504 bogomips        : 4406.62
505 clflush size    : 64
506 cache_alignment : 64
507 address sizes   : 46 bits physical, 48 bits virtual
508 power management:
509
510 processor       : 87
511 vendor_id       : GenuineIntel
512 cpu family      : 6
513 model           : 79
514 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
515 stepping        : 1
516 microcode       : 0xb00001f
517 cpu MHz         : 1200.708
518 cache size      : 56320 KB
519 physical id     : 1
520 siblings        : 44
521 core id         : 28
522 cpu cores       : 22
523 apicid          : 121
524 initial apicid  : 121
525 fpu             : yes
526 fpu_exception   : yes
527 cpuid level     : 20
528 wp              : yes
529 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
530 bugs            :
531 bogomips        : 4413.48
532 clflush size    : 64
533 cache_alignment : 64
534 address sizes   : 46 bits physical, 48 bits virtual
535 power management:
536
537 """
538         socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
539         assert sorted(socket_map.keys()) == [0, 1]
540         assert sorted(socket_map[0].keys()) == [0, 1, 2]
541         assert sorted(socket_map[1].keys()) == [26, 27, 28]
542         assert sorted(socket_map[0][0]) == [44]
543         assert sorted(socket_map[0][1]) == [1]
544         assert sorted(socket_map[0][2]) == [2]
545         assert sorted(socket_map[1][26]) == [85]
546         assert sorted(socket_map[1][27]) == [86]
547         assert sorted(socket_map[1][28]) == [43, 87]
548
549     def test_dual_socket_no_hyperthread(self):
550         cpuinfo = """\
551 processor       : 1
552 vendor_id       : GenuineIntel
553 cpu family      : 6
554 model           : 79
555 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
556 stepping        : 1
557 microcode       : 0xb00001f
558 cpu MHz         : 1200.976
559 cache size      : 56320 KB
560 physical id     : 0
561 siblings        : 44
562 core id         : 1
563 cpu cores       : 22
564 apicid          : 2
565 initial apicid  : 2
566 fpu             : yes
567 fpu_exception   : yes
568 cpuid level     : 20
569 wp              : yes
570 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
571 bugs            :
572 bogomips        : 4401.07
573 clflush size    : 64
574 cache_alignment : 64
575 address sizes   : 46 bits physical, 48 bits virtual
576 power management:
577
578 processor       : 2
579 vendor_id       : GenuineIntel
580 cpu family      : 6
581 model           : 79
582 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
583 stepping        : 1
584 microcode       : 0xb00001f
585 cpu MHz         : 1226.892
586 cache size      : 56320 KB
587 physical id     : 0
588 siblings        : 44
589 core id         : 2
590 cpu cores       : 22
591 apicid          : 4
592 initial apicid  : 4
593 fpu             : yes
594 fpu_exception   : yes
595 cpuid level     : 20
596 wp              : yes
597 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
598 bugs            :
599 bogomips        : 4400.84
600 clflush size    : 64
601 cache_alignment : 64
602 address sizes   : 46 bits physical, 48 bits virtual
603 power management:
604
605 processor       : 43
606 vendor_id       : GenuineIntel
607 cpu family      : 6
608 model           : 79
609 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
610 stepping        : 1
611 microcode       : 0xb00001f
612 cpu MHz         : 1200.305
613 cache size      : 56320 KB
614 physical id     : 1
615 siblings        : 44
616 core id         : 28
617 cpu cores       : 22
618 apicid          : 120
619 initial apicid  : 120
620 fpu             : yes
621 fpu_exception   : yes
622 cpuid level     : 20
623 wp              : yes
624 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
625 bugs            :
626 bogomips        : 4411.31
627 clflush size    : 64
628 cache_alignment : 64
629 address sizes   : 46 bits physical, 48 bits virtual
630 power management:
631
632 processor       : 44
633 vendor_id       : GenuineIntel
634 cpu family      : 6
635 model           : 79
636 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
637 stepping        : 1
638 microcode       : 0xb00001f
639 cpu MHz         : 1200.305
640 cache size      : 56320 KB
641 physical id     : 0
642 siblings        : 44
643 core id         : 0
644 cpu cores       : 22
645 apicid          : 1
646 initial apicid  : 1
647 fpu             : yes
648 fpu_exception   : yes
649 cpuid level     : 20
650 wp              : yes
651 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
652 bugs            :
653 bogomips        : 4410.61
654 clflush size    : 64
655 cache_alignment : 64
656 address sizes   : 46 bits physical, 48 bits virtual
657 power management:
658
659 processor       : 85
660 vendor_id       : GenuineIntel
661 cpu family      : 6
662 model           : 79
663 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
664 stepping        : 1
665 microcode       : 0xb00001f
666 cpu MHz         : 1200.573
667 cache size      : 56320 KB
668 physical id     : 1
669 siblings        : 44
670 core id         : 26
671 cpu cores       : 22
672 apicid          : 117
673 initial apicid  : 117
674 fpu             : yes
675 fpu_exception   : yes
676 cpuid level     : 20
677 wp              : yes
678 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
679 bugs            :
680 bogomips        : 4409.07
681 clflush size    : 64
682 cache_alignment : 64
683 address sizes   : 46 bits physical, 48 bits virtual
684 power management:
685
686 processor       : 86
687 vendor_id       : GenuineIntel
688 cpu family      : 6
689 model           : 79
690 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
691 stepping        : 1
692 microcode       : 0xb00001f
693 cpu MHz         : 1200.305
694 cache size      : 56320 KB
695 physical id     : 1
696 siblings        : 44
697 core id         : 27
698 cpu cores       : 22
699 apicid          : 119
700 initial apicid  : 119
701 fpu             : yes
702 fpu_exception   : yes
703 cpuid level     : 20
704 wp              : yes
705 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
706 bugs            :
707 bogomips        : 4406.62
708 clflush size    : 64
709 cache_alignment : 64
710 address sizes   : 46 bits physical, 48 bits virtual
711 power management:
712
713 processor       : 87
714 vendor_id       : GenuineIntel
715 cpu family      : 6
716 model           : 79
717 model name      : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
718 stepping        : 1
719 microcode       : 0xb00001f
720 cpu MHz         : 1200.708
721 cache size      : 56320 KB
722 physical id     : 1
723 siblings        : 44
724 core id         : 28
725 cpu cores       : 22
726 apicid          : 121
727 initial apicid  : 121
728 fpu             : yes
729 fpu_exception   : yes
730 cpuid level     : 20
731 wp              : yes
732 flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
733 bugs            :
734 bogomips        : 4413.48
735 clflush size    : 64
736 cache_alignment : 64
737 address sizes   : 46 bits physical, 48 bits virtual
738 power management:
739
740 """
741         socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
742         processors = socket_map.processors()
743         assert processors == [1, 2, 43, 44, 85, 86, 87]
744         cores = socket_map.cores()
745         assert cores == [0, 1, 2, 26, 27, 28]
746         sockets = socket_map.sockets()
747         assert sockets == [0, 1]
748
749
750 class ChangeObjToDictTestCase(unittest.TestCase):
751
752     def test_change_obj_to_dict(self):
753         class A(object):
754             def __init__(self):
755                 self.name = 'yardstick'
756
757         obj = A()
758         obj_r = utils.change_obj_to_dict(obj)
759         obj_s = {'name': 'yardstick'}
760         self.assertEqual(obj_r, obj_s)
761
762
763 class SetDictValueTestCase(unittest.TestCase):
764
765     def test_set_dict_value(self):
766         input_dic = {
767             'hello': 'world'
768         }
769         output_dic = utils.set_dict_value(input_dic, 'welcome.to', 'yardstick')
770         self.assertEqual(output_dic.get('welcome', {}).get('to'), 'yardstick')
771
772
773 class RemoveFileTestCase(unittest.TestCase):
774
775     def test_remove_file(self):
776         try:
777             utils.remove_file('notexistfile.txt')
778         except Exception as e:  # pylint: disable=broad-except
779             # NOTE(ralonsoh): to narrow the scope of this exception.
780             self.assertTrue(isinstance(e, OSError))
781
782
783 class TestUtils(unittest.TestCase):
784
785     @mock.patch('yardstick.common.utils.os.makedirs')
786     def test_makedirs(self, *_):
787         self.assertIsNone(utils.makedirs('a/b/c/d'))
788
789     @mock.patch('yardstick.common.utils.os.makedirs')
790     def test_makedirs_exists(self, mock_os_makedirs):
791         mock_os_makedirs.side_effect = OSError(errno.EEXIST, 'exists')
792         self.assertIsNone(utils.makedirs('a/b/c/d'))
793
794     @mock.patch('yardstick.common.utils.os.makedirs')
795     def test_makedirs_busy(self, mock_os_makedirs):
796         mock_os_makedirs.side_effect = OSError(errno.EBUSY, 'busy')
797         with self.assertRaises(OSError):
798             utils.makedirs('a/b/c/d')
799
800     @mock.patch('yardstick.common.utils.jsonify')
801     def test_result_handler(self, mock_jsonify):
802         mock_jsonify.return_value = 432
803
804         self.assertEqual(utils.result_handler('x', 234), 432)
805         mock_jsonify.assert_called_once_with({'status': 'x', 'result': 234})
806
807     @mock.patch('random.randint')
808     @mock.patch('socket.socket')
809     def test_get_free_port(self, mock_socket, mock_randint):
810         mock_randint.return_value = 7777
811         s = mock_socket('x', 'y')
812         s.connect_ex.side_effect = iter([0, 1])
813         result = utils.get_free_port('10.20.30.40')
814         self.assertEqual(result, 7777)
815         self.assertEqual(s.connect_ex.call_count, 2)
816
817     @mock.patch('subprocess.check_output')
818     def test_execute_command(self, mock_check_output):
819         expected = ['hello world', '1234']
820         mock_check_output.return_value = os.linesep.join(expected)
821         result = utils.execute_command('my_command arg1 arg2')
822         self.assertEqual(result, expected)
823
824     @mock.patch('subprocess.Popen')
825     def test_source_env(self, mock_popen):
826         base_env = deepcopy(os.environ)
827         mock_process = mock_popen()
828         output_list = [
829             'garbage line before',
830             'NEW_ENV_VALUE=234',
831             'garbage line after',
832         ]
833         mock_process.communicate.return_value = os.linesep.join(output_list), '', 0
834         expected = {'NEW_ENV_VALUE': '234'}
835         result = utils.source_env('my_file')
836         self.assertDictEqual(result, expected)
837         os.environ.clear()
838         os.environ.update(base_env)
839
840     @mock.patch('yardstick.common.utils.configparser.ConfigParser')
841     def test_parse_ini_file(self, mock_config_parser_type):
842         defaults = {
843             'default1': 'value1',
844             'default2': 'value2',
845         }
846         s1 = {
847             'key1': 'value11',
848             'key2': 'value22',
849         }
850         s2 = {
851             'key1': 'value123',
852             'key2': 'value234',
853         }
854
855         mock_config_parser = mock_config_parser_type()
856         mock_config_parser.read.return_value = True
857         mock_config_parser.sections.return_value = ['s1', 's2']
858         mock_config_parser.items.side_effect = iter([
859             defaults.items(),
860             s1.items(),
861             s2.items(),
862         ])
863
864         expected = {
865             'DEFAULT': defaults,
866             's1': s1,
867             's2': s2,
868         }
869         result = utils.parse_ini_file('my_path')
870         self.assertDictEqual(result, expected)
871
872     @mock.patch('yardstick.common.utils.configparser.ConfigParser')
873     def test_parse_ini_file_missing_section_header(self, mock_config_parser_type):
874         mock_config_parser = mock_config_parser_type()
875         mock_config_parser.read.side_effect = \
876             configparser.MissingSectionHeaderError(mock.Mock(), 321, mock.Mock())
877
878         with self.assertRaises(configparser.MissingSectionHeaderError):
879             utils.parse_ini_file('my_path')
880
881     @mock.patch('yardstick.common.utils.configparser.ConfigParser')
882     def test_parse_ini_file_no_file(self, mock_config_parser_type):
883         mock_config_parser = mock_config_parser_type()
884         mock_config_parser.read.return_value = False
885         with self.assertRaises(RuntimeError):
886             utils.parse_ini_file('my_path')
887
888     @mock.patch('yardstick.common.utils.configparser.ConfigParser')
889     def test_parse_ini_file_no_default_section_header(self, mock_config_parser_type):
890         s1 = {
891             'key1': 'value11',
892             'key2': 'value22',
893         }
894         s2 = {
895             'key1': 'value123',
896             'key2': 'value234',
897         }
898
899         mock_config_parser = mock_config_parser_type()
900         mock_config_parser.read.return_value = True
901         mock_config_parser.sections.return_value = ['s1', 's2']
902         mock_config_parser.items.side_effect = iter([
903             configparser.NoSectionError(mock.Mock()),
904             s1.items(),
905             s2.items(),
906         ])
907
908         expected = {
909             'DEFAULT': {},
910             's1': s1,
911             's2': s2,
912         }
913         result = utils.parse_ini_file('my_path')
914         self.assertDictEqual(result, expected)
915
916     def test_join_non_strings(self):
917         self.assertEqual(utils.join_non_strings(':'), '')
918         self.assertEqual(utils.join_non_strings(':', 'a'), 'a')
919         self.assertEqual(utils.join_non_strings(':', 'a', 2, 'c'), 'a:2:c')
920         self.assertEqual(utils.join_non_strings(':', ['a', 2, 'c']), 'a:2:c')
921         self.assertEqual(utils.join_non_strings(':', 'abc'), 'abc')
922
923     def test_validate_non_string_sequence(self):
924         self.assertEqual(utils.validate_non_string_sequence([1, 2, 3]), [1, 2, 3])
925         self.assertIsNone(utils.validate_non_string_sequence('123'))
926         self.assertIsNone(utils.validate_non_string_sequence(1))
927
928         self.assertEqual(utils.validate_non_string_sequence(1, 2), 2)
929         self.assertEqual(utils.validate_non_string_sequence(1, default=2), 2)
930
931         with self.assertRaises(RuntimeError):
932             utils.validate_non_string_sequence(1, raise_exc=RuntimeError)
933
934     def test_error_class(self):
935         with self.assertRaises(RuntimeError):
936             utils.ErrorClass()
937
938         error_instance = utils.ErrorClass(test='')
939         with self.assertRaises(AttributeError):
940             error_instance.get_name()
941
942
943 class TestUtilsIpAddrMethods(unittest.TestCase):
944
945     GOOD_IP_V4_ADDRESS_STR_LIST = [
946         u'0.0.0.0',
947         u'10.20.30.40',
948         u'127.0.0.1',
949         u'10.20.30.40',
950         u'172.29.50.75',
951         u'192.168.230.9',
952         u'255.255.255.255',
953     ]
954
955     GOOD_IP_V4_MASK_STR_LIST = [
956         u'/1',
957         u'/8',
958         u'/13',
959         u'/19',
960         u'/24',
961         u'/32',
962     ]
963
964     GOOD_IP_V6_ADDRESS_STR_LIST = [
965         u'::1',
966         u'fe80::250:56ff:fe89:91ff',
967         u'123:4567:89ab:cdef:123:4567:89ab:cdef',
968     ]
969
970     GOOD_IP_V6_MASK_STR_LIST = [
971         u'/1',
972         u'/16',
973         u'/29',
974         u'/64',
975         u'/99',
976         u'/128',
977     ]
978
979     INVALID_IP_ADDRESS_STR_LIST = [
980         1,
981         u'w.x.y.z',
982         u'10.20.30.40/33',
983         u'123:4567:89ab:cdef:123:4567:89ab:cdef/129',
984     ]
985
986     def test_safe_ip_address(self):
987         addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
988         for addr in addr_list:
989             # test with no mask
990             expected = ipaddress.ip_address(addr)
991             self.assertEqual(utils.safe_ip_address(addr), expected, addr)
992
993     def test_safe_ip_address_v6_ip(self):
994         addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
995         for addr in addr_list:
996             # test with no mask
997             expected = ipaddress.ip_address(addr)
998             self.assertEqual(utils.safe_ip_address(addr), expected, addr)
999
1000     @mock.patch("yardstick.common.utils.logging")
1001     def test_safe_ip_address_negative(self, *args):
1002         # NOTE(ralonsoh): check the calls to mocked functions.
1003         for value in self.INVALID_IP_ADDRESS_STR_LIST:
1004             self.assertIsNone(utils.safe_ip_address(value), value)
1005
1006         addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1007         mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1008         for addr_mask_pair in product(addr_list, mask_list):
1009             value = ''.join(addr_mask_pair)
1010             self.assertIsNone(utils.safe_ip_address(value), value)
1011
1012         addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1013         mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1014         for addr_mask_pair in product(addr_list, mask_list):
1015             value = ''.join(addr_mask_pair)
1016             self.assertIsNone(utils.safe_ip_address(value), value)
1017
1018     def test_get_ip_version(self):
1019         addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1020         for addr in addr_list:
1021             # test with no mask
1022             self.assertEqual(utils.get_ip_version(addr), 4, addr)
1023
1024     def test_get_ip_version_v6_ip(self):
1025         addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1026         for addr in addr_list:
1027             # test with no mask
1028             self.assertEqual(utils.get_ip_version(addr), 6, addr)
1029
1030     @mock.patch("yardstick.common.utils.logging")
1031     def test_get_ip_version_negative(self, *args):
1032         # NOTE(ralonsoh): check the calls to mocked functions.
1033         for value in self.INVALID_IP_ADDRESS_STR_LIST:
1034             self.assertIsNone(utils.get_ip_version(value), value)
1035
1036         addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1037         mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1038         for addr_mask_pair in product(addr_list, mask_list):
1039             value = ''.join(addr_mask_pair)
1040             self.assertIsNone(utils.get_ip_version(value), value)
1041
1042         addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1043         mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1044         for addr_mask_pair in product(addr_list, mask_list):
1045             value = ''.join(addr_mask_pair)
1046             self.assertIsNone(utils.get_ip_version(value), value)
1047
1048     def test_ip_to_hex(self):
1049         self.assertEqual(utils.ip_to_hex('0.0.0.0'), '00000000')
1050         self.assertEqual(utils.ip_to_hex('10.20.30.40'), '0a141e28')
1051         self.assertEqual(utils.ip_to_hex('127.0.0.1'), '7f000001')
1052         self.assertEqual(utils.ip_to_hex('172.31.90.100'), 'ac1f5a64')
1053         self.assertEqual(utils.ip_to_hex('192.168.254.253'), 'c0a8fefd')
1054         self.assertEqual(utils.ip_to_hex('255.255.255.255'), 'ffffffff')
1055
1056     def test_ip_to_hex_v6_ip(self):
1057         for value in self.GOOD_IP_V6_ADDRESS_STR_LIST:
1058             self.assertEqual(utils.ip_to_hex(value), value)
1059
1060     @mock.patch("yardstick.common.utils.logging")
1061     def test_ip_to_hex_negative(self, *args):
1062         # NOTE(ralonsoh): check the calls to mocked functions.
1063         addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1064         mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1065         value_iter = (''.join(pair) for pair in product(addr_list, mask_list))
1066         for value in chain(value_iter, self.INVALID_IP_ADDRESS_STR_LIST):
1067             self.assertEqual(utils.ip_to_hex(value), value)
1068
1069
1070 class SafeDecodeUtf8TestCase(unittest.TestCase):
1071
1072     @unittest.skipIf(six.PY2,
1073                      'This test should only be launched with Python 3.x')
1074     def test_safe_decode_utf8(self):
1075         _bytes = b'this is a byte array'
1076         out = utils.safe_decode_utf8(_bytes)
1077         self.assertIs(type(out), str)
1078         self.assertEqual('this is a byte array', out)
1079
1080
1081 def main():
1082     unittest.main()
1083
1084 if __name__ == '__main__':
1085     main()