Merge "Open storperf testcase to huawei-pod2"
[yardstick.git] / 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 # Unittest for yardstick.common.utils
11
12 from __future__ import absolute_import
13 import os
14 import mock
15 import unittest
16
17 from yardstick.common import utils
18
19
20 class IterSubclassesTestCase(unittest.TestCase):
21     # Disclaimer: this class is a modified copy from
22     # rally/tests/unit/common/plugin/test_discover.py
23     # Copyright 2015: Mirantis Inc.
24
25     def test_itersubclasses(self):
26         class A(object):
27             pass
28
29         class B(A):
30             pass
31
32         class C(A):
33             pass
34
35         class D(C):
36             pass
37
38         self.assertEqual([B, C, D], list(utils.itersubclasses(A)))
39
40
41 class TryAppendModuleTestCase(unittest.TestCase):
42
43     @mock.patch('yardstick.common.utils.importutils')
44     def test_try_append_module_not_in_modules(self, mock_importutils):
45
46         modules = {}
47         name = 'foo'
48         utils.try_append_module(name, modules)
49         mock_importutils.import_module.assert_called_with(name)
50
51     @mock.patch('yardstick.common.utils.importutils')
52     def test_try_append_module_already_in_modules(self, mock_importutils):
53
54         modules = {'foo'}
55         name = 'foo'
56         utils.try_append_module(name, modules)
57         self.assertFalse(mock_importutils.import_module.called)
58
59
60 class ImportModulesFromPackageTestCase(unittest.TestCase):
61
62     @mock.patch('yardstick.common.utils.os.walk')
63     @mock.patch('yardstick.common.utils.try_append_module')
64     def test_import_modules_from_package_no_mod(self, mock_append, mock_walk):
65
66         sep = os.sep
67         mock_walk.return_value = ([
68             ('..' + sep + 'foo', ['bar'], ['__init__.py']),
69             ('..' + sep + 'foo' + sep + 'bar', [], ['baz.txt', 'qux.rst'])
70         ])
71
72         utils.import_modules_from_package('foo.bar')
73         self.assertFalse(mock_append.called)
74
75     @mock.patch('yardstick.common.utils.os.walk')
76     @mock.patch('yardstick.common.utils.importutils')
77     def test_import_modules_from_package(self, mock_importutils, mock_walk):
78
79         sep = os.sep
80         mock_walk.return_value = ([
81             ('foo' + sep + '..' + sep + 'bar', [], ['baz.py'])
82         ])
83
84         utils.import_modules_from_package('foo.bar')
85         mock_importutils.import_module.assert_called_with('bar.baz')
86
87
88 class GetParaFromYaml(unittest.TestCase):
89
90     @mock.patch('yardstick.common.utils.os.environ.get')
91     def test_get_param_para_not_found(self, get_env):
92         file_path = 'config_sample.yaml'
93         get_env.return_value = self._get_file_abspath(file_path)
94         args = 'releng.file'
95         default = 'hello'
96         self.assertTrue(utils.get_param(args, default), default)
97
98     @mock.patch('yardstick.common.utils.os.environ.get')
99     def test_get_param_para_exists(self, get_env):
100         file_path = 'config_sample.yaml'
101         get_env.return_value = self._get_file_abspath(file_path)
102         args = 'releng.dir'
103         para = '/home/opnfv/repos/releng'
104         self.assertEqual(para, utils.get_param(args))
105
106     def _get_file_abspath(self, filename):
107         curr_path = os.path.dirname(os.path.abspath(__file__))
108         file_path = os.path.join(curr_path, filename)
109         return file_path
110
111
112 class CommonUtilTestCase(unittest.TestCase):
113
114     def setUp(self):
115         self.data = {
116             "benchmark": {
117                 "data": {
118                     "mpstat": {
119                         "cpu0": {
120                             "%sys": "0.00",
121                             "%idle": "99.00"
122                         },
123                         "loadavg": [
124                             "1.09",
125                             "0.29"
126                         ]
127                     },
128                     "rtt": "1.03"
129                 }
130             }
131         }
132
133     def test__dict_key_flatten(self):
134         line = 'mpstat.loadavg1=0.29,rtt=1.03,mpstat.loadavg0=1.09,' \
135                'mpstat.cpu0.%idle=99.00,mpstat.cpu0.%sys=0.00'
136         # need to sort for assert to work
137         line = ",".join(sorted(line.split(',')))
138         flattened_data = utils.flatten_dict_key(
139             self.data['benchmark']['data'])
140         result = ",".join(
141             ("=".join(item) for item in sorted(flattened_data.items())))
142         self.assertEqual(result, line)
143
144
145 class TranslateToStrTestCase(unittest.TestCase):
146
147     def test_translate_to_str_unicode(self):
148         input_str = u'hello'
149         output_str = utils.translate_to_str(input_str)
150
151         result = 'hello'
152         self.assertEqual(result, output_str)
153
154     def test_translate_to_str_dict_list_unicode(self):
155         input_str = {
156             u'hello': {u'hello': [u'world']}
157         }
158         output_str = utils.translate_to_str(input_str)
159
160         result = {
161             'hello': {'hello': ['world']}
162         }
163         self.assertEqual(result, output_str)
164
165
166 class ChangeObjToDictTestCase(unittest.TestCase):
167
168     def test_change_obj_to_dict(self):
169         class A(object):
170             def __init__(self):
171                 self.name = 'yardstick'
172
173         obj = A()
174         obj_r = utils.change_obj_to_dict(obj)
175         obj_s = {'name': 'yardstick'}
176         self.assertEqual(obj_r, obj_s)
177
178
179 class SetDictValueTestCase(unittest.TestCase):
180
181     def test_set_dict_value(self):
182         input_dic = {
183             'hello': 'world'
184         }
185         output_dic = utils.set_dict_value(input_dic, 'welcome.to', 'yardstick')
186         self.assertEqual(output_dic.get('welcome', {}).get('to'), 'yardstick')
187
188
189 class RemoveFileTestCase(unittest.TestCase):
190
191     def test_remove_file(self):
192         try:
193             utils.remove_file('notexistfile.txt')
194         except Exception as e:
195             self.assertTrue(isinstance(e, OSError))
196
197
198 def main():
199     unittest.main()
200
201 if __name__ == '__main__':
202     main()