aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJuha Kosonen <juha.kosonen@nokia.com>2018-02-09 17:35:46 +0200
committerJuha Kosonen <juha.kosonen@nokia.com>2018-02-09 17:35:46 +0200
commit918eafbc4b9a71a2e7be062aaccaa073a86772ee (patch)
tree97d29b23ad9b24026cbcea798bce33b6cf94f3b8
parent9fd0361c6361b061eae3851e61f9d16edffc6de7 (diff)
Fix pylint errors/warnings in tempest modules
JIRA: FUNCTEST-913 Change-Id: I37b25bbcf43fb1d6f7de0c815ad49070d1e1af12 Signed-off-by: Juha Kosonen <juha.kosonen@nokia.com>
-rw-r--r--functest/opnfv_tests/openstack/tempest/conf_utils.py103
-rw-r--r--functest/opnfv_tests/openstack/tempest/tempest.py206
-rw-r--r--functest/tests/unit/openstack/tempest/test_conf_utils.py45
-rw-r--r--functest/tests/unit/openstack/tempest/test_tempest.py58
-rw-r--r--tox.ini2
5 files changed, 226 insertions, 188 deletions
diff --git a/functest/opnfv_tests/openstack/tempest/conf_utils.py b/functest/opnfv_tests/openstack/tempest/conf_utils.py
index e61ab813..6b35b96e 100644
--- a/functest/opnfv_tests/openstack/tempest/conf_utils.py
+++ b/functest/opnfv_tests/openstack/tempest/conf_utils.py
@@ -7,6 +7,9 @@
#
# http://www.apache.org/licenses/LICENSE-2.0
#
+
+"""Tempest configuration utilities."""
+
import ConfigParser
import logging
import fileinput
@@ -52,31 +55,32 @@ CI_INSTALLER_TYPE = CONST.__getattribute__('INSTALLER_TYPE')
CI_INSTALLER_IP = CONST.__getattribute__('INSTALLER_IP')
""" logging configuration """
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
def create_rally_deployment():
+ """Create new rally deployment"""
# set the architecture to default
pod_arch = os.getenv("POD_ARCH", None)
arch_filter = ['aarch64']
if pod_arch and pod_arch in arch_filter:
- logger.info("Apply aarch64 specific to rally config...")
- with open(RALLY_AARCH64_PATCH_PATH, "r") as f:
- rally_patch_conf = f.read()
+ LOGGER.info("Apply aarch64 specific to rally config...")
+ with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile:
+ rally_patch_conf = pfile.read()
for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
print line,
if "cirros|testvm" in line:
print rally_patch_conf
- logger.info("Creating Rally environment...")
+ LOGGER.info("Creating Rally environment...")
cmd = "rally deployment destroy opnfv-rally"
ft_utils.execute_command(cmd, error_msg=(
"Deployment %s does not exist."
% CONST.__getattribute__('rally_deployment_name')),
- verbose=False)
+ verbose=False)
cmd = ("rally deployment create --fromenv --name={0}"
.format(CONST.__getattribute__('rally_deployment_name')))
@@ -89,13 +93,14 @@ def create_rally_deployment():
def create_verifier():
- logger.info("Create verifier from existing repo...")
+ """Create new verifier"""
+ LOGGER.info("Create verifier from existing repo...")
cmd = ("rally verify delete-verifier --id '{0}' --force").format(
CONST.__getattribute__('tempest_verifier_name'))
ft_utils.execute_command(cmd, error_msg=(
"Verifier %s does not exist."
% CONST.__getattribute__('tempest_verifier_name')),
- verbose=False)
+ verbose=False)
cmd = ("rally verify create-verifier --source {0} "
"--name {1} --type tempest --system-wide"
.format(CONST.__getattribute__('dir_repo_tempest'),
@@ -113,12 +118,12 @@ def get_verifier_id():
cmd = ("rally verify list-verifiers | awk '/" +
CONST.__getattribute__('tempest_verifier_name') +
"/ {print $2}'")
- p = subprocess.Popen(cmd, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- deployment_uuid = p.stdout.readline().rstrip()
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+ deployment_uuid = proc.stdout.readline().rstrip()
if deployment_uuid == "":
- logger.error("Tempest verifier not found.")
+ LOGGER.error("Tempest verifier not found.")
raise Exception('Error with command:%s' % cmd)
return deployment_uuid
@@ -130,12 +135,12 @@ def get_verifier_deployment_id():
cmd = ("rally deployment list | awk '/" +
CONST.__getattribute__('rally_deployment_name') +
"/ {print $2}'")
- p = subprocess.Popen(cmd, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- deployment_uuid = p.stdout.readline().rstrip()
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+ deployment_uuid = proc.stdout.readline().rstrip()
if deployment_uuid == "":
- logger.error("Rally deployment not found.")
+ LOGGER.error("Rally deployment not found.")
raise Exception('Error with command:%s' % cmd)
return deployment_uuid
@@ -192,13 +197,14 @@ def configure_tempest(deployment_dir, image_id=None, flavor_id=None,
def configure_tempest_defcore(deployment_dir, image_id, flavor_id,
image_id_alt, flavor_id_alt, tenant_id):
+ # pylint: disable=too-many-arguments
"""
Add/update needed parameters into tempest.conf file
"""
conf_file = configure_verifier(deployment_dir)
configure_tempest_update_params(conf_file, image_id, flavor_id)
- logger.debug("Updating selected tempest.conf parameters for defcore...")
+ LOGGER.debug("Updating selected tempest.conf parameters for defcore...")
config = ConfigParser.RawConfigParser()
config.read(conf_file)
config.set('DEFAULT', 'log_file', '{}/tempest.log'.format(deployment_dir))
@@ -227,7 +233,7 @@ def generate_test_accounts_file(tenant_id):
Add needed tenant and user params into test_accounts.yaml
"""
- logger.debug("Add needed params into test_accounts.yaml...")
+ LOGGER.debug("Add needed params into test_accounts.yaml...")
accounts_list = [
{
'tenant_name':
@@ -239,8 +245,25 @@ def generate_test_accounts_file(tenant_id):
}
]
- with open(TEST_ACCOUNTS_FILE, "w") as f:
- yaml.dump(accounts_list, f, default_flow_style=False)
+ with open(TEST_ACCOUNTS_FILE, "w") as tfile:
+ yaml.dump(accounts_list, tfile, default_flow_style=False)
+
+
+def update_tempest_conf_file(conf_file, config):
+ """Update defined paramters into tempest config file"""
+ with open(TEMPEST_CONF_YAML) as yfile:
+ conf_yaml = yaml.safe_load(yfile)
+ if conf_yaml:
+ sections = config.sections()
+ for section in conf_yaml:
+ if section not in sections:
+ config.add_section(section)
+ sub_conf = conf_yaml.get(section)
+ for key, value in sub_conf.items():
+ config.set(section, key, value)
+
+ with open(conf_file, 'wb') as config_file:
+ config.write(config_file)
def configure_tempest_update_params(tempest_conf_file, image_id=None,
@@ -248,7 +271,7 @@ def configure_tempest_update_params(tempest_conf_file, image_id=None,
"""
Add/update needed parameters into tempest.conf file
"""
- logger.debug("Updating selected tempest.conf parameters...")
+ LOGGER.debug("Updating selected tempest.conf parameters...")
config = ConfigParser.RawConfigParser()
config.read(tempest_conf_file)
config.set(
@@ -276,8 +299,9 @@ def configure_tempest_update_params(tempest_conf_file, image_id=None,
CONST.__getattribute__('OS_REGION_NAME'))
identity_api_version = os.getenv(
"OS_IDENTITY_API_VERSION", os.getenv("IDENTITY_API_VERSION"))
- if (identity_api_version == '3'):
+ if identity_api_version == '3':
auth_version = 'v3'
+ config.set('identity-feature-enabled', 'api_v2', False)
else:
auth_version = 'v2'
config.set('identity', 'auth_version', auth_version)
@@ -291,9 +315,6 @@ def configure_tempest_update_params(tempest_conf_file, image_id=None,
config.set('identity', 'v3_endpoint_type',
CONST.__getattribute__('OS_ENDPOINT_TYPE'))
- if (identity_api_version == '3'):
- config.set('identity-feature-enabled', 'api_v2', False)
-
if CONST.__getattribute__('OS_ENDPOINT_TYPE') is not None:
sections = config.sections()
services_list = ['compute',
@@ -309,21 +330,9 @@ def configure_tempest_update_params(tempest_conf_file, image_id=None,
config.set(service, 'endpoint_type',
CONST.__getattribute__('OS_ENDPOINT_TYPE'))
- logger.debug('Add/Update required params defined in tempest_conf.yaml '
+ LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
'into tempest.conf file')
- with open(TEMPEST_CONF_YAML) as f:
- conf_yaml = yaml.safe_load(f)
- if conf_yaml:
- sections = config.sections()
- for section in conf_yaml:
- if section not in sections:
- config.add_section(section)
- sub_conf = conf_yaml.get(section)
- for key, value in sub_conf.items():
- config.set(section, key, value)
-
- with open(tempest_conf_file, 'wb') as config_file:
- config.write(config_file)
+ update_tempest_conf_file(tempest_conf_file, config)
backup_tempest_config(tempest_conf_file)
@@ -334,18 +343,18 @@ def configure_verifier(deployment_dir):
"""
tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
if os.path.isfile(tempest_conf_file):
- logger.debug("Verifier is already configured.")
- logger.debug("Reconfiguring the current verifier...")
+ LOGGER.debug("Verifier is already configured.")
+ LOGGER.debug("Reconfiguring the current verifier...")
cmd = "rally verify configure-verifier --reconfigure"
else:
- logger.info("Configuring the verifier...")
+ LOGGER.info("Configuring the verifier...")
cmd = "rally verify configure-verifier"
ft_utils.execute_command(cmd)
- logger.debug("Looking for tempest.conf file...")
+ LOGGER.debug("Looking for tempest.conf file...")
if not os.path.isfile(tempest_conf_file):
- logger.error("Tempest configuration file %s NOT found."
- % tempest_conf_file)
+ LOGGER.error("Tempest configuration file %s NOT found.",
+ tempest_conf_file)
raise Exception("Tempest configuration file %s NOT found."
% tempest_conf_file)
else:
diff --git a/functest/opnfv_tests/openstack/tempest/tempest.py b/functest/opnfv_tests/openstack/tempest/tempest.py
index e75192b9..c5ad4ecb 100644
--- a/functest/opnfv_tests/openstack/tempest/tempest.py
+++ b/functest/opnfv_tests/openstack/tempest/tempest.py
@@ -8,6 +8,8 @@
# http://www.apache.org/licenses/LICENSE-2.0
#
+"""Tempest testcases implementation."""
+
from __future__ import division
import logging
@@ -37,36 +39,68 @@ from snaps.openstack.tests import openstack_tests
from snaps.openstack.utils import deploy_utils
-""" logging configuration """
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
class TempestCommon(testcase.TestCase):
+ # pylint: disable=too-many-instance-attributes
+ """TempestCommon testcases implementation class."""
def __init__(self, **kwargs):
super(TempestCommon, self).__init__(**kwargs)
self.resources = TempestResourcesManager(**kwargs)
- self.MODE = ""
- self.OPTION = []
- self.VERIFIER_ID = conf_utils.get_verifier_id()
- self.VERIFIER_REPO_DIR = conf_utils.get_verifier_repo_dir(
- self.VERIFIER_ID)
- self.DEPLOYMENT_ID = conf_utils.get_verifier_deployment_id()
- self.DEPLOYMENT_DIR = conf_utils.get_verifier_deployment_dir(
- self.VERIFIER_ID, self.DEPLOYMENT_ID)
- self.VERIFICATION_ID = None
+ self.mode = ""
+ self.option = []
+ self.verifier_id = conf_utils.get_verifier_id()
+ self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
+ self.verifier_id)
+ self.deployment_id = conf_utils.get_verifier_deployment_id()
+ self.deployment_dir = conf_utils.get_verifier_deployment_dir(
+ self.verifier_id, self.deployment_id)
+ self.verification_id = None
@staticmethod
def read_file(filename):
+ """Read file and return content as a stripped list."""
with open(filename) as src:
return [line.strip() for line in src.readlines()]
+ @staticmethod
+ def get_verifier_result(verif_id):
+ """Retrieve verification results."""
+ result = {
+ 'num_tests': 0,
+ 'num_success': 0,
+ 'num_failures': 0,
+ 'num_skipped': 0
+ }
+ cmd = ["rally", "verify", "show", "--uuid", verif_id]
+ LOGGER.info("Showing result for a verification: '%s'.", cmd)
+ proc = subprocess.Popen(cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+ for line in proc.stdout:
+ new_line = line.replace(' ', '').split('|')
+ if 'Tests' in new_line:
+ break
+ LOGGER.info(line)
+ if 'Testscount' in new_line:
+ result['num_tests'] = int(new_line[2])
+ elif 'Success' in new_line:
+ result['num_success'] = int(new_line[2])
+ elif 'Skipped' in new_line:
+ result['num_skipped'] = int(new_line[2])
+ elif 'Failures' in new_line:
+ result['num_failures'] = int(new_line[2])
+ return result
+
def generate_test_list(self, verifier_repo_dir):
- logger.debug("Generating test case list...")
- if self.MODE == 'defcore':
+ """Generate test list based on the test mode."""
+ LOGGER.debug("Generating test case list...")
+ if self.mode == 'defcore':
shutil.copyfile(
conf_utils.TEMPEST_DEFCORE, conf_utils.TEMPEST_RAW_LIST)
- elif self.MODE == 'custom':
+ elif self.mode == 'custom':
if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
shutil.copyfile(
conf_utils.TEMPEST_CUSTOM, conf_utils.TEMPEST_RAW_LIST)
@@ -74,12 +108,12 @@ class TempestCommon(testcase.TestCase):
raise Exception("Tempest test list file %s NOT found."
% conf_utils.TEMPEST_CUSTOM)
else:
- if self.MODE == 'smoke':
+ if self.mode == 'smoke':
testr_mode = "smoke"
- elif self.MODE == 'full':
+ elif self.mode == 'full':
testr_mode = ""
else:
- testr_mode = 'tempest.api.' + self.MODE
+ testr_mode = 'tempest.api.' + self.mode
cmd = ("cd {0};"
"testr list-tests {1} > {2};"
"cd -;".format(verifier_repo_dir,
@@ -88,14 +122,15 @@ class TempestCommon(testcase.TestCase):
ft_utils.execute_command(cmd)
def apply_tempest_blacklist(self):
- logger.debug("Applying tempest blacklist...")
+ """Exclude blacklisted test cases."""
+ LOGGER.debug("Applying tempest blacklist...")
cases_file = self.read_file(conf_utils.TEMPEST_RAW_LIST)
result_file = open(conf_utils.TEMPEST_LIST, 'w')
black_tests = []
try:
installer_type = CONST.__getattribute__('INSTALLER_TYPE')
deploy_scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
- if (bool(installer_type) * bool(deploy_scenario)):
+ if bool(installer_type) * bool(deploy_scenario):
# if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
# file
black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
@@ -110,9 +145,9 @@ class TempestCommon(testcase.TestCase):
for test in tests:
black_tests.append(test)
break
- except Exception:
+ except Exception: # pylint: disable=broad-except
black_tests = []
- logger.debug("Tempest blacklist file does not exist.")
+ LOGGER.debug("Tempest blacklist file does not exist.")
for cases_line in cases_file:
for black_tests_line in black_tests:
@@ -123,10 +158,11 @@ class TempestCommon(testcase.TestCase):
result_file.close()
def run_verifier_tests(self):
+ """Execute tempest test cases."""
cmd = ["rally", "verify", "start", "--load-list",
conf_utils.TEMPEST_LIST]
- cmd.extend(self.OPTION)
- logger.info("Starting Tempest test suite: '%s'." % cmd)
+ cmd.extend(self.option)
+ LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
header = ("Tempest environment:\n"
" SUT: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
@@ -144,63 +180,45 @@ class TempestCommon(testcase.TestCase):
"environment.log"), 'w+')
f_env.write(header)
- p = subprocess.Popen(
+ proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=f_stderr,
bufsize=1)
- with p.stdout:
- for line in iter(p.stdout.readline, b''):
- if re.search("\} tempest\.", line):
- logger.info(line.replace('\n', ''))
+ with proc.stdout:
+ for line in iter(proc.stdout.readline, b''):
+ if re.search(r"\} tempest\.", line):
+ LOGGER.info(line.replace('\n', ''))
elif re.search('Starting verification', line):
- logger.info(line.replace('\n', ''))
+ LOGGER.info(line.replace('\n', ''))
first_pos = line.index("UUID=") + len("UUID=")
last_pos = line.index(") for deployment")
- self.VERIFICATION_ID = line[first_pos:last_pos]
- logger.debug('Verification UUID: %s', self.VERIFICATION_ID)
+ self.verification_id = line[first_pos:last_pos]
+ LOGGER.debug('Verification UUID: %s', self.verification_id)
f_stdout.write(line)
- p.wait()
+ proc.wait()
f_stdout.close()
f_stderr.close()
f_env.close()
def parse_verifier_result(self):
- if self.VERIFICATION_ID is None:
+ """Parse and save test results."""
+ if self.verification_id is None:
raise Exception('Verification UUID not found')
- cmd = ["rally", "verify", "show", "--uuid", self.VERIFICATION_ID]
- logger.info("Showing result for a verification: '%s'." % cmd)
- p = subprocess.Popen(cmd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- for line in p.stdout:
- new_line = line.replace(' ', '').split('|')
- if 'Tests' in new_line:
- break
-
- logger.info(line)
- if 'Testscount' in new_line:
- num_tests = new_line[2]
- elif 'Success' in new_line:
- num_success = new_line[2]
- elif 'Skipped' in new_line:
- num_skipped = new_line[2]
- elif 'Failures' in new_line:
- num_failures = new_line[2]
-
+ stat = self.get_verifier_result(self.verification_id)
try:
- num_executed = int(num_tests) - int(num_skipped)
+ num_executed = stat['num_tests'] - stat['num_skipped']
try:
- self.result = 100 * int(num_success) / int(num_executed)
+ self.result = 100 * stat['num_success'] / num_executed
except ZeroDivisionError:
self.result = 0
- if int(num_tests) > 0:
- logger.info("All tests have been skipped")
+ if stat['num_tests'] > 0:
+ LOGGER.info("All tests have been skipped")
else:
- logger.error("No test has been executed")
+ LOGGER.error("No test has been executed")
return
with open(os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
@@ -208,25 +226,25 @@ class TempestCommon(testcase.TestCase):
output = logfile.read()
success_testcases = []
- for match in re.findall('.*\{0\} (.*?)[. ]*success ', output):
+ for match in re.findall(r'.*\{0\} (.*?)[. ]*success ', output):
success_testcases.append(match)
failed_testcases = []
- for match in re.findall('.*\{0\} (.*?)[. ]*fail ', output):
+ for match in re.findall(r'.*\{0\} (.*?)[. ]*fail ', output):
failed_testcases.append(match)
skipped_testcases = []
- for match in re.findall('.*\{0\} (.*?)[. ]*skip:', output):
+ for match in re.findall(r'.*\{0\} (.*?)[. ]*skip:', output):
skipped_testcases.append(match)
- self.details = {"tests": int(num_tests),
- "failures": int(num_failures),
+ self.details = {"tests": stat['num_tests'],
+ "failures": stat['num_failures'],
"success": success_testcases,
- "errors": failed_testcases,
- "skipped": skipped_testcases}
- except Exception:
+ "skipped": skipped_testcases,
+ "errors": failed_testcases}
+ except Exception: # pylint: disable=broad-except
self.result = 0
- logger.info("Tempest %s success_rate is %s%%"
- % (self.case_name, self.result))
+ LOGGER.info("Tempest %s success_rate is %s%%",
+ self.case_name, self.result)
def run(self):
@@ -238,17 +256,17 @@ class TempestCommon(testcase.TestCase):
compute_cnt = snaps_utils.get_active_compute_cnt(
self.resources.os_creds)
conf_utils.configure_tempest(
- self.DEPLOYMENT_DIR,
+ self.deployment_dir,
image_id=resources.get("image_id"),
flavor_id=resources.get("flavor_id"),
compute_cnt=compute_cnt)
- self.generate_test_list(self.VERIFIER_REPO_DIR)
+ self.generate_test_list(self.verifier_repo_dir)
self.apply_tempest_blacklist()
self.run_verifier_tests()
self.parse_verifier_result()
res = testcase.TestCase.EX_OK
- except Exception as e:
- logger.error('Error with run: %s' % e)
+ except Exception as err: # pylint: disable=broad-except
+ LOGGER.error('Error with run: %s', err)
res = testcase.TestCase.EX_RUN_ERROR
finally:
self.resources.cleanup()
@@ -258,55 +276,55 @@ class TempestCommon(testcase.TestCase):
class TempestSmokeSerial(TempestCommon):
-
+ """Tempest smoke serial testcase implementation."""
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest_smoke_serial'
TempestCommon.__init__(self, **kwargs)
- self.MODE = "smoke"
- self.OPTION = ["--concurrency", "1"]
+ self.mode = "smoke"
+ self.option = ["--concurrency", "1"]
class TempestSmokeParallel(TempestCommon):
-
+ """Tempest smoke parallel testcase implementation."""
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest_smoke_parallel'
TempestCommon.__init__(self, **kwargs)
- self.MODE = "smoke"
+ self.mode = "smoke"
class TempestFullParallel(TempestCommon):
-
+ """Tempest full parallel testcase implementation."""
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest_full_parallel'
TempestCommon.__init__(self, **kwargs)
- self.MODE = "full"
+ self.mode = "full"
class TempestCustom(TempestCommon):
-
+ """Tempest custom testcase implementation."""
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest_custom'
TempestCommon.__init__(self, **kwargs)
- self.MODE = "custom"
- self.OPTION = ["--concurrency", "1"]
+ self.mode = "custom"
+ self.option = ["--concurrency", "1"]
class TempestDefcore(TempestCommon):
-
+ """Tempest Defcore testcase implementation."""
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest_defcore'
TempestCommon.__init__(self, **kwargs)
- self.MODE = "defcore"
- self.OPTION = ["--concurrency", "1"]
+ self.mode = "defcore"
+ self.option = ["--concurrency", "1"]
class TempestResourcesManager(object):
-
+ """Tempest resource manager."""
def __init__(self, **kwargs):
self.os_creds = kwargs.get('os_creds') or snaps_utils.get_credentials()
self.guid = '-' + str(uuid.uuid4())
@@ -423,34 +441,34 @@ class TempestResourcesManager(object):
project_name = None
if create_project:
- logger.debug("Creating project and user for Tempest suite")
+ LOGGER.debug("Creating project and user for Tempest suite")
project_name = CONST.__getattribute__(
'tempest_identity_tenant_name') + self.guid
result['project_id'] = self._create_project()
result['user_id'] = self._create_user()
result['tenant_id'] = result['project_id'] # for compatibility
- logger.debug("Creating private network for Tempest suite")
+ LOGGER.debug("Creating private network for Tempest suite")
self._create_network(project_name)
- logger.debug("Creating image for Tempest suite")
+ LOGGER.debug("Creating image for Tempest suite")
image_name = CONST.__getattribute__('openstack_image_name') + self.guid
result['image_id'] = self._create_image(image_name)
if use_custom_images:
- logger.debug("Creating 2nd image for Tempest suite")
+ LOGGER.debug("Creating 2nd image for Tempest suite")
image_name = CONST.__getattribute__(
'openstack_image_name_alt') + self.guid
result['image_id_alt'] = self._create_image(image_name)
if (CONST.__getattribute__('tempest_use_custom_flavors') == 'True' or
use_custom_flavors):
- logger.info("Creating flavor for Tempest suite")
+ LOGGER.info("Creating flavor for Tempest suite")
name = CONST.__getattribute__('openstack_flavor_name') + self.guid
result['flavor_id'] = self._create_flavor(name)
if use_custom_flavors:
- logger.info("Creating 2nd flavor for Tempest suite")
+ LOGGER.info("Creating 2nd flavor for Tempest suite")
scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
if 'ovs' in scenario or 'fdio' in scenario:
CONST.__setattr__('openstack_flavor_ram', 1024)
@@ -467,5 +485,5 @@ class TempestResourcesManager(object):
for creator in reversed(self.creators):
try:
creator.clean()
- except Exception as e:
- logger.error('Unexpected error cleaning - %s', e)
+ except Exception as err: # pylint: disable=broad-except
+ LOGGER.error('Unexpected error cleaning - %s', err)
diff --git a/functest/tests/unit/openstack/tempest/test_conf_utils.py b/functest/tests/unit/openstack/tempest/test_conf_utils.py
index 1c168032..c31ea0ab 100644
--- a/functest/tests/unit/openstack/tempest/test_conf_utils.py
+++ b/functest/tests/unit/openstack/tempest/test_conf_utils.py
@@ -5,7 +5,7 @@
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
-# pylint: disable=missing-docstring
+# pylint: disable=invalid-name,missing-docstring
import logging
import unittest
@@ -18,7 +18,7 @@ from snaps.openstack.os_credentials import OSCreds
class OSTempestConfUtilsTesting(unittest.TestCase):
-
+ # pylint: disable=too-many-public-methods
def setUp(self):
self.os_creds = OSCreds(
username='user', password='pass',
@@ -33,6 +33,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
@mock.patch('snaps.openstack.utils.deploy_utils.create_image',
return_value=mock.Mock())
def test_create_tempest_resources_missing_network_dic(self, *mock_args):
+ # pylint: disable=unused-argument
tempest_resources = tempest.TempestResourcesManager(
os_creds=self.os_creds)
with self.assertRaises(Exception) as context:
@@ -49,6 +50,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
@mock.patch('snaps.openstack.utils.deploy_utils.create_image',
return_value=None)
def test_create_tempest_resources_missing_image(self, *mock_args):
+ # pylint: disable=unused-argument
tempest_resources = tempest.TempestResourcesManager(
os_creds=self.os_creds)
@@ -68,6 +70,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
@mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
return_value=None)
def test_create_tempest_resources_missing_flavor(self, *mock_args):
+ # pylint: disable=unused-argument
tempest_resources = tempest.TempestResourcesManager(
os_creds=self.os_creds)
@@ -83,11 +86,12 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
msg = 'Failed to create flavor'
self.assertTrue(msg in context.exception, msg=str(context.exception))
+ @staticmethod
@mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
- '.logger.info')
+ '.LOGGER.info')
@mock.patch('functest.utils.functest_utils.execute_command_raise')
@mock.patch('functest.utils.functest_utils.execute_command')
- def test_create_rally_deployment(self, mock_exec, mock_exec_raise,
+ def test_create_rally_deployment(mock_exec, mock_exec_raise,
mock_logger_info):
conf_utils.create_rally_deployment()
@@ -109,7 +113,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
mock_exec_raise.assert_any_call(cmd, error_msg=error_msg)
@mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
- '.logger.debug')
+ '.LOGGER.debug')
def test_create_verifier(self, mock_logger_debug):
mock_popen = mock.Mock()
attrs = {'poll.return_value': None,
@@ -129,6 +133,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
'create_rally_deployment', return_value=mock.Mock())
def test_get_verifier_id_missing_verifier(self, mock_rally, mock_tempest):
+ # pylint: disable=unused-argument
CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
with mock.patch('functest.opnfv_tests.openstack.tempest.'
'conf_utils.subprocess.Popen') as mock_popen, \
@@ -144,6 +149,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
'create_rally_deployment', return_value=mock.Mock())
def test_get_verifier_id_default(self, mock_rally, mock_tempest):
+ # pylint: disable=unused-argument
CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
with mock.patch('functest.opnfv_tests.openstack.tempest.'
'conf_utils.subprocess.Popen') as mock_popen:
@@ -164,7 +170,7 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
attrs = {'stdout.readline.return_value': ''}
mock_stdout.configure_mock(**attrs)
mock_popen.return_value = mock_stdout
- conf_utils.get_verifier_deployment_id(),
+ conf_utils.get_verifier_deployment_id()
def test_get_verifier_deployment_id_default(self):
CONST.__setattr__('tempest_verifier_name', 'test_deploy_name')
@@ -292,27 +298,24 @@ class OSTempestConfUtilsTesting(unittest.TestCase):
self.assertTrue(mwrite.called)
def test_configure_tempest_update_params_missing_image_id(self):
- self._test_missing_param(('compute', 'image_ref',
- 'test_image_id'), 'test_image_id',
- None)
+ self._test_missing_param(('compute', 'image_ref', 'test_image_id'),
+ 'test_image_id', None)
def test_configure_tempest_update_params_missing_image_id_alt(self):
- conf_utils.IMAGE_ID_ALT = 'test_image_id_alt'
- self._test_missing_param(('compute', 'image_ref_alt',
- 'test_image_id_alt'), None, None)
+ conf_utils.IMAGE_ID_ALT = 'test_image_id_alt'
+ self._test_missing_param(('compute', 'image_ref_alt',
+ 'test_image_id_alt'), None, None)
def test_configure_tempest_update_params_missing_flavor_id(self):
- CONST.__setattr__('tempest_use_custom_flavors', 'True')
- self._test_missing_param(('compute', 'flavor_ref',
- 'test_flavor_id'), None,
- 'test_flavor_id')
+ CONST.__setattr__('tempest_use_custom_flavors', 'True')
+ self._test_missing_param(('compute', 'flavor_ref', 'test_flavor_id'),
+ None, 'test_flavor_id')
def test_configure_tempest_update_params_missing_flavor_id_alt(self):
- CONST.__setattr__('tempest_use_custom_flavors', 'True')
- conf_utils.FLAVOR_ID_ALT = 'test_flavor_id_alt'
- self._test_missing_param(('compute', 'flavor_ref_alt',
- 'test_flavor_id_alt'), None,
- None)
+ CONST.__setattr__('tempest_use_custom_flavors', 'True')
+ conf_utils.FLAVOR_ID_ALT = 'test_flavor_id_alt'
+ self._test_missing_param(('compute', 'flavor_ref_alt',
+ 'test_flavor_id_alt'), None, None)
def test_configure_verifier_missing_temp_conf_file(self):
with mock.patch('functest.opnfv_tests.openstack.tempest.'
diff --git a/functest/tests/unit/openstack/tempest/test_tempest.py b/functest/tests/unit/openstack/tempest/test_tempest.py
index 37b61f3b..26f2e8ad 100644
--- a/functest/tests/unit/openstack/tempest/test_tempest.py
+++ b/functest/tests/unit/openstack/tempest/test_tempest.py
@@ -5,7 +5,7 @@
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
-# pylint: disable=missing-docstring
+# pylint: disable=invalid-name,missing-docstring
import logging
import unittest
@@ -49,20 +49,22 @@ class OSTempestTesting(unittest.TestCase):
self.tempestcustom = tempest.TempestCustom()
self.tempestdefcore = tempest.TempestDefcore()
- @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.debug')
+ @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug')
def test_generate_test_list_defcore_mode(self, mock_logger_debug):
- self.tempestcommon.MODE = 'defcore'
+ # pylint: disable=unused-argument
+ self.tempestcommon.mode = 'defcore'
with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
- 'shutil.copyfile') as m:
+ 'shutil.copyfile') as mock_copyfile:
self.tempestcommon.generate_test_list('test_verifier_repo_dir')
- self.assertTrue(m.called)
+ self.assertTrue(mock_copyfile.called)
- @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.error')
- @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.debug')
+ @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.error')
+ @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug')
def test_generate_test_list_custom_mode_missing_file(self,
mock_logger_debug,
mock_logger_error):
- self.tempestcommon.MODE = 'custom'
+ # pylint: disable=unused-argument
+ self.tempestcommon.mode = 'custom'
with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'os.path.isfile', return_value=False), \
self.assertRaises(Exception) as context:
@@ -71,33 +73,32 @@ class OSTempestTesting(unittest.TestCase):
self.assertTrue((msg % conf_utils.TEMPEST_CUSTOM) in context)
def test_generate_test_list_custom_mode_default(self):
- self.tempestcommon.MODE = 'custom'
+ self.tempestcommon.mode = 'custom'
with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
- 'shutil.copyfile') as m, \
+ 'shutil.copyfile') as mock_copyfile, \
mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'os.path.isfile', return_value=True):
self.tempestcommon.generate_test_list('test_verifier_repo_dir')
- self.assertTrue(m.called)
+ self.assertTrue(mock_copyfile.called)
def _test_generate_test_list_mode_default(self, mode):
- self.tempestcommon.MODE = mode
- if self.tempestcommon.MODE == 'smoke':
+ self.tempestcommon.mode = mode
+ if self.tempestcommon.mode == 'smoke':
testr_mode = "smoke"
- elif self.tempestcommon.MODE == 'full':
+ elif self.tempestcommon.mode == 'full':
testr_mode = ""
else:
- testr_mode = 'tempest.api.' + self.tempestcommon.MODE
+ testr_mode = 'tempest.api.' + self.tempestcommon.mode
conf_utils.TEMPEST_RAW_LIST = 'raw_list'
verifier_repo_dir = 'test_verifier_repo_dir'
with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
- 'ft_utils.execute_command') as m:
+ 'ft_utils.execute_command') as mock_exec:
cmd = ("cd {0};"
"testr list-tests {1} > {2};"
- "cd -;".format(verifier_repo_dir,
- testr_mode,
+ "cd -;".format(verifier_repo_dir, testr_mode,
conf_utils.TEMPEST_RAW_LIST))
self.tempestcommon.generate_test_list('test_verifier_repo_dir')
- m.assert_any_call(cmd)
+ mock_exec.assert_any_call(cmd)
def test_generate_test_list_smoke_mode(self):
self._test_generate_test_list_mode_default('smoke')
@@ -106,7 +107,7 @@ class OSTempestTesting(unittest.TestCase):
self._test_generate_test_list_mode_default('full')
def test_parse_verifier_result_missing_verification_uuid(self):
- self.tempestcommon.VERIFICATION_ID = None
+ self.tempestcommon.verification_id = None
with self.assertRaises(Exception):
self.tempestcommon.parse_verifier_result()
@@ -138,10 +139,10 @@ class OSTempestTesting(unittest.TestCase):
obj.write.assert_any_call('test1\n')
self.assertFalse(obj.write.assert_any_call('test2\n'))
- @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.info')
+ @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.info')
def test_run_verifier_tests_default(self, mock_logger_info):
with mock.patch('__builtin__.open', mock.mock_open()), \
- mock.patch('__builtin__.iter', return_value=['\} tempest\.']), \
+ mock.patch('__builtin__.iter', return_value=[r'\} tempest\.']), \
mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'subprocess.Popen'):
conf_utils.TEMPEST_LIST = 'test_tempest_list'
@@ -149,13 +150,14 @@ class OSTempestTesting(unittest.TestCase):
conf_utils.TEMPEST_LIST]
self.tempestcommon.run_verifier_tests()
mock_logger_info. \
- assert_any_call("Starting Tempest test suite: '%s'." % cmd)
+ assert_any_call("Starting Tempest test suite: '%s'.", cmd)
@mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'os.path.exists', return_value=False)
@mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs',
side_effect=Exception)
def test_run_makedirs_ko(self, *args):
+ # pylint: disable=unused-argument
self.assertEqual(self.tempestcommon.run(),
testcase.TestCase.EX_RUN_ERROR)
@@ -165,6 +167,7 @@ class OSTempestTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'TempestResourcesManager.create', side_effect=Exception)
def test_run_tempest_create_resources_ko(self, *args):
+ # pylint: disable=unused-argument
self.assertEqual(self.tempestcommon.run(),
testcase.TestCase.EX_RUN_ERROR)
@@ -176,6 +179,7 @@ class OSTempestTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
'get_active_compute_cnt', side_effect=Exception)
def test_run_get_active_compute_cnt_ko(self, *args):
+ # pylint: disable=unused-argument
self.assertEqual(self.tempestcommon.run(),
testcase.TestCase.EX_RUN_ERROR)
@@ -189,6 +193,7 @@ class OSTempestTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'conf_utils.configure_tempest', side_effect=Exception)
def test_run_configure_tempest_ko(self, *args):
+ # pylint: disable=unused-argument
self.assertEqual(self.tempestcommon.run(),
testcase.TestCase.EX_RUN_ERROR)
@@ -202,6 +207,7 @@ class OSTempestTesting(unittest.TestCase):
@mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
'conf_utils.configure_tempest')
def _test_run(self, status, *args):
+ # pylint: disable=unused-argument
self.assertEqual(self.tempestcommon.run(), status)
def test_run_missing_generate_test_list(self):
@@ -216,7 +222,7 @@ class OSTempestTesting(unittest.TestCase):
side_effect=Exception()):
self._test_run(testcase.TestCase.EX_RUN_ERROR)
- def test_run_verifier_tests_ko(self, *args):
+ def test_run_verifier_tests_ko(self):
with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
mock.patch.object(self.tempestcommon,
'apply_tempest_blacklist'), \
@@ -226,7 +232,7 @@ class OSTempestTesting(unittest.TestCase):
side_effect=Exception):
self._test_run(testcase.TestCase.EX_RUN_ERROR)
- def test_run_parse_verifier_result_ko(self, *args):
+ def test_run_parse_verifier_result_ko(self):
with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
mock.patch.object(self.tempestcommon,
'apply_tempest_blacklist'), \
@@ -235,7 +241,7 @@ class OSTempestTesting(unittest.TestCase):
side_effect=Exception):
self._test_run(testcase.TestCase.EX_RUN_ERROR)
- def test_run(self, *args):
+ def test_run(self):
with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
mock.patch.object(self.tempestcommon,
'apply_tempest_blacklist'), \
diff --git a/tox.ini b/tox.ini
index 01de45c8..d2c94342 100644
--- a/tox.ini
+++ b/tox.ini
@@ -37,6 +37,7 @@ modules =
functest.opnfv_tests.openstack.rally
functest.opnfv_tests.openstack.refstack_client
functest.opnfv_tests.openstack.snaps
+ functest.opnfv_tests.openstack.tempest
functest.opnfv_tests.openstack.vping
functest.opnfv_tests.sdn.odl
functest.opnfv_tests.vnf.router
@@ -48,6 +49,7 @@ modules =
functest.tests.unit.openstack.rally
functest.tests.unit.openstack.refstack_client
functest.tests.unit.openstack.snaps
+ functest.tests.unit.openstack.tempest
functest.tests.unit.openstack.vping
functest.tests.unit.vnf.router
functest.tests.unit.utils.test_decorators