3 # jose.lausuch@ericsson.com
4 # valentin.boucher@orange.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
21 from six.moves import urllib
24 from functest.utils import constants
26 logger = logging.getLogger(__name__)
29 # ----------------------------------------------------------
33 # -----------------------------------------------------------
34 def check_internet_connectivity(url='http://www.opnfv.org/'):
36 Check if there is access to the internet
39 urllib.request.urlopen(url, timeout=5)
41 except urllib.error.URLError:
45 def download_url(url, dest_path):
47 Download a file to a destination path given a URL
49 name = url.rsplit('/')[-1]
50 dest = dest_path + "/" + name
52 response = urllib.request.urlopen(url)
53 except (urllib.error.HTTPError, urllib.error.URLError):
56 with open(dest, 'wb') as f:
57 shutil.copyfileobj(response, f)
61 # ----------------------------------------------------------
65 # -----------------------------------------------------------
66 def get_resolvconf_ns():
68 Get nameservers from current resolv.conf
71 rconf = open("/etc/resolv.conf", "r")
72 line = rconf.readline()
73 resolver = dns.resolver.Resolver()
75 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
77 resolver.nameservers = [ip.group(0)]
79 result = resolver.query('opnfv.org')[0]
81 nameservers.append(ip.group())
82 except dns.exception.Timeout:
84 line = rconf.readline()
90 Get the CI env variables
93 "installer": os.environ.get('INSTALLER_TYPE'),
94 "scenario": os.environ.get('DEPLOY_SCENARIO')}
98 def execute_command_raise(cmd, info=False, error_msg="",
99 verbose=True, output_file=None):
100 ret = execute_command(cmd, info, error_msg, verbose, output_file)
102 raise Exception(error_msg)
105 def execute_command(cmd, info=False, error_msg="",
106 verbose=True, output_file=None):
108 error_msg = ("The command '%s' failed." % cmd)
109 msg_exec = ("Executing command: '%s'" % cmd)
112 logger.info(msg_exec)
114 logger.debug(msg_exec)
115 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
116 stderr=subprocess.STDOUT)
118 f = open(output_file, "w")
119 for line in iter(p.stdout.readline, b''):
123 line = line.replace('\n', '')
129 returncode = p.wait()
132 logger.error(error_msg)
137 def get_dict_by_test(testname):
138 with open(pkg_resources.resource_filename(
139 'functest', 'ci/testcases.yaml')) as f:
140 testcases_yaml = yaml.safe_load(f)
142 for dic_tier in testcases_yaml.get("tiers"):
143 for dic_testcase in dic_tier['testcases']:
144 if dic_testcase['case_name'] == testname:
147 logger.error('Project %s is not defined in testcases.yaml' % testname)
151 def get_criteria_by_test(testname):
152 dict = get_dict_by_test(testname)
154 return dict['criteria']
158 # ----------------------------------------------------------
162 # -----------------------------------------------------------
163 def get_parameter_from_yaml(parameter, file):
165 Returns the value of a given parameter in file.yaml
166 parameter must be given in string format with dots
167 Example: general.openstack.image_name
169 with open(file) as f:
170 file_yaml = yaml.safe_load(f)
173 for element in parameter.split("."):
174 value = value.get(element)
176 raise ValueError("The parameter %s is not defined in"
177 " %s" % (parameter, file))
181 def get_functest_config(parameter):
182 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
183 return get_parameter_from_yaml(parameter, yaml_)
186 def get_functest_yaml():
187 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
188 functest_yaml = yaml.safe_load(f)
193 def print_separator():
194 logger.info("==============================================")
198 """Measure the time it takes for a function to complete"""
199 @functools.wraps(func)
200 def timed(*args, **kwargs):
202 result = func(*args, **kwargs)
204 elapsed = '{0}'.format(te - ts)
205 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
206 f=func.__name__, a=args, kw=kwargs, t=elapsed))
207 return result, elapsed