aboutsummaryrefslogtreecommitdiffstats
path: root/xtesting/core
diff options
context:
space:
mode:
authorCédric Ollivier <cedric.ollivier@orange.com>2021-11-09 11:22:02 +0100
committerCédric Ollivier <cedric.ollivier@orange.com>2021-11-09 13:21:47 +0100
commit17739d718901a10f7ec0aaf9a6d53141294a347d (patch)
treea98e6d09a42016ceec90713adac681918a4a9c62 /xtesting/core
parent92681911699428a87ea56c0263832b96a93da3da (diff)
Leverage latest pylint features
It adds encoding in all open call and leverage f-strings. Change-Id: I70ccd2bfcadae44929d5874f98fa3bf4ff644488 Signed-off-by: Cédric Ollivier <cedric.ollivier@orange.com>
Diffstat (limited to 'xtesting/core')
-rw-r--r--xtesting/core/behaveframework.py8
-rw-r--r--xtesting/core/campaign.py27
-rw-r--r--xtesting/core/feature.py6
-rw-r--r--xtesting/core/mts.py19
-rw-r--r--xtesting/core/robotframework.py6
-rw-r--r--xtesting/core/testcase.py11
-rw-r--r--xtesting/core/unit.py8
-rw-r--r--xtesting/core/vnf.py8
8 files changed, 45 insertions, 48 deletions
diff --git a/xtesting/core/behaveframework.py b/xtesting/core/behaveframework.py
index 3dc60384..6003c4ab 100644
--- a/xtesting/core/behaveframework.py
+++ b/xtesting/core/behaveframework.py
@@ -41,7 +41,7 @@ class BehaveFramework(testcase.TestCase):
def parse_results(self):
"""Parse output.json and get the details in it."""
- with open(self.json_file) as stream_:
+ with open(self.json_file, encoding='utf-8') as stream_:
self.response = json.load(stream_)
if self.response:
self.total_tests = len(self.response)
@@ -87,11 +87,11 @@ class BehaveFramework(testcase.TestCase):
except Exception: # pylint: disable=broad-except
self.__logger.exception("Cannot create %s", self.res_dir)
return self.EX_RUN_ERROR
- config = ['--junit', '--junit-directory={}'.format(self.res_dir),
- '--format=json', '--outfile={}'.format(self.json_file)]
+ config = ['--junit', f'--junit-directory={self.res_dir}',
+ '--format=json', f'--outfile={self.json_file}']
html_file = os.path.join(self.res_dir, 'output.html')
config += ['--format=behave_html_formatter:HTMLFormatter',
- '--outfile={}'.format(html_file)]
+ f'--outfile={html_file}']
if kwargs.get("tags", False):
config += ['--tags='+','.join(kwargs.get("tags", []))]
if kwargs.get("console", False):
diff --git a/xtesting/core/campaign.py b/xtesting/core/campaign.py
index 58747681..5c5744ef 100644
--- a/xtesting/core/campaign.py
+++ b/xtesting/core/campaign.py
@@ -69,7 +69,7 @@ class Campaign():
try:
url = env.get('TEST_DB_URL')
req = requests.get(
- "{}?build_tag={}".format(url, env.get('BUILD_TAG')),
+ f"{url}?build_tag={env.get('BUILD_TAG')}",
headers=testcase.TestCase.headers)
req.raise_for_status()
output = req.json()
@@ -78,10 +78,11 @@ class Campaign():
for j, _ in enumerate(
output["results"][i]["details"]["links"]):
output["results"][i]["details"]["links"][j] = re.sub(
- "^{}/*".format(os.environ["HTTP_DST_URL"]), '',
+ "^{os.environ['HTTP_DST_URL']}/*", '',
output["results"][i]["details"]["links"][j])
Campaign.__logger.debug("data to archive: \n%s", output)
- with open("{}.json".format(env.get('BUILD_TAG')), "w") as dfile:
+ with open("{env.get('BUILD_TAG')}.json", "w",
+ encoding='utf-8') as dfile:
json.dump(output, dfile)
except Exception: # pylint: disable=broad-except
Campaign.__logger.exception(
@@ -126,19 +127,19 @@ class Campaign():
prefix = os.path.join(s3path, build_tag)
# pylint: disable=no-member
for s3_object in b3resource.Bucket(bucket_name).objects.filter(
- Prefix="{}/".format(prefix)):
+ Prefix=f"{prefix}/"):
path, _ = os.path.split(s3_object.key)
- lpath = re.sub('^{}/*'.format(s3path), '', path)
+ lpath = re.sub(f'^{s3path}/*', '', path)
if lpath and not os.path.exists(lpath):
os.makedirs(lpath)
# pylint: disable=no-member
b3resource.Bucket(bucket_name).download_file(
s3_object.key,
- re.sub('^{}/*'.format(s3path), '', s3_object.key),
+ re.sub(f'^{s3path}/*', '', s3_object.key),
Config=config)
Campaign.__logger.info(
"Downloading %s",
- re.sub('^{}/*'.format(s3path), '', s3_object.key))
+ re.sub(f'^{s3path}/*', '', s3_object.key))
return Campaign.EX_OK
except Exception: # pylint: disable=broad-except
Campaign.__logger.exception("Cannot publish the artifacts")
@@ -171,9 +172,9 @@ class Campaign():
build_tag = env.get('BUILD_TAG')
assert Campaign.dump_db() == Campaign.EX_OK
assert Campaign.dump_artifacts() == Campaign.EX_OK
- with zipfile.ZipFile('{}.zip'.format(build_tag),
+ with zipfile.ZipFile(f'{build_tag}.zip',
'w', zipfile.ZIP_DEFLATED) as zfile:
- zfile.write("{}.json".format(build_tag))
+ zfile.write(f"{build_tag}.json")
for root, _, files in os.walk(build_tag):
for filename in files:
zfile.write(os.path.join(root, filename))
@@ -184,17 +185,17 @@ class Campaign():
"S3_ENDPOINT_URL"] else 8 * 1024 * 1024
config = TransferConfig(multipart_threshold=multipart_threshold)
bucket_name = urlparse(dst_s3_url).netloc
- mime_type = mimetypes.guess_type('{}.zip'.format(build_tag))
+ mime_type = mimetypes.guess_type(f'{build_tag}.zip')
path = urlparse(dst_s3_url).path.strip("/")
# pylint: disable=no-member
b3resource.Bucket(bucket_name).upload_file(
- '{}.zip'.format(build_tag),
- os.path.join(path, '{}.zip'.format(build_tag)),
+ f'{build_tag}.zip',
+ os.path.join(path, f'{build_tag}.zip'),
Config=config,
ExtraArgs={'ContentType': mime_type[
0] or 'application/octet-stream'})
dst_http_url = os.environ["HTTP_DST_URL"]
- link = os.path.join(dst_http_url, '{}.zip'.format(build_tag))
+ link = os.path.join(dst_http_url, f'{build_tag}.zip')
Campaign.__logger.info(
"All data were successfully published:\n\n%s", link)
return Campaign.EX_OK
diff --git a/xtesting/core/feature.py b/xtesting/core/feature.py
index 5a02bb6a..8cc9a210 100644
--- a/xtesting/core/feature.py
+++ b/xtesting/core/feature.py
@@ -86,7 +86,7 @@ class BashFeature(Feature):
def __init__(self, **kwargs):
super().__init__(**kwargs)
- self.result_file = "{}/{}.log".format(self.res_dir, self.case_name)
+ self.result_file = f"{self.res_dir}/{self.case_name}.log"
def execute(self, **kwargs):
"""Execute the cmd passed as arg
@@ -105,7 +105,7 @@ class BashFeature(Feature):
max_duration = kwargs.get("max_duration")
if not os.path.isdir(self.res_dir):
os.makedirs(self.res_dir)
- with open(self.result_file, 'w') as f_stdout:
+ with open(self.result_file, 'w', encoding='utf-8') as f_stdout:
self.__logger.info("Calling %s", cmd)
with subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE,
@@ -122,7 +122,7 @@ class BashFeature(Feature):
"Killing process after %d second(s).",
max_duration)
return -2
- with open(self.result_file, 'r') as f_stdin:
+ with open(self.result_file, 'r', encoding='utf-8') as f_stdin:
self.__logger.debug("$ %s\n%s", cmd, f_stdin.read().rstrip())
return process.returncode
except KeyError:
diff --git a/xtesting/core/mts.py b/xtesting/core/mts.py
index 3bc7bde9..0f15733c 100644
--- a/xtesting/core/mts.py
+++ b/xtesting/core/mts.py
@@ -65,7 +65,7 @@ class MTSLauncher(feature.BashFeature):
"""Parse testPlan.csv containing the status of each testcase of the test file.
See sample file in `xtesting/samples/mts/output/testPlan.csv`
"""
- with open(self.mts_result_csv_file) as stream_:
+ with open(self.mts_result_csv_file, encoding='utf-8') as stream_:
self.__logger.info("Parsing file : %s", self.mts_result_csv_file)
reader = csv.reader(stream_, delimiter=';')
rownum = 0
@@ -183,18 +183,13 @@ class MTSLauncher(feature.BashFeature):
return -3
# Build command line to launch for MTS
- cmd = ("cd {} && ./startCmd.sh {} {} -sequential -levelLog:{}"
- " -storageLog:{}"
- " -config:stats.REPORT_DIRECTORY+{}"
- " -config:logs.STORAGE_DIRECTORY+{}"
+ cmd = (f"cd {cwd} && ./startCmd.sh {test_file} "
+ f"{enabled_testcases_str} -sequential -levelLog:{log_level}"
+ f" -storageLog:{store_method}"
+ f" -config:stats.REPORT_DIRECTORY+{self.mts_stats_dir}"
+ f" -config:logs.STORAGE_DIRECTORY+{self.mts_logs_dir}"
" -genReport:true"
- " -showRep:false").format(cwd,
- test_file,
- enabled_testcases_str,
- log_level,
- store_method,
- self.mts_stats_dir,
- self.mts_logs_dir)
+ " -showRep:false")
# Make sure to create the necessary output sub-folders for MTS
# and cleanup output files from previous run.
diff --git a/xtesting/core/robotframework.py b/xtesting/core/robotframework.py
index 3a439eca..775ed1ce 100644
--- a/xtesting/core/robotframework.py
+++ b/xtesting/core/robotframework.py
@@ -79,9 +79,9 @@ class RobotFramework(testcase.TestCase):
result = robot.api.ExecutionResult(self.xml_file)
writer = resultwriter.ResultWriter(result)
return writer.write_results(
- report='{}/report.html'.format(self.res_dir),
- log='{}/log.html'.format(self.res_dir),
- xunit='{}/xunit.xml'.format(self.res_dir))
+ report=f'{self.res_dir}/report.html',
+ log=f'{self.res_dir}/log.html',
+ xunit=f'{self.res_dir}/xunit.xml')
def run(self, **kwargs):
"""Run the RobotFramework suites
diff --git a/xtesting/core/testcase.py b/xtesting/core/testcase.py
index 672ba3f7..f7814f72 100644
--- a/xtesting/core/testcase.py
+++ b/xtesting/core/testcase.py
@@ -105,9 +105,10 @@ class TestCase(metaclass=abc.ABCMeta):
assert self.stop_time
if self.stop_time < self.start_time:
return "XX:XX"
- return "{}:{}".format(
- str(int(self.stop_time - self.start_time) // 60).zfill(2),
- str(int(self.stop_time - self.start_time) % 60).zfill(2))
+ return(
+ f"{str(int(self.stop_time - self.start_time) // 60).zfill(2)}:"
+ f"{str(int(self.stop_time - self.start_time) % 60).zfill(2)}")
+
except Exception: # pylint: disable=broad-except
self.__logger.error("Please run test before getting the duration")
return "XX:XX"
@@ -314,7 +315,7 @@ class TestCase(metaclass=abc.ABCMeta):
ExtraArgs={'ContentType': mime_type[
0] or 'application/octet-stream'})
link = os.path.join(dst_http_url, log_file)
- output_str += "\n{}".format(link)
+ output_str += f"\n{link}"
self.details["links"].append(link)
for root, _, files in os.walk(self.res_dir):
for pub_file in files:
@@ -334,7 +335,7 @@ class TestCase(metaclass=abc.ABCMeta):
link = os.path.join(dst_http_url, os.path.relpath(
os.path.join(root, pub_file),
start=self.dir_results))
- output_str += "\n{}".format(link)
+ output_str += f"\n{link}"
self.details["links"].append(link)
self.__logger.info(
"All artifacts were successfully published: %s\n", output_str)
diff --git a/xtesting/core/unit.py b/xtesting/core/unit.py
index e6c3cd87..10feb886 100644
--- a/xtesting/core/unit.py
+++ b/xtesting/core/unit.py
@@ -56,7 +56,7 @@ class Suite(testcase.TestCase):
Exception
"""
stream.seek(0)
- with open("{}/results.xml".format(self.res_dir), "w") as xml:
+ with open(f"{self.res_dir}/results.xml", "w", encoding='utf-8') as xml:
with subprocess.Popen(
['subunit2junitxml'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE) as stats:
@@ -69,7 +69,7 @@ class Suite(testcase.TestCase):
Raises:
CalledProcessError
"""
- cmd = ['subunit2html', stream, '{}/results.html'.format(self.res_dir)]
+ cmd = ['subunit2html', stream, f'{self.res_dir}/results.html']
output = subprocess.check_output(cmd)
self.__logger.debug("\n%s\n\n%s", ' '.join(cmd), output)
@@ -117,10 +117,10 @@ class Suite(testcase.TestCase):
stream=stream, verbosity=2).run(self.suite).decorated
self.generate_stats(stream)
self.generate_xunit(stream)
- with open('{}/subunit_stream'.format(self.res_dir), 'wb') as subfd:
+ with open(f'{self.res_dir}/subunit_stream', 'wb') as subfd:
stream.seek(0)
shutil.copyfileobj(stream, subfd)
- self.generate_html('{}/subunit_stream'.format(self.res_dir))
+ self.generate_html(f'{self.res_dir}/subunit_stream')
self.stop_time = time.time()
self.details = {
"testsRun": result.testsRun,
diff --git a/xtesting/core/vnf.py b/xtesting/core/vnf.py
index 72d54b51..c3bc4322 100644
--- a/xtesting/core/vnf.py
+++ b/xtesting/core/vnf.py
@@ -44,13 +44,13 @@ class VnfOnBoarding(testcase.TestCase):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.uuid = uuid.uuid4()
- self.user_name = "{}-{}".format(self.case_name, self.uuid)
- self.tenant_name = "{}-{}".format(self.case_name, self.uuid)
+ self.user_name = f"{self.case_name}-{self.uuid}"
+ self.tenant_name = f"{self.case_name}-{self.uuid}"
self.snaps_creds = {}
self.created_object = []
self.os_project = None
- self.tenant_description = "Created by OPNFV Functest: {}".format(
- self.case_name)
+ self.tenant_description = (
+ f"Created by OPNFV Functest: {self.case_name}")
def run(self, **kwargs):
"""