1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
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 ##############################################################################
10 from copy import deepcopy
14 from itertools import product, chain
22 from six.moves import configparser
26 from yardstick import ssh
27 from yardstick.common import constants
28 from yardstick.common import utils
29 from yardstick.common import exceptions
30 from yardstick.tests.unit import base as ut_base
33 class IterSubclassesTestCase(ut_base.BaseUnitTestCase):
34 # Disclaimer: this class is a modified copy from
35 # rally/tests/unit/common/plugin/test_discover.py
36 # Copyright 2015: Mirantis Inc.
38 def test_itersubclasses(self):
51 self.assertEqual([B, C, D], list(utils.itersubclasses(A)))
54 class ImportModulesFromPackageTestCase(ut_base.BaseUnitTestCase):
56 @mock.patch('yardstick.common.utils.os.walk')
57 def test_import_modules_from_package_no_mod(self, mock_walk):
58 yardstick_root = os.path.dirname(os.path.dirname(yardstick.__file__))
59 mock_walk.return_value = ([
60 (os.path.join(yardstick_root, 'foo'), ['bar'], ['__init__.py']),
61 (os.path.join(yardstick_root, 'foo', 'bar'), [], ['baz.txt', 'qux.rst'])
64 utils.import_modules_from_package('foo.bar')
66 @mock.patch('yardstick.common.utils.os.walk')
67 @mock.patch.object(importlib, 'import_module')
68 def test_import_modules_from_package(self, mock_import_module, mock_walk):
70 yardstick_root = os.path.dirname(os.path.dirname(yardstick.__file__))
71 mock_walk.return_value = ([
72 (os.path.join(yardstick_root, 'foo', os.pardir, 'bar'), [], ['baz.py'])
75 utils.import_modules_from_package('foo.bar')
76 mock_import_module.assert_called_once_with('bar.baz')
79 class GetParaFromYaml(ut_base.BaseUnitTestCase):
81 @mock.patch('yardstick.common.utils.os.environ.get')
82 def test_get_param_para_not_found(self, get_env):
83 file_path = 'config_sample.yaml'
84 get_env.return_value = self._get_file_abspath(file_path)
87 self.assertTrue(constants.get_param(args, default), default)
89 @mock.patch('yardstick.common.utils.os.environ.get')
90 def test_get_param_para_exists(self, get_env):
91 file_path = 'config_sample.yaml'
92 get_env.return_value = self._get_file_abspath(file_path)
94 para = '/home/opnfv/repos/releng'
95 self.assertEqual(para, constants.get_param(args))
97 def _get_file_abspath(self, filename):
98 curr_path = os.path.dirname(os.path.abspath(__file__))
99 file_path = os.path.join(curr_path, filename)
103 class CommonUtilTestCase(ut_base.BaseUnitTestCase):
124 def test__dict_key_flatten(self):
125 line = 'mpstat.loadavg1=0.29,rtt=1.03,mpstat.loadavg0=1.09,' \
126 'mpstat.cpu0.%idle=99.00,mpstat.cpu0.%sys=0.00'
127 # need to sort for assert to work
128 line = ",".join(sorted(line.split(',')))
129 flattened_data = utils.flatten_dict_key(
130 self.data['benchmark']['data'])
132 ("=".join(item) for item in sorted(flattened_data.items())))
133 self.assertEqual(result, line)
135 def test_get_key_with_default_negative(self):
136 with self.assertRaises(KeyError):
137 utils.get_key_with_default({}, 'key1')
139 @mock.patch('yardstick.common.utils.open', create=True)
140 def test_(self, mock_open):
141 mock_open.side_effect = IOError
143 with self.assertRaises(IOError):
144 utils.find_relative_file('my/path', 'task/path')
146 self.assertEqual(mock_open.call_count, 2)
148 @mock.patch('yardstick.common.utils.open', create=True)
149 def test_open_relative_path(self, mock_open):
150 mock_open_result = mock_open()
151 mock_open_call_count = 1 # initial call to get result
153 self.assertEqual(utils.open_relative_file('foo', 'bar'), mock_open_result)
155 mock_open_call_count += 1 # one more call expected
156 self.assertEqual(mock_open.call_count, mock_open_call_count)
157 self.assertIn('foo', mock_open.call_args_list[-1][0][0])
158 self.assertNotIn('bar', mock_open.call_args_list[-1][0][0])
160 def open_effect(*args, **kwargs):
161 if kwargs.get('name', args[0]) == os.path.join('bar', 'foo'):
162 return mock_open_result
163 raise IOError(errno.ENOENT, 'not found')
165 mock_open.side_effect = open_effect
166 self.assertEqual(utils.open_relative_file('foo', 'bar'), mock_open_result)
168 mock_open_call_count += 2 # two more calls expected
169 self.assertEqual(mock_open.call_count, mock_open_call_count)
170 self.assertIn('foo', mock_open.call_args_list[-1][0][0])
171 self.assertIn('bar', mock_open.call_args_list[-1][0][0])
173 # test an IOError of type ENOENT
174 mock_open.side_effect = IOError(errno.ENOENT, 'not found')
175 with self.assertRaises(IOError):
176 # the second call still raises
177 utils.open_relative_file('foo', 'bar')
179 mock_open_call_count += 2 # two more calls expected
180 self.assertEqual(mock_open.call_count, mock_open_call_count)
181 self.assertIn('foo', mock_open.call_args_list[-1][0][0])
182 self.assertIn('bar', mock_open.call_args_list[-1][0][0])
184 # test an IOError other than ENOENT
185 mock_open.side_effect = IOError(errno.EBUSY, 'busy')
186 with self.assertRaises(IOError):
187 utils.open_relative_file('foo', 'bar')
189 mock_open_call_count += 1 # one more call expected
190 self.assertEqual(mock_open.call_count, mock_open_call_count)
193 class TestMacAddressToHex(ut_base.BaseUnitTestCase):
195 def test_mac_address_to_hex_list(self):
196 self.assertEqual(utils.mac_address_to_hex_list("ea:3e:e1:9a:99:e8"),
197 ['0xea', '0x3e', '0xe1', '0x9a', '0x99', '0xe8'])
199 def test_mac_address_to_hex_list_too_short_mac(self):
200 with self.assertRaises(exceptions.InvalidMacAddress):
201 utils.mac_address_to_hex_list("ea:3e:e1:9a")
203 def test_mac_address_to_hex_list_no_int_mac(self):
204 with self.assertRaises(exceptions.InvalidMacAddress):
205 utils.mac_address_to_hex_list("invalid_mac")
208 class TranslateToStrTestCase(ut_base.BaseUnitTestCase):
210 def test_translate_to_str_unicode(self):
212 output_str = utils.translate_to_str(input_str)
215 self.assertEqual(result, output_str)
217 def test_translate_to_str_dict_list_unicode(self):
219 u'hello': {u'hello': [u'world']}
221 output_str = utils.translate_to_str(input_str)
224 'hello': {'hello': ['world']}
226 self.assertEqual(result, output_str)
228 def test_translate_to_str_non_string(self):
229 input_value = object()
230 result = utils.translate_to_str(input_value)
231 self.assertIs(input_value, result)
234 class TestParseCpuInfo(ut_base.BaseUnitTestCase):
236 def test_single_socket_no_hyperthread(self):
239 vendor_id : GenuineIntel
242 model name : Intel Core Processor (Haswell, no TSX)
257 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
262 address sizes : 46 bits physical, 48 bits virtual
266 vendor_id : GenuineIntel
269 model name : Intel Core Processor (Haswell, no TSX)
284 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
289 address sizes : 46 bits physical, 48 bits virtual
293 vendor_id : GenuineIntel
296 model name : Intel Core Processor (Haswell, no TSX)
311 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
316 address sizes : 46 bits physical, 48 bits virtual
320 socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
321 self.assertEqual(sorted(socket_map.keys()), [0])
322 self.assertEqual(sorted(socket_map[0].keys()), [2, 3, 4])
324 def test_single_socket_hyperthread(self):
327 vendor_id : GenuineIntel
330 model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
345 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
350 address sizes : 39 bits physical, 48 bits virtual
354 vendor_id : GenuineIntel
357 model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
372 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
377 address sizes : 39 bits physical, 48 bits virtual
381 vendor_id : GenuineIntel
384 model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
399 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
404 address sizes : 39 bits physical, 48 bits virtual
408 socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
409 self.assertEqual(sorted(socket_map.keys()), [0])
410 self.assertEqual(sorted(socket_map[0].keys()), [1, 2, 3])
411 self.assertEqual(sorted(socket_map[0][1]), [5])
412 self.assertEqual(sorted(socket_map[0][2]), [6])
413 self.assertEqual(sorted(socket_map[0][3]), [7])
415 def test_dual_socket_hyperthread(self):
418 vendor_id : GenuineIntel
421 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
423 microcode : 0xb00001f
425 cache size : 56320 KB
436 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
441 address sizes : 46 bits physical, 48 bits virtual
445 vendor_id : GenuineIntel
448 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
450 microcode : 0xb00001f
452 cache size : 56320 KB
463 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
468 address sizes : 46 bits physical, 48 bits virtual
472 vendor_id : GenuineIntel
475 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
477 microcode : 0xb00001f
479 cache size : 56320 KB
490 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
495 address sizes : 46 bits physical, 48 bits virtual
499 vendor_id : GenuineIntel
502 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
504 microcode : 0xb00001f
506 cache size : 56320 KB
517 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
522 address sizes : 46 bits physical, 48 bits virtual
526 vendor_id : GenuineIntel
529 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
531 microcode : 0xb00001f
533 cache size : 56320 KB
544 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
549 address sizes : 46 bits physical, 48 bits virtual
553 vendor_id : GenuineIntel
556 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
558 microcode : 0xb00001f
560 cache size : 56320 KB
571 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
576 address sizes : 46 bits physical, 48 bits virtual
580 vendor_id : GenuineIntel
583 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
585 microcode : 0xb00001f
587 cache size : 56320 KB
598 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
603 address sizes : 46 bits physical, 48 bits virtual
607 socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
608 self.assertEqual(sorted(socket_map.keys()), [0, 1])
609 self.assertEqual(sorted(socket_map[0].keys()), [0, 1, 2])
610 self.assertEqual(sorted(socket_map[1].keys()), [26, 27, 28])
611 self.assertEqual(sorted(socket_map[0][0]), [44])
612 self.assertEqual(sorted(socket_map[0][1]), [1])
613 self.assertEqual(sorted(socket_map[0][2]), [2])
614 self.assertEqual(sorted(socket_map[1][26]), [85])
615 self.assertEqual(sorted(socket_map[1][27]), [86])
616 self.assertEqual(sorted(socket_map[1][28]), [43, 87])
618 def test_dual_socket_no_hyperthread(self):
621 vendor_id : GenuineIntel
624 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
626 microcode : 0xb00001f
628 cache size : 56320 KB
639 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
644 address sizes : 46 bits physical, 48 bits virtual
648 vendor_id : GenuineIntel
651 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
653 microcode : 0xb00001f
655 cache size : 56320 KB
666 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
671 address sizes : 46 bits physical, 48 bits virtual
675 vendor_id : GenuineIntel
678 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
680 microcode : 0xb00001f
682 cache size : 56320 KB
693 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
698 address sizes : 46 bits physical, 48 bits virtual
702 vendor_id : GenuineIntel
705 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
707 microcode : 0xb00001f
709 cache size : 56320 KB
720 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
725 address sizes : 46 bits physical, 48 bits virtual
729 vendor_id : GenuineIntel
732 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
734 microcode : 0xb00001f
736 cache size : 56320 KB
747 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
752 address sizes : 46 bits physical, 48 bits virtual
756 vendor_id : GenuineIntel
759 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
761 microcode : 0xb00001f
763 cache size : 56320 KB
774 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
779 address sizes : 46 bits physical, 48 bits virtual
783 vendor_id : GenuineIntel
786 model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
788 microcode : 0xb00001f
790 cache size : 56320 KB
801 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
806 address sizes : 46 bits physical, 48 bits virtual
810 socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
811 processors = socket_map.processors()
812 self.assertEqual(processors, [1, 2, 43, 44, 85, 86, 87])
813 cores = socket_map.cores()
814 self.assertEqual(cores, [0, 1, 2, 26, 27, 28])
815 sockets = socket_map.sockets()
816 self.assertEqual(sockets, [0, 1])
819 class ChangeObjToDictTestCase(ut_base.BaseUnitTestCase):
821 def test_change_obj_to_dict(self):
824 self.name = 'yardstick'
827 obj_r = utils.change_obj_to_dict(obj)
828 obj_s = {'name': 'yardstick'}
829 self.assertEqual(obj_r, obj_s)
832 class SetDictValueTestCase(ut_base.BaseUnitTestCase):
834 def test_set_dict_value(self):
838 output_dic = utils.set_dict_value(input_dic, 'welcome.to', 'yardstick')
839 self.assertEqual(output_dic.get('welcome', {}).get('to'), 'yardstick')
842 class RemoveFileTestCase(ut_base.BaseUnitTestCase):
844 def test_remove_file(self):
846 utils.remove_file('notexistfile.txt')
847 except Exception as e: # pylint: disable=broad-except
848 # NOTE(ralonsoh): to narrow the scope of this exception.
849 self.assertTrue(isinstance(e, OSError))
852 class ParseIniFileTestCase(ut_base.BaseUnitTestCase):
855 self._mock_config_parser_type = mock.patch.object(configparser,
857 self.mock_config_parser_type = self._mock_config_parser_type.start()
858 self.addCleanup(self._stop_mocks)
860 def _stop_mocks(self):
861 self._mock_config_parser_type.stop()
863 def test_parse_ini_file(self):
864 defaults = {'default1': 'value1',
865 'default2': 'value2'}
866 s1 = {'key1': 'value11',
868 s2 = {'key1': 'value123',
871 mock_config_parser = mock.Mock()
872 self.mock_config_parser_type.return_value = mock_config_parser
873 mock_config_parser.read.return_value = True
874 mock_config_parser.sections.return_value = ['s1', 's2']
875 mock_config_parser.items.side_effect = iter([
881 expected = {'DEFAULT': defaults,
884 result = utils.parse_ini_file('my_path')
885 self.assertDictEqual(expected, result)
887 @mock.patch.object(utils, 'logger')
888 def test_parse_ini_file_missing_section_header(self, *args):
889 mock_config_parser = mock.Mock()
890 self.mock_config_parser_type.return_value = mock_config_parser
891 mock_config_parser.read.side_effect = (
892 configparser.MissingSectionHeaderError(
893 mock.Mock(), 321, mock.Mock()))
895 with self.assertRaises(configparser.MissingSectionHeaderError):
896 utils.parse_ini_file('my_path')
898 def test_parse_ini_file_no_file(self):
899 mock_config_parser = mock.Mock()
900 self.mock_config_parser_type.return_value = mock_config_parser
901 mock_config_parser.read.return_value = False
902 with self.assertRaises(RuntimeError):
903 utils.parse_ini_file('my_path')
905 def test_parse_ini_file_no_default_section_header(self):
906 s1 = {'key1': 'value11',
908 s2 = {'key1': 'value123',
911 mock_config_parser = mock.Mock()
912 self.mock_config_parser_type.return_value = mock_config_parser
913 mock_config_parser.read.return_value = True
914 mock_config_parser.sections.return_value = ['s1', 's2']
915 mock_config_parser.items.side_effect = iter([
916 configparser.NoSectionError(mock.Mock()),
921 expected = {'DEFAULT': {},
924 result = utils.parse_ini_file('my_path')
925 self.assertDictEqual(expected, result)
928 class TestUtils(ut_base.BaseUnitTestCase):
930 @mock.patch('yardstick.common.utils.os.makedirs')
931 def test_makedirs(self, *_):
932 self.assertIsNone(utils.makedirs('a/b/c/d'))
934 @mock.patch('yardstick.common.utils.os.makedirs')
935 def test_makedirs_exists(self, mock_os_makedirs):
936 mock_os_makedirs.side_effect = OSError(errno.EEXIST, 'exists')
937 self.assertIsNone(utils.makedirs('a/b/c/d'))
939 @mock.patch('yardstick.common.utils.os.makedirs')
940 def test_makedirs_busy(self, mock_os_makedirs):
941 mock_os_makedirs.side_effect = OSError(errno.EBUSY, 'busy')
942 with self.assertRaises(OSError):
943 utils.makedirs('a/b/c/d')
945 @mock.patch('yardstick.common.utils.jsonify')
946 def test_result_handler(self, mock_jsonify):
947 mock_jsonify.return_value = 432
949 self.assertEqual(utils.result_handler('x', 234), 432)
950 mock_jsonify.assert_called_once_with({'status': 'x', 'result': 234})
952 @mock.patch('random.randint')
953 @mock.patch('socket.socket')
954 def test_get_free_port(self, mock_socket, mock_randint):
955 mock_randint.return_value = 7777
956 s = mock_socket('x', 'y')
957 s.connect_ex.side_effect = iter([0, 1])
958 result = utils.get_free_port('10.20.30.40')
959 self.assertEqual(result, 7777)
960 self.assertEqual(s.connect_ex.call_count, 2)
962 @mock.patch('subprocess.check_output')
963 def test_execute_command(self, mock_check_output):
964 expected = ['hello world', '1234']
965 mock_check_output.return_value = os.linesep.join(expected)
966 result = utils.execute_command('my_command arg1 arg2')
967 self.assertEqual(result, expected)
969 @mock.patch('subprocess.Popen')
970 def test_source_env(self, mock_popen):
971 base_env = deepcopy(os.environ)
972 mock_process = mock_popen()
974 'garbage line before',
976 'garbage line after',
978 mock_process.communicate.return_value = os.linesep.join(output_list), '', 0
979 expected = {'NEW_ENV_VALUE': '234'}
980 result = utils.source_env('my_file')
981 self.assertDictEqual(result, expected)
983 os.environ.update(base_env)
985 @mock.patch.object(configparser, 'ConfigParser')
986 def test_parse_ini_file(self, mock_config_parser_type):
988 'default1': 'value1',
989 'default2': 'value2',
1000 mock_config_parser = mock_config_parser_type()
1001 mock_config_parser.read.return_value = True
1002 mock_config_parser.sections.return_value = ['s1', 's2']
1003 mock_config_parser.items.side_effect = iter([
1010 'DEFAULT': defaults,
1014 result = utils.parse_ini_file('my_path')
1015 self.assertDictEqual(result, expected)
1017 @mock.patch.object(utils, 'logger')
1018 @mock.patch.object(configparser, 'ConfigParser')
1019 def test_parse_ini_file_missing_section_header(
1020 self, mock_config_parser_type, *args):
1021 mock_config_parser = mock_config_parser_type()
1022 mock_config_parser.read.side_effect = (
1023 configparser.MissingSectionHeaderError(mock.Mock(), 321,
1026 with self.assertRaises(configparser.MissingSectionHeaderError):
1027 utils.parse_ini_file('my_path')
1029 @mock.patch.object(configparser, 'ConfigParser')
1030 def test_parse_ini_file_no_file(self, mock_config_parser_type):
1031 mock_config_parser = mock_config_parser_type()
1032 mock_config_parser.read.return_value = False
1033 with self.assertRaises(RuntimeError):
1034 utils.parse_ini_file('my_path')
1036 @mock.patch.object(configparser, 'ConfigParser')
1037 def test_parse_ini_file_no_default_section_header(self, mock_config_parser_type):
1047 mock_config_parser = mock_config_parser_type()
1048 mock_config_parser.read.return_value = True
1049 mock_config_parser.sections.return_value = ['s1', 's2']
1050 mock_config_parser.items.side_effect = iter([
1051 configparser.NoSectionError(mock.Mock()),
1061 result = utils.parse_ini_file('my_path')
1062 self.assertDictEqual(result, expected)
1064 def test_join_non_strings(self):
1065 self.assertEqual(utils.join_non_strings(':'), '')
1066 self.assertEqual(utils.join_non_strings(':', 'a'), 'a')
1067 self.assertEqual(utils.join_non_strings(':', 'a', 2, 'c'), 'a:2:c')
1068 self.assertEqual(utils.join_non_strings(':', ['a', 2, 'c']), 'a:2:c')
1069 self.assertEqual(utils.join_non_strings(':', 'abc'), 'abc')
1071 def test_validate_non_string_sequence(self):
1072 self.assertEqual(utils.validate_non_string_sequence([1, 2, 3]), [1, 2, 3])
1073 self.assertIsNone(utils.validate_non_string_sequence('123'))
1074 self.assertIsNone(utils.validate_non_string_sequence(1))
1076 self.assertEqual(utils.validate_non_string_sequence(1, 2), 2)
1077 self.assertEqual(utils.validate_non_string_sequence(1, default=2), 2)
1079 with self.assertRaises(RuntimeError):
1080 utils.validate_non_string_sequence(1, raise_exc=RuntimeError)
1083 class TestUtilsIpAddrMethods(ut_base.BaseUnitTestCase):
1085 GOOD_IP_V4_ADDRESS_STR_LIST = [
1095 GOOD_IP_V4_MASK_STR_LIST = [
1104 GOOD_IP_V6_ADDRESS_STR_LIST = [
1106 u'fe80::250:56ff:fe89:91ff',
1107 u'123:4567:89ab:cdef:123:4567:89ab:cdef',
1110 GOOD_IP_V6_MASK_STR_LIST = [
1119 INVALID_IP_ADDRESS_STR_LIST = [
1123 u'123:4567:89ab:cdef:123:4567:89ab:cdef/129',
1126 def test_make_ipv4_address(self):
1127 for addr in self.GOOD_IP_V4_ADDRESS_STR_LIST:
1129 expected = ipaddress.IPv4Address(addr)
1130 self.assertEqual(utils.make_ipv4_address(addr), expected, addr)
1132 def test_make_ipv4_address_error(self):
1133 addr_list = self.INVALID_IP_ADDRESS_STR_LIST +\
1134 self.GOOD_IP_V6_ADDRESS_STR_LIST
1135 for addr in addr_list:
1136 self.assertRaises(Exception, utils.make_ipv4_address, addr)
1138 def test_get_ip_range_count(self):
1139 iprange = "192.168.0.1-192.168.0.25"
1140 count = utils.get_ip_range_count(iprange)
1141 self.assertEqual(count, 24)
1143 def test_get_ip_range_start(self):
1144 iprange = "192.168.0.1-192.168.0.25"
1145 start = utils.get_ip_range_start(iprange)
1146 self.assertEqual(start, "192.168.0.1")
1148 def test_safe_ip_address(self):
1149 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1150 for addr in addr_list:
1152 expected = ipaddress.ip_address(addr)
1153 self.assertEqual(utils.safe_ip_address(addr), expected, addr)
1155 def test_safe_ip_address_v6_ip(self):
1156 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1157 for addr in addr_list:
1159 expected = ipaddress.ip_address(addr)
1160 self.assertEqual(utils.safe_ip_address(addr), expected, addr)
1162 @mock.patch("yardstick.common.utils.logging")
1163 def test_safe_ip_address_negative(self, *args):
1164 # NOTE(ralonsoh): check the calls to mocked functions.
1165 for value in self.INVALID_IP_ADDRESS_STR_LIST:
1166 self.assertIsNone(utils.safe_ip_address(value), value)
1168 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1169 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1170 for addr_mask_pair in product(addr_list, mask_list):
1171 value = ''.join(addr_mask_pair)
1172 self.assertIsNone(utils.safe_ip_address(value), value)
1174 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1175 mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1176 for addr_mask_pair in product(addr_list, mask_list):
1177 value = ''.join(addr_mask_pair)
1178 self.assertIsNone(utils.safe_ip_address(value), value)
1180 def test_get_ip_version(self):
1181 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1182 for addr in addr_list:
1184 self.assertEqual(utils.get_ip_version(addr), 4, addr)
1186 def test_get_ip_version_v6_ip(self):
1187 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1188 for addr in addr_list:
1190 self.assertEqual(utils.get_ip_version(addr), 6, addr)
1192 @mock.patch("yardstick.common.utils.logging")
1193 def test_get_ip_version_negative(self, *args):
1194 # NOTE(ralonsoh): check the calls to mocked functions.
1195 for value in self.INVALID_IP_ADDRESS_STR_LIST:
1196 self.assertIsNone(utils.get_ip_version(value), value)
1198 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1199 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1200 for addr_mask_pair in product(addr_list, mask_list):
1201 value = ''.join(addr_mask_pair)
1202 self.assertIsNone(utils.get_ip_version(value), value)
1204 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1205 mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1206 for addr_mask_pair in product(addr_list, mask_list):
1207 value = ''.join(addr_mask_pair)
1208 self.assertIsNone(utils.get_ip_version(value), value)
1210 def test_ip_to_hex(self):
1211 self.assertEqual(utils.ip_to_hex('0.0.0.0'), '00000000')
1212 self.assertEqual(utils.ip_to_hex('10.20.30.40'), '0a141e28')
1213 self.assertEqual(utils.ip_to_hex('127.0.0.1'), '7f000001')
1214 self.assertEqual(utils.ip_to_hex('172.31.90.100'), 'ac1f5a64')
1215 self.assertEqual(utils.ip_to_hex('192.168.254.253'), 'c0a8fefd')
1216 self.assertEqual(utils.ip_to_hex('255.255.255.255'), 'ffffffff')
1218 def test_ip_to_hex_v6_ip(self):
1219 for value in self.GOOD_IP_V6_ADDRESS_STR_LIST:
1220 self.assertEqual(utils.ip_to_hex(value), value)
1222 @mock.patch("yardstick.common.utils.logging")
1223 def test_ip_to_hex_negative(self, *args):
1224 # NOTE(ralonsoh): check the calls to mocked functions.
1225 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1226 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1227 value_iter = (''.join(pair) for pair in product(addr_list, mask_list))
1228 for value in chain(value_iter, self.INVALID_IP_ADDRESS_STR_LIST):
1229 self.assertEqual(utils.ip_to_hex(value), value)
1231 def test_get_mask_from_ip_range_ipv4(self):
1233 for mask in range(8, 30):
1234 ip = ipaddress.ip_network(ip_str + '/' + str(mask), strict=False)
1235 result = utils.get_mask_from_ip_range(ip[2], ip[-2])
1236 self.assertEqual(mask, result)
1238 def test_get_mask_from_ip_range_ipv6(self):
1240 for mask in range(8, 120):
1241 ip = ipaddress.ip_network(ip_str + '/' + str(mask), strict=False)
1242 result = utils.get_mask_from_ip_range(ip[2], ip[-2])
1243 self.assertEqual(mask, result)
1246 class SafeDecodeUtf8TestCase(ut_base.BaseUnitTestCase):
1248 @unittest.skipIf(six.PY2,
1249 'This test should only be launched with Python 3.x')
1250 def test_safe_decode_utf8(self):
1251 _bytes = b'this is a byte array'
1252 out = utils.safe_decode_utf8(_bytes)
1253 self.assertIs(type(out), str)
1254 self.assertEqual('this is a byte array', out)
1257 class ReadMeminfoTestCase(ut_base.BaseUnitTestCase):
1259 MEMINFO = (b'MemTotal: 65860500 kB\n'
1260 b'MemFree: 28690900 kB\n'
1261 b'MemAvailable: 52873764 kB\n'
1262 b'Active(anon): 3015676 kB\n'
1263 b'HugePages_Total: 8\n'
1264 b'Hugepagesize: 1048576 kB')
1265 MEMINFO_DICT = {'MemTotal': '65860500',
1266 'MemFree': '28690900',
1267 'MemAvailable': '52873764',
1268 'Active(anon)': '3015676',
1269 'HugePages_Total': '8',
1270 'Hugepagesize': '1048576'}
1272 def test_read_meminfo(self):
1273 ssh_client = ssh.SSH('user', 'host')
1274 with mock.patch.object(ssh_client, 'get_file_obj') as \
1276 mock.patch.object(six, 'BytesIO',
1277 return_value=six.BytesIO(self.MEMINFO)):
1278 output = utils.read_meminfo(ssh_client)
1279 mock_get_client.assert_called_once_with('/proc/meminfo', mock.ANY)
1280 self.assertEqual(self.MEMINFO_DICT, output)
1283 class TimerTestCase(ut_base.BaseUnitTestCase):
1285 def test__getattr(self):
1286 with utils.Timer() as timer:
1288 self.assertEqual(1, round(timer.total_seconds(), 0))
1289 self.assertEqual(1, timer.delta.seconds)
1291 def test__enter_with_timeout(self):
1292 with utils.Timer(timeout=10) as timer:
1294 self.assertEqual(1, round(timer.total_seconds(), 0))
1296 def test__enter_with_timeout_exception(self):
1297 with self.assertRaises(exceptions.TimerTimeout):
1298 with utils.Timer(timeout=1):
1301 def test__enter_with_timeout_no_exception(self):
1302 with utils.Timer(timeout=1, raise_exception=False):
1305 def test__iter(self):
1307 for i in utils.Timer(timeout=2):
1308 iterations.append(i)
1310 self.assertEqual(2, len(iterations))
1312 def test_delta_time_sec(self):
1313 with utils.Timer() as timer:
1314 self.assertIsInstance(timer.delta_time_sec(), float)
1317 class WaitUntilTrueTestCase(ut_base.BaseUnitTestCase):
1319 def test_no_timeout(self):
1320 self.assertIsNone(utils.wait_until_true(lambda: True,
1321 timeout=1, sleep=1))
1323 def test_timeout_generic_exception(self):
1324 with self.assertRaises(exceptions.WaitTimeout):
1325 self.assertIsNone(utils.wait_until_true(lambda: False,
1326 timeout=1, sleep=1))
1328 def test_timeout_given_exception(self):
1329 class MyTimeoutException(exceptions.YardstickException):
1330 message = 'My timeout exception'
1332 with self.assertRaises(MyTimeoutException):
1334 utils.wait_until_true(lambda: False, timeout=1, sleep=1,
1335 exception=MyTimeoutException))
1337 def _run_thread(self):
1338 with self.assertRaises(exceptions.WaitTimeout):
1339 utils.wait_until_true(lambda: False, timeout=1, sleep=1)
1341 def test_timeout_no_main_thread(self):
1342 new_thread = threading.Thread(target=self._run_thread)
1344 new_thread.join(timeout=3)
1347 class SendSocketCommandTestCase(unittest.TestCase):
1349 @mock.patch.object(socket, 'socket')
1350 def test_execute_correct(self, mock_socket):
1351 mock_socket_obj = mock.Mock()
1352 mock_socket_obj.connect_ex.return_value = 0
1353 mock_socket.return_value = mock_socket_obj
1354 self.assertEqual(0, utils.send_socket_command('host', 22, 'command'))
1355 mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
1356 mock_socket_obj.connect_ex.assert_called_once_with(('host', 22))
1357 mock_socket_obj.sendall.assert_called_once_with(six.b('command'))
1358 mock_socket_obj.close.assert_called_once()
1360 @mock.patch.object(socket, 'socket')
1361 def test_execute_exception(self, mock_socket):
1362 mock_socket_obj = mock.Mock()
1363 mock_socket_obj.connect_ex.return_value = 0
1364 mock_socket.return_value = mock_socket_obj
1365 mock_socket_obj.sendall.side_effect = socket.error
1366 self.assertEqual(1, utils.send_socket_command('host', 22, 'command'))
1367 mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
1368 mock_socket_obj.connect_ex.assert_called_once_with(('host', 22))
1369 mock_socket_obj.sendall.assert_called_once_with(six.b('command'))
1370 mock_socket_obj.close.assert_called_once()
1373 class GetPortMacTestCase(unittest.TestCase):
1376 self.ssh_client = mock.Mock()
1377 self.ssh_client.execute.return_value = (0, 'foo ', '')
1379 def test_ssh_client_execute_called(self):
1380 utils.get_port_mac(self.ssh_client, 99)
1381 self.ssh_client.execute.assert_called_once_with(
1382 "ifconfig |grep HWaddr |grep 99 |awk '{print $5}' ",
1383 raise_on_error=True)
1385 def test_return_value(self):
1386 self.assertEqual('foo', utils.get_port_mac(self.ssh_client, 99))
1389 class GetPortIPTestCase(unittest.TestCase):
1392 self.ssh_client = mock.Mock()
1393 self.ssh_client.execute.return_value = (0, 'foo ', '')
1395 def test_ssh_client_execute_called(self):
1396 utils.get_port_ip(self.ssh_client, 99)
1397 self.ssh_client.execute.assert_called_once_with(
1398 "ifconfig 99 |grep 'inet addr' |awk '{print $2}' |cut -d ':' -f2 ",
1399 raise_on_error=True)
1401 def test_return_value(self):
1402 self.assertEqual('foo', utils.get_port_ip(self.ssh_client, 99))
1405 class SafeCaseTestCase(unittest.TestCase):
1407 def test_correct_type_int(self):
1408 self.assertEqual(35, utils.safe_cast('35', int, 0))
1410 def test_correct_int_as_string(self):
1411 self.assertEqual(25, utils.safe_cast('25', 'int', 0))
1413 def test_incorrect_type_as_string(self):
1414 with self.assertRaises(exceptions.InvalidType):
1415 utils.safe_cast('100', 'intt', 0)
1417 def test_default_value(self):
1418 self.assertEqual(0, utils.safe_cast('', 'int', 0))
1421 class SetupHugepagesTestCase(unittest.TestCase):
1423 @mock.patch.object(six, 'BytesIO', return_value=six.BytesIO(b'5\n'))
1424 @mock.patch.object(utils, 'read_meminfo',
1425 return_value={'Hugepagesize': '1024'})
1426 def test_setup_hugepages(self, mock_meminfo, *args):
1428 ssh.execute = mock.Mock()
1429 hp_size_kb, hp_number, hp_number_set = utils.setup_hugepages(ssh, 10 * 1024)
1430 mock_meminfo.assert_called_once_with(ssh)
1431 ssh.execute.assert_called_once_with(
1432 'echo 10 | sudo tee /proc/sys/vm/nr_hugepages')
1433 self.assertEqual(hp_size_kb, 1024)
1434 self.assertEqual(hp_number, 10)
1435 self.assertEqual(hp_number_set, 5)