Modify TestCase constructor attributes
[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 json
10 import os
11 import shutil
12
13 import requests
14
15 import functest.core.vnf_base as vnf_base
16 from functest.utils.constants import CONST
17 import functest.utils.functest_logger as ft_logger
18 import functest.utils.functest_utils as ft_utils
19
20
21 class ClearwaterOnBoardingBase(vnf_base.VnfOnBoardingBase):
22
23     def __init__(self, **kwargs):
24         self.logger = ft_logger.Logger(__name__).getLogger()
25         super(ClearwaterOnBoardingBase, self).__init__(**kwargs)
26         self.case_dir = os.path.join(CONST.dir_functest_test, 'vnf', 'ims')
27         self.data_dir = CONST.dir_ims_data
28         self.result_dir = os.path.join(CONST.dir_results, self.case_name)
29         self.test_dir = CONST.dir_repo_vims_test
30
31         if not os.path.exists(self.data_dir):
32             os.makedirs(self.data_dir)
33         if not os.path.exists(self.result_dir):
34             os.makedirs(self.result_dir)
35
36     def config_ellis(self, ellis_ip, signup_code='secret', two_numbers=False):
37         output_dict = {}
38         self.logger.info('Configure Ellis: %s', ellis_ip)
39         output_dict['ellis_ip'] = ellis_ip
40         account_url = 'http://{0}/accounts'.format(ellis_ip)
41         params = {"password": "functest",
42                   "full_name": "opnfv functest user",
43                   "email": "functest@opnfv.org",
44                   "signup_code": signup_code}
45         rq = requests.post(account_url, data=params)
46         output_dict['login'] = params
47         if rq.status_code != 201 and rq.status_code != 409:
48             raise Exception("Unable to create an account for number provision")
49         self.logger.info('Account is created on Ellis: %s', params)
50
51         session_url = 'http://{0}/session'.format(ellis_ip)
52         session_data = {
53             'username': params['email'],
54             'password': params['password'],
55             'email': params['email']
56         }
57         rq = requests.post(session_url, data=session_data)
58         if rq.status_code != 201:
59             raise Exception('Failed to get cookie for Ellis')
60         cookies = rq.cookies
61         self.logger.info('Cookies: %s' % cookies)
62
63         number_url = 'http://{0}/accounts/{1}/numbers'.format(
64                      ellis_ip,
65                      params['email'])
66         self.logger.info('Create 1st calling number on Ellis')
67         number_res = self.create_ellis_number(number_url, cookies)
68         output_dict['number'] = number_res
69
70         if two_numbers:
71             self.logger.info('Create 2nd calling number on Ellis')
72             number_res = self.create_ellis_number(number_url, cookies)
73             output_dict['number2'] = number_res
74
75         return output_dict
76
77     def create_ellis_number(self, number_url, cookies):
78         rq = requests.post(number_url, cookies=cookies)
79
80         if rq.status_code != 200:
81             if rq and rq.json():
82                 reason = rq.json()['reason']
83             else:
84                 reason = rq
85             raise Exception("Unable to create a number: %s" % reason)
86         number_res = rq.json()
87         self.logger.info('Calling number is created: %s', number_res)
88         return number_res
89
90     def run_clearwater_live_test(self, dns_ip, public_domain,
91                                  bono_ip=None, ellis_ip=None,
92                                  signup_code='secret'):
93         self.logger.info('Run Clearwater live test')
94         nameservers = ft_utils.get_resolvconf_ns()
95         resolvconf = ['{0}{1}{2}'.format(os.linesep, 'nameserver ', ns)
96                       for ns in nameservers]
97         self.logger.debug('resolvconf: %s', resolvconf)
98         dns_file = '/etc/resolv.conf'
99         dns_file_bak = '/etc/resolv.conf.bak'
100         shutil.copy(dns_file, dns_file_bak)
101         script = ('echo -e "nameserver {0}{1}" > {2};'
102                   'source /etc/profile.d/rvm.sh;'
103                   'cd {3};'
104                   'rake test[{4}] SIGNUP_CODE={5}'
105                   .format(dns_ip,
106                           ''.join(resolvconf),
107                           dns_file,
108                           self.test_dir,
109                           public_domain,
110                           signup_code))
111         if bono_ip and ellis_ip:
112             subscript = ' PROXY={0} ELLIS={1}'.format(bono_ip, ellis_ip)
113             script = '{0}{1}'.format(script, subscript)
114         script = ('{0}{1}'.format(script, ' --trace'))
115         cmd = "/bin/bash -c '{0}'".format(script)
116         self.logger.info('Live test cmd: %s', cmd)
117         output_file = os.path.join(self.result_dir, "ims_test_output.txt")
118         ft_utils.execute_command(cmd,
119                                  error_msg='Clearwater live test failed',
120                                  output_file=output_file)
121
122         with open(dns_file_bak, 'r') as bak_file:
123             result = bak_file.read()
124             with open(dns_file, 'w') as f:
125                 f.write(result)
126
127         f = open(output_file, 'r')
128         result = f.read()
129         if result != "":
130             self.logger.debug(result)
131
132         vims_test_result = ""
133         tempFile = os.path.join(self.test_dir, "temp.json")
134         try:
135             self.logger.debug("Trying to load test results")
136             with open(tempFile) as f:
137                 vims_test_result = json.load(f)
138             f.close()
139         except Exception:
140             self.logger.error("Unable to retrieve test results")
141
142         try:
143             os.remove(tempFile)
144         except Exception:
145             self.logger.error("Deleting file failed")
146
147         return vims_test_result