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)
1139 def test_safe_ip_address(self):
1140 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1141 for addr in addr_list:
1143 expected = ipaddress.ip_address(addr)
1144 self.assertEqual(utils.safe_ip_address(addr), expected, addr)
1146 def test_safe_ip_address_v6_ip(self):
1147 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1148 for addr in addr_list:
1150 expected = ipaddress.ip_address(addr)
1151 self.assertEqual(utils.safe_ip_address(addr), expected, addr)
1153 @mock.patch("yardstick.common.utils.logging")
1154 def test_safe_ip_address_negative(self, *args):
1155 # NOTE(ralonsoh): check the calls to mocked functions.
1156 for value in self.INVALID_IP_ADDRESS_STR_LIST:
1157 self.assertIsNone(utils.safe_ip_address(value), value)
1159 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1160 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1161 for addr_mask_pair in product(addr_list, mask_list):
1162 value = ''.join(addr_mask_pair)
1163 self.assertIsNone(utils.safe_ip_address(value), value)
1165 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1166 mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1167 for addr_mask_pair in product(addr_list, mask_list):
1168 value = ''.join(addr_mask_pair)
1169 self.assertIsNone(utils.safe_ip_address(value), value)
1171 def test_get_ip_version(self):
1172 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1173 for addr in addr_list:
1175 self.assertEqual(utils.get_ip_version(addr), 4, addr)
1177 def test_get_ip_version_v6_ip(self):
1178 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1179 for addr in addr_list:
1181 self.assertEqual(utils.get_ip_version(addr), 6, addr)
1183 @mock.patch("yardstick.common.utils.logging")
1184 def test_get_ip_version_negative(self, *args):
1185 # NOTE(ralonsoh): check the calls to mocked functions.
1186 for value in self.INVALID_IP_ADDRESS_STR_LIST:
1187 self.assertIsNone(utils.get_ip_version(value), value)
1189 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1190 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1191 for addr_mask_pair in product(addr_list, mask_list):
1192 value = ''.join(addr_mask_pair)
1193 self.assertIsNone(utils.get_ip_version(value), value)
1195 addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
1196 mask_list = self.GOOD_IP_V6_MASK_STR_LIST
1197 for addr_mask_pair in product(addr_list, mask_list):
1198 value = ''.join(addr_mask_pair)
1199 self.assertIsNone(utils.get_ip_version(value), value)
1201 def test_ip_to_hex(self):
1202 self.assertEqual(utils.ip_to_hex('0.0.0.0'), '00000000')
1203 self.assertEqual(utils.ip_to_hex('10.20.30.40'), '0a141e28')
1204 self.assertEqual(utils.ip_to_hex('127.0.0.1'), '7f000001')
1205 self.assertEqual(utils.ip_to_hex('172.31.90.100'), 'ac1f5a64')
1206 self.assertEqual(utils.ip_to_hex('192.168.254.253'), 'c0a8fefd')
1207 self.assertEqual(utils.ip_to_hex('255.255.255.255'), 'ffffffff')
1209 def test_ip_to_hex_v6_ip(self):
1210 for value in self.GOOD_IP_V6_ADDRESS_STR_LIST:
1211 self.assertEqual(utils.ip_to_hex(value), value)
1213 @mock.patch("yardstick.common.utils.logging")
1214 def test_ip_to_hex_negative(self, *args):
1215 # NOTE(ralonsoh): check the calls to mocked functions.
1216 addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
1217 mask_list = self.GOOD_IP_V4_MASK_STR_LIST
1218 value_iter = (''.join(pair) for pair in product(addr_list, mask_list))
1219 for value in chain(value_iter, self.INVALID_IP_ADDRESS_STR_LIST):
1220 self.assertEqual(utils.ip_to_hex(value), value)
1222 def test_get_mask_from_ip_range_ipv4(self):
1224 for mask in range(8, 30):
1225 ip = ipaddress.ip_network(ip_str + '/' + str(mask), strict=False)
1226 result = utils.get_mask_from_ip_range(ip[2], ip[-2])
1227 self.assertEqual(mask, result)
1229 def test_get_mask_from_ip_range_ipv6(self):
1231 for mask in range(8, 120):
1232 ip = ipaddress.ip_network(ip_str + '/' + str(mask), strict=False)
1233 result = utils.get_mask_from_ip_range(ip[2], ip[-2])
1234 self.assertEqual(mask, result)
1237 class SafeDecodeUtf8TestCase(ut_base.BaseUnitTestCase):
1239 @unittest.skipIf(six.PY2,
1240 'This test should only be launched with Python 3.x')
1241 def test_safe_decode_utf8(self):
1242 _bytes = b'this is a byte array'
1243 out = utils.safe_decode_utf8(_bytes)
1244 self.assertIs(type(out), str)
1245 self.assertEqual('this is a byte array', out)
1248 class ReadMeminfoTestCase(ut_base.BaseUnitTestCase):
1250 MEMINFO = (b'MemTotal: 65860500 kB\n'
1251 b'MemFree: 28690900 kB\n'
1252 b'MemAvailable: 52873764 kB\n'
1253 b'Active(anon): 3015676 kB\n'
1254 b'HugePages_Total: 8\n'
1255 b'Hugepagesize: 1048576 kB')
1256 MEMINFO_DICT = {'MemTotal': '65860500',
1257 'MemFree': '28690900',
1258 'MemAvailable': '52873764',
1259 'Active(anon)': '3015676',
1260 'HugePages_Total': '8',
1261 'Hugepagesize': '1048576'}
1263 def test_read_meminfo(self):
1264 ssh_client = ssh.SSH('user', 'host')
1265 with mock.patch.object(ssh_client, 'get_file_obj') as \
1267 mock.patch.object(six, 'BytesIO',
1268 return_value=six.BytesIO(self.MEMINFO)):
1269 output = utils.read_meminfo(ssh_client)
1270 mock_get_client.assert_called_once_with('/proc/meminfo', mock.ANY)
1271 self.assertEqual(self.MEMINFO_DICT, output)
1274 class TimerTestCase(ut_base.BaseUnitTestCase):
1276 def test__getattr(self):
1277 with utils.Timer() as timer:
1279 self.assertEqual(1, round(timer.total_seconds(), 0))
1280 self.assertEqual(1, timer.delta.seconds)
1282 def test__enter_with_timeout(self):
1283 with utils.Timer(timeout=10) as timer:
1285 self.assertEqual(1, round(timer.total_seconds(), 0))
1287 def test__enter_with_timeout_exception(self):
1288 with self.assertRaises(exceptions.TimerTimeout):
1289 with utils.Timer(timeout=1):
1292 def test__enter_with_timeout_no_exception(self):
1293 with utils.Timer(timeout=1, raise_exception=False):
1296 def test__iter(self):
1298 for i in utils.Timer(timeout=2):
1299 iterations.append(i)
1301 self.assertEqual(2, len(iterations))
1303 def test_delta_time_sec(self):
1304 with utils.Timer() as timer:
1305 self.assertIsInstance(timer.delta_time_sec(), float)
1308 class WaitUntilTrueTestCase(ut_base.BaseUnitTestCase):
1310 def test_no_timeout(self):
1311 self.assertIsNone(utils.wait_until_true(lambda: True,
1312 timeout=1, sleep=1))
1314 def test_timeout_generic_exception(self):
1315 with self.assertRaises(exceptions.WaitTimeout):
1316 self.assertIsNone(utils.wait_until_true(lambda: False,
1317 timeout=1, sleep=1))
1319 def test_timeout_given_exception(self):
1320 class MyTimeoutException(exceptions.YardstickException):
1321 message = 'My timeout exception'
1323 with self.assertRaises(MyTimeoutException):
1325 utils.wait_until_true(lambda: False, timeout=1, sleep=1,
1326 exception=MyTimeoutException))
1328 def _run_thread(self):
1329 with self.assertRaises(exceptions.WaitTimeout):
1330 utils.wait_until_true(lambda: False, timeout=1, sleep=1)
1332 def test_timeout_no_main_thread(self):
1333 new_thread = threading.Thread(target=self._run_thread)
1335 new_thread.join(timeout=3)
1338 class SendSocketCommandTestCase(unittest.TestCase):
1340 @mock.patch.object(socket, 'socket')
1341 def test_execute_correct(self, mock_socket):
1342 mock_socket_obj = mock.Mock()
1343 mock_socket_obj.connect_ex.return_value = 0
1344 mock_socket.return_value = mock_socket_obj
1345 self.assertEqual(0, utils.send_socket_command('host', 22, 'command'))
1346 mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
1347 mock_socket_obj.connect_ex.assert_called_once_with(('host', 22))
1348 mock_socket_obj.sendall.assert_called_once_with(six.b('command'))
1349 mock_socket_obj.close.assert_called_once()
1351 @mock.patch.object(socket, 'socket')
1352 def test_execute_exception(self, mock_socket):
1353 mock_socket_obj = mock.Mock()
1354 mock_socket_obj.connect_ex.return_value = 0
1355 mock_socket.return_value = mock_socket_obj
1356 mock_socket_obj.sendall.side_effect = socket.error
1357 self.assertEqual(1, utils.send_socket_command('host', 22, 'command'))
1358 mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
1359 mock_socket_obj.connect_ex.assert_called_once_with(('host', 22))
1360 mock_socket_obj.sendall.assert_called_once_with(six.b('command'))
1361 mock_socket_obj.close.assert_called_once()
1364 class GetPortMacTestCase(unittest.TestCase):
1367 self.ssh_client = mock.Mock()
1368 self.ssh_client.execute.return_value = (0, 'foo ', '')
1370 def test_ssh_client_execute_called(self):
1371 utils.get_port_mac(self.ssh_client, 99)
1372 self.ssh_client.execute.assert_called_once_with(
1373 "ifconfig |grep HWaddr |grep 99 |awk '{print $5}' ",
1374 raise_on_error=True)
1376 def test_return_value(self):
1377 self.assertEqual('foo', utils.get_port_mac(self.ssh_client, 99))
1380 class GetPortIPTestCase(unittest.TestCase):
1383 self.ssh_client = mock.Mock()
1384 self.ssh_client.execute.return_value = (0, 'foo ', '')
1386 def test_ssh_client_execute_called(self):
1387 utils.get_port_ip(self.ssh_client, 99)
1388 self.ssh_client.execute.assert_called_once_with(
1389 "ifconfig 99 |grep 'inet addr' |awk '{print $2}' |cut -d ':' -f2 ",
1390 raise_on_error=True)
1392 def test_return_value(self):
1393 self.assertEqual('foo', utils.get_port_ip(self.ssh_client, 99))