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