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