Fix pylint warnings in clearwater_ims_base
[functest.git] / functest / opnfv_tests / vnf / ims / clearwater_ims_base.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2017 All rights reserved
4 # 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 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 import logging
10 import os
11 import re
12 import shlex
13 import shutil
14 import subprocess
15 import time
16
17 import pkg_resources
18 import requests
19
20 import functest.core.vnf as vnf
21 from functest.utils import config
22 import functest.utils.functest_utils as ft_utils
23
24 __author__ = ("Valentin Boucher <valentin.boucher@orange.com>, "
25               "Helen Yao <helanyao@gmail.com>")
26
27
28 class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
29     """ vIMS clearwater base usable by several orchestrators"""
30
31     def __init__(self, **kwargs):
32         self.logger = logging.getLogger(__name__)
33         super(ClearwaterOnBoardingBase, self).__init__(**kwargs)
34         self.case_dir = pkg_resources.resource_filename(
35             'functest', 'opnfv_tests/vnf/ims')
36         self.data_dir = getattr(config.CONF, 'dir_ims_data')
37         self.result_dir = os.path.join(getattr(config.CONF, 'dir_results'),
38                                        self.case_name)
39         self.test_dir = getattr(config.CONF, 'dir_repo_vims_test')
40
41         if not os.path.exists(self.data_dir):
42             os.makedirs(self.data_dir)
43         if not os.path.exists(self.result_dir):
44             os.makedirs(self.result_dir)
45
46     def config_ellis(self, ellis_ip, signup_code='secret', two_numbers=False):
47         output_dict = {}
48         self.logger.debug('Configure Ellis: %s', ellis_ip)
49         output_dict['ellis_ip'] = ellis_ip
50         account_url = 'http://{0}/accounts'.format(ellis_ip)
51         params = {"password": "functest",
52                   "full_name": "opnfv functest user",
53                   "email": "functest@opnfv.org",
54                   "signup_code": signup_code}
55         req = requests.post(account_url, data=params)
56         output_dict['login'] = params
57         if req.status_code != 201 and req.status_code != 409:
58             raise Exception(
59                 "Unable to create an account {}\n{}".format(
60                     params, req.text))
61         self.logger.debug(
62             'Account %s is created on Ellis\n%s', params, req.json())
63
64         session_url = 'http://{0}/session'.format(ellis_ip)
65         session_data = {
66             'username': params['email'],
67             'password': params['password'],
68             'email': params['email']
69         }
70         req = requests.post(session_url, data=session_data)
71         if req.status_code != 201:
72             raise Exception('Failed to get cookie for Ellis\n{}'.format(
73                 req.text))
74         cookies = req.cookies
75         self.logger.debug('Cookies: %s', cookies)
76
77         number_url = 'http://{0}/accounts/{1}/numbers'.format(
78             ellis_ip, params['email'])
79         self.logger.debug('Create 1st calling number on Ellis')
80         i = 30
81         while req.status_code != 200 and i > 0:
82             try:
83                 number_res = self._create_ellis_number(number_url, cookies)
84                 break
85             except Exception:  # pylint: disable=broad-except
86                 if i == 1:
87                     self.logger.exception("Unable to create a number")
88                     raise Exception("Unable to create a number")
89                 self.logger.info("Unable to create a number. Retry ..")
90                 time.sleep(25)
91             i = i - 1
92         output_dict['number'] = number_res
93
94         if two_numbers:
95             self.logger.debug('Create 2nd calling number on Ellis')
96             number_res = self._create_ellis_number(number_url, cookies)
97             output_dict['number2'] = number_res
98
99         return output_dict
100
101     def _create_ellis_number(self, number_url, cookies):
102         req = requests.post(number_url, cookies=cookies)
103
104         if req.status_code != 200:
105             if req and req.json():
106                 reason = req.json()['reason']
107             else:
108                 reason = req
109             raise Exception("Unable to create a number: %s" % reason)
110         number_res = req.json()
111         self.logger.info('Calling number is created: %s', number_res)
112         return number_res
113
114     def run_clearwater_live_test(self, dns_ip, public_domain,
115                                  bono_ip=None, ellis_ip=None,
116                                  signup_code='secret'):
117         # pylint: disable=too-many-locals,too-many-arguments
118         self.logger.info('Run Clearwater live test')
119         dns_file = '/etc/resolv.conf'
120         dns_file_bak = '/etc/resolv.conf.bak'
121         self.logger.debug('Backup %s -> %s', dns_file, dns_file_bak)
122         shutil.copy(dns_file, dns_file_bak)
123         cmd = ("dnsmasq -d -u root --server=/clearwater.opnfv/{0} "
124                "-r /etc/resolv.conf.bak".format(dns_ip))
125         dnsmasq_process = subprocess.Popen(shlex.split(cmd))
126         script = ('echo -e "nameserver {0}" > {1};'
127                   'cd {2};'
128                   'rake test[{3}] SIGNUP_CODE={4}'
129                   .format('127.0.0.1',
130                           dns_file,
131                           self.test_dir,
132                           public_domain,
133                           signup_code))
134         if bono_ip and ellis_ip:
135             subscript = ' PROXY={0} ELLIS={1}'.format(bono_ip, ellis_ip)
136             script = '{0}{1}'.format(script, subscript)
137         script = ('{0}{1}'.format(script, ' --trace'))
138         cmd = "/bin/bash -c '{0}'".format(script)
139         self.logger.debug('Live test cmd: %s', cmd)
140         output_file = os.path.join(self.result_dir, "ims_test_output.txt")
141         ft_utils.execute_command(cmd,
142                                  error_msg='Clearwater live test failed',
143                                  output_file=output_file)
144         dnsmasq_process.kill()
145         with open(dns_file_bak, 'r') as bak_file:
146             result = bak_file.read()
147             with open(dns_file, 'w') as dfile:
148                 dfile.write(result)
149
150         with open(output_file, 'r') as ofile:
151             result = ofile.read()
152
153         if result != "":
154             self.logger.debug(result)
155
156         vims_test_result = {}
157         try:
158             grp = re.search(
159                 r'(\d+) failures out of (\d+) tests run.*'
160                 r'(\d+) tests skipped', result, re.MULTILINE | re.DOTALL)
161             assert grp
162             vims_test_result["failures"] = int(grp.group(1))
163             vims_test_result["total"] = int(grp.group(2))
164             vims_test_result["skipped"] = int(grp.group(3))
165             vims_test_result['passed'] = (
166                 int(grp.group(2)) - int(grp.group(3)) - int(grp.group(1)))
167         except Exception:  # pylint: disable=broad-except
168             self.logger.exception("Cannot parse live tests results")
169             return None
170         return vims_test_result