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