aboutsummaryrefslogtreecommitdiffstats
path: root/functest/tests/unit/utils/test_functest_utils.py
blob: 4ec20589447809ecf18b63499a5d009e0394dd86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env python

# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

# pylint: disable=missing-docstring

import logging
import time
import unittest

import mock
import pkg_resources
import six

from functest.utils import functest_utils


class FunctestUtilsTesting(unittest.TestCase):
    # pylint: disable=too-many-instance-attributes,too-many-public-methods

    readline = 0
    test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']

    def setUp(self):
        self.url = 'http://www.opnfv.org/'
        self.timeout = 5
        self.dest_path = 'test_path'
        self.repo_path = 'test_repo_path'
        self.installer = 'test_installer'
        self.scenario = 'test_scenario'
        self.build_tag = 'jenkins-functest-fuel-opnfv-jump-2-daily-master-190'
        self.build_tag_week = 'jenkins-functest-fuel-baremetal-weekly-master-8'
        self.version = 'master'
        self.node_name = 'test_node_name'
        self.project = 'test_project'
        self.case_name = 'test_case_name'
        self.status = 'test_status'
        self.details = 'test_details'
        self.db_url = 'test_db_url'
        self.criteria = 50
        self.result = 75
        self.start_date = 1482624000
        self.stop_date = 1482624000
        self.start_time = time.time()
        self.stop_time = time.time()
        self.readline = -1
        self.test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
        self.test_file = 'test_file'
        self.error_msg = 'test_error_msg'
        self.cmd = 'test_cmd'
        self.output_file = 'test_output_file'
        self.testname = 'testname'
        self.parameter = 'general.openstack.image_name'
        self.config_yaml = pkg_resources.resource_filename(
            'functest', 'ci/config_functest.yaml')
        self.db_url_env = 'http://foo/testdb'
        self.testcases_yaml = "test_testcases_yaml"
        self.file_yaml = {'general': {'openstack': {'image_name':
                                                    'test_image_name'}}}

    def _get_env_dict(self, var):
        dic = {'INSTALLER_TYPE': self.installer,
               'DEPLOY_SCENARIO': self.scenario,
               'NODE_NAME': self.node_name,
               'BUILD_TAG': self.build_tag}
        dic.pop(var, None)
        return dic

    @staticmethod
    def readline_side():
        if FunctestUtilsTesting.readline == \
                len(FunctestUtilsTesting.test_ip) - 1:
            return False
        FunctestUtilsTesting.readline += 1
        return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]

    def _get_environ(self, var, *args):  # pylint: disable=unused-argument
        if var == 'INSTALLER_TYPE':
            return self.installer
        elif var == 'DEPLOY_SCENARIO':
            return self.scenario
        return var

    @staticmethod
    def cmd_readline():
        return 'test_value\n'

    @mock.patch('functest.utils.functest_utils.LOGGER.error')
    @mock.patch('functest.utils.functest_utils.LOGGER.info')
    def test_exec_cmd_args_present_ko(self, mock_logger_info,
                                      mock_logger_error):
        with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
                as mock_subproc_open, \
                mock.patch('six.moves.builtins.open',
                           mock.mock_open()) as mopen:
            stream = six.BytesIO()
            stream.write(self.cmd_readline().encode("utf-8"))
            mock_obj2 = mock.Mock()
            attrs = {'stdout': stream, 'wait.return_value': 1}
            mock_obj2.configure_mock(**attrs)
            mock_subproc_open.return_value = mock_obj2
            resp = functest_utils.execute_command(
                self.cmd, info=True, error_msg=self.error_msg, verbose=True,
                output_file=self.output_file)
            self.assertEqual(resp, 1)
            msg_exec = ("Executing command: '%s'" % self.cmd)
            mock_logger_info.assert_called_once_with(msg_exec)
            mopen.assert_called_once_with(self.output_file, "w")
            mock_logger_error.assert_called_once_with(self.error_msg)

    @mock.patch('functest.utils.functest_utils.LOGGER.info')
    def test_exec_cmd_args_present_ok(self, mock_logger_info):
        with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
                as mock_subproc_open, \
                mock.patch('six.moves.builtins.open',
                           mock.mock_open()) as mopen:
            stream = six.BytesIO()
            stream.write(self.cmd_readline().encode("utf-8"))
            mock_obj2 = mock.Mock()
            attrs = {'stdout': stream, 'wait.return_value': 0}
            mock_obj2.configure_mock(**attrs)
            mock_subproc_open.return_value = mock_obj2
            resp = functest_utils.execute_command(
                self.cmd, info=True, error_msg=self.error_msg, verbose=True,
                output_file=self.output_file)
            self.assertEqual(resp, 0)
            msg_exec = ("Executing command: '%s'" % self.cmd)
            mock_logger_info.assert_called_once_with(msg_exec)
            mopen.assert_called_once_with(self.output_file, "w")

    @mock.patch('sys.stdout')
    def test_exec_cmd_args_missing_ok(self, stdout=None):
        # pylint: disable=unused-argument
        with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
                as mock_subproc_open:
            stream = six.BytesIO()
            stream.write(self.cmd_readline().encode("utf-8"))
            mock_obj2 = mock.Mock()
            attrs = {'stdout': stream, 'wait.return_value': 0}
            mock_obj2.configure_mock(**attrs)
            mock_subproc_open.return_value = mock_obj2
            resp = functest_utils.execute_command(
                self.cmd, info=False, error_msg="", verbose=False,
                output_file=None)
            self.assertEqual(resp, 0)

    @mock.patch('sys.stdout')
    def test_exec_cmd_args_missing_ko(self, stdout=None):
        # pylint: disable=unused-argument
        with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
                as mock_subproc_open:
            stream = six.BytesIO()
            stream.write(self.cmd_readline().encode("utf-8"))
            mock_obj2 = mock.Mock()
            attrs = {'stdout': stream, 'wait.return_value': 1}
            mock_obj2.configure_mock(**attrs)
            mock_subproc_open.return_value = mock_obj2
            resp = functest_utils.execute_command(
                self.cmd, info=False, error_msg="", verbose=False,
                output_file=None)
            self.assertEqual(resp, 1)

    def test_get_param_from_yaml_failed(self):
        self.file_yaml['general'] = None
        with mock.patch('six.moves.builtins.open', mock.mock_open()), \
                mock.patch('functest.utils.functest_utils.yaml.safe_load') \
                as mock_yaml, \
                self.assertRaises(ValueError) as excep:
            mock_yaml.return_value = self.file_yaml
            functest_utils.get_parameter_from_yaml(self.parameter,
                                                   self.test_file)
            self.assertTrue(("The parameter %s is not"
                             " defined in config_functest.yaml" %
                             self.parameter) in excep.exception)

    def test_get_param_from_yaml_def(self):
        with mock.patch('six.moves.builtins.open', mock.mock_open()), \
                mock.patch('functest.utils.functest_utils.yaml.safe_load') \
                as mock_yaml:
            mock_yaml.return_value = self.file_yaml
            self.assertEqual(functest_utils.
                             get_parameter_from_yaml(self.parameter,
                                                     self.test_file),
                             'test_image_name')

    def test_nova_version_exc1(self):
        # pylint: disable=protected-access
        cloud = mock.Mock()
        cloud._compute_client.request.return_value = None
        self.assertEqual(functest_utils.get_nova_version(cloud), None)
        cloud._compute_client.request.assert_called_once_with('/', 'GET')

    def test_nova_version_exc2(self):
        # pylint: disable=protected-access
        cloud = mock.Mock()
        cloud._compute_client.request.return_value = {"version": None}
        self.assertEqual(functest_utils.get_nova_version(cloud), None)
        cloud._compute_client.request.assert_called_once_with('/', 'GET')

    def test_nova_version_exc3(self):
        # pylint: disable=protected-access
        cloud = mock.Mock()
        cloud._compute_client.request.return_value = {
            "version": {"version": None}}
        self.assertEqual(functest_utils.get_nova_version(cloud), None)
        cloud._compute_client.request.assert_called_once_with('/', 'GET')

    def test_nova_version_exc4(self):
        # pylint: disable=protected-access
        cloud = mock.Mock()
        cloud._compute_client.request.return_value = {
            "version": {"version": "a.b"}}
        self.assertEqual(functest_utils.get_nova_version(cloud), None)
        cloud._compute_client.request.assert_called_once_with('/', 'GET')

    def test_nova_version(self):
        # pylint: disable=protected-access
        cloud = mock.Mock()
        cloud._compute_client.request.return_value = {
            "version": {"version": "2.1"}}
        self.assertEqual(functest_utils.get_nova_version(cloud), (2, 1))
        cloud._compute_client.request.assert_called_once_with('/', 'GET')

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 61))
    def test_openstack_version1(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(
            cloud), "Rocky")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 60))
    def test_openstack_version2(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Queens")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 43))
    def test_openstack_version3(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Pike")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 39))
    def test_openstack_version4(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Ocata")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 26))
    def test_openstack_version5(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Newton")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 13))
    def test_openstack_version6(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Mitaka")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 4))
    def test_openstack_version7(self, *args):
        cloud = mock.Mock()
        self.assertEqual(
            functest_utils.get_openstack_version(cloud), "Liberty")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 1))
    def test_openstack_version8(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(cloud), "Kilo")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(1, 9))
    def test_openstack_version9(self, *args):
        cloud = mock.Mock()
        self.assertEqual(
            functest_utils.get_openstack_version(cloud), "Unknown")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(3, 1))
    def test_openstack_version10(self, *args):
        cloud = mock.Mock()
        self.assertEqual(
            functest_utils.get_openstack_version(cloud), "Master")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=(2, 66))
    def test_openstack_version11(self, *args):
        cloud = mock.Mock()
        self.assertEqual(functest_utils.get_openstack_version(
            cloud), "Stein")
        args[0].assert_called_once_with(cloud)

    @mock.patch('functest.utils.functest_utils.get_nova_version',
                return_value=None)
    def test_openstack_version_exc(self, *args):
        cloud = mock.Mock()
        self.assertEqual(
            functest_utils.get_openstack_version(cloud), "Unknown")
        args[0].assert_called_once_with(cloud)

    def test_convert_dict_to_ini(self):
        self.assertEqual(
            functest_utils.convert_dict_to_ini({}), "")
        self.assertEqual(
            functest_utils.convert_dict_to_ini({"a": "b"}), "a:b")
        value = functest_utils.convert_dict_to_ini({"a": "b", "c": "d"})
        self.assertTrue(value == "a:b,c:d" or value == "c:d,a:b")
        with self.assertRaises(AssertionError):
            functest_utils.convert_list_to_ini("")

    def test_convert_list_to_ini(self):
        self.assertEqual(
            functest_utils.convert_list_to_ini([]), "")
        self.assertEqual(
            functest_utils.convert_list_to_ini(["a"]), "a")
        self.assertEqual(
            functest_utils.convert_list_to_ini(["a", "b"]), "a,b")
        with self.assertRaises(AssertionError):
            functest_utils.convert_list_to_ini("")

    def test_convert_ini_to_dict(self):
        self.assertEqual(
            functest_utils.convert_ini_to_dict(""), {})
        self.assertEqual(
            functest_utils.convert_ini_to_dict("a:b"), {"a": "b"})
        self.assertEqual(
            functest_utils.convert_ini_to_dict(
                "a:b,c:d"), {"a": "b", "c": "d"})
        self.assertEqual(
            functest_utils.convert_ini_to_dict(
                "a:b:c,d:e:f"), {"a:b": "c", "d:e": "f"})
        with self.assertRaises(AssertionError):
            functest_utils.convert_list_to_ini({})

    def test_convert_ini_to_list(self):
        self.assertEqual(
            functest_utils.convert_ini_to_list(""), [])
        self.assertEqual(
            functest_utils.convert_ini_to_list("a"), ["a"])
        self.assertEqual(
            functest_utils.convert_ini_to_list("a,b"), ["a", "b"])
        with self.assertRaises(AssertionError):
            functest_utils.convert_ini_to_list([])


if __name__ == "__main__":
    logging.disable(logging.CRITICAL)
    unittest.main(verbosity=2)