diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index c692ebe0b9..666a705465 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -15,6 +15,18 @@ repos:
args: [--safe, --line-length, '100']
language_version: python3.7
<<: *exclude
+- repo: https://github.com/asottile/pyupgrade
+ rev: v1.23.0
+ hooks:
+ - id: pyupgrade
+ language_version: python3.7
+ args: [--py36-plus]
+- repo: https://gitlab.com/pycqa/flake8
+ rev: 3.7.9
+ hooks:
+ - id: flake8
+ language_version: python3.7
+ additional_dependencies: [polarion-docstrings, bugzilla-docstrings]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
@@ -23,12 +35,3 @@ repos:
- id: check-yaml
- id: debug-statements
exclude: ^(sprout|scripts|cfme/fixtures/rdb.py)
- - id: flake8
- language_version: python3.7
- additional_dependencies: [polarion-docstrings, bugzilla-docstrings]
-- repo: https://github.com/asottile/pyupgrade
- rev: v1.23.0
- hooks:
- - id: pyupgrade
- language_version: python3.7
- <<: *exclude
diff --git a/artifactor/plugins/filedump.py b/artifactor/plugins/filedump.py
index f52f945e86..896f54c363 100644
--- a/artifactor/plugins/filedump.py
+++ b/artifactor/plugins/filedump.py
@@ -110,7 +110,7 @@ def filedump(
@ArtifactorBasePlugin.check_configured
def sanitize(self, test_location, test_name, artifacts, words):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
filename = None
try:
for f in artifacts[test_ident]["files"]:
diff --git a/artifactor/plugins/logger.py b/artifactor/plugins/logger.py
index 2f1f8a9a2f..b9f6254864 100644
--- a/artifactor/plugins/logger.py
+++ b/artifactor/plugins/logger.py
@@ -19,7 +19,7 @@
class Logger(ArtifactorBasePlugin):
- class Test(object):
+ class Test:
def __init__(self, ident):
self.ident = ident
self.in_progress = False
@@ -43,7 +43,7 @@ def configure(self):
def start_test(self, artifact_path, test_name, test_location, slaveid):
if not slaveid:
slaveid = "Master"
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
if slaveid in self.store:
if self.store[slaveid].in_progress:
print("Test already running, can't start another, logger")
@@ -51,7 +51,7 @@ def start_test(self, artifact_path, test_name, test_location, slaveid):
self.store[slaveid].close()
self.store[slaveid] = self.Test(test_ident)
self.store[slaveid].in_progress = True
- filename = "{ident}-cfme.log".format(ident=self.ident)
+ filename = f"{self.ident}-cfme.log"
self.store[slaveid].handler = make_file_handler(
filename,
root=artifact_path,
diff --git a/artifactor/plugins/ostriz.py b/artifactor/plugins/ostriz.py
index 5358561715..450d86c234 100644
--- a/artifactor/plugins/ostriz.py
+++ b/artifactor/plugins/ostriz.py
@@ -45,7 +45,7 @@ def ostriz_send(
env_params=None,
):
env_params = env_params or {}
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
json_data = artifacts[test_ident]
json_data["name"] = test_ident
json_data["run"] = run_id
diff --git a/artifactor/plugins/reporter.py b/artifactor/plugins/reporter.py
index 2dc74db504..2940c37c14 100644
--- a/artifactor/plugins/reporter.py
+++ b/artifactor/plugins/reporter.py
@@ -56,7 +56,7 @@ def overall_test_status(statuses):
return "passed"
-class ReporterBase(object):
+class ReporterBase:
def _run_report(self, old_artifacts, artifact_dir, version=None, fw_version=None):
template_data = self.process_data(old_artifacts, artifact_dir, version, fw_version)
@@ -71,7 +71,7 @@ def render_report(self, report, filename, log_dir, template):
template_env = Environment(loader=FileSystemLoader(template_path.strpath))
data = template_env.get_template(template).render(**report)
- with open(os.path.join(log_dir, "{}.html".format(filename)), "w") as f:
+ with open(os.path.join(log_dir, f"{filename}.html"), "w") as f:
f.write(data)
try:
shutil.copytree(template_path.join("dist").strpath, os.path.join(log_dir, "dist"))
@@ -201,9 +201,7 @@ def process_data(self, artifacts, log_dir, version, fw_version, name_filter=None
if name_filter:
template_data["tests"] = [
- x
- for x in template_data["tests"]
- if re.findall(r"{}[-\]]+".format(name_filter), x["name"])
+ x for x in template_data["tests"] if re.findall(fr"{name_filter}[-\]]+", x["name"])
]
# Create the tree dict that is used for js tree
@@ -295,7 +293,7 @@ def build_li(self, lev):
).format(v["name"], proc_name, teststring, label, pretty_time)
# Do we really need the os.path.split (now process_pytest_path) here?
# For me it seems the name is always the leaf
- list_string += "
{}\n".format(link)
+ list_string += f"{link}\n"
# If there is a '_sub' attribute then we know we have other modules to go.
elif "_sub" in v:
@@ -351,7 +349,7 @@ def composite_pump(self, old_artifacts):
@ArtifactorBasePlugin.check_configured
def skip_test(self, test_location, test_name, skip_data):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
return None, {"artifacts": {test_ident: {"skipped": skip_data}}}
@ArtifactorBasePlugin.check_configured
@@ -367,7 +365,7 @@ def start_test(
):
if not param_dict:
param_dict = {}
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
return (
None,
{
@@ -388,7 +386,7 @@ def start_test(
@ArtifactorBasePlugin.check_configured
def finish_test(self, artifacts, test_location, test_name, slaveid):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
overall_status = overall_test_status(artifacts[test_ident]["statuses"])
return (
None,
@@ -414,7 +412,7 @@ def report_test(
test_outcome,
test_phase_duration,
):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
ret_dict = {
"artifacts": {
test_ident: {
@@ -434,7 +432,7 @@ def session_info(self, version=None, build=None, stream=None, fw_version=None):
@ArtifactorBasePlugin.check_configured
def tb_info(self, test_location, test_name, exception, file_line, short_tb):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
return (
None,
{
diff --git a/artifactor/plugins/video.py b/artifactor/plugins/video.py
index 937701ba63..aa197bbca0 100644
--- a/artifactor/plugins/video.py
+++ b/artifactor/plugins/video.py
@@ -19,7 +19,7 @@
class Video(ArtifactorBasePlugin):
- class Test(object):
+ class Test:
def __init__(self, ident):
self.ident = ident
self.in_progress = False
@@ -38,7 +38,7 @@ def configure(self):
@ArtifactorBasePlugin.check_configured
def start_test(self, artifact_path, test_name, test_location, slaveid):
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
if test_ident in self.tests:
if self.tests[test_ident].in_progress:
print("Test already running, can't start another")
@@ -78,7 +78,7 @@ def start_test(self, artifact_path, test_name, test_location, slaveid):
@ArtifactorBasePlugin.check_configured
def finish_test(self, artifact_path, test_name, test_location):
"""Finish test"""
- test_ident = "{}/{}".format(test_location, test_name)
+ test_ident = f"{test_location}/{test_name}"
try:
self.tests[test_ident].recorder.stop()
except Exception as e:
diff --git a/cfme/ansible/credentials.py b/cfme/ansible/credentials.py
index 7abf37c46f..4f44c3d919 100644
--- a/cfme/ansible/credentials.py
+++ b/cfme/ansible/credentials.py
@@ -393,7 +393,7 @@ class Credential(BaseEntity, Taggable):
# is also problematic for attrs
def __init__(self, collection, name, credential_type, **credentials):
- super(Credential, self).__init__(collection)
+ super().__init__(collection)
self.name = name
self.credential_type = credential_type
for key, value in credentials.items():
@@ -431,7 +431,7 @@ def update(self, updates):
updates.get("name", self.name)))
else:
view.flash.assert_message(
- 'Edit of Credential "{}" was canceled by the user.'.format(self.name))
+ f'Edit of Credential "{self.name}" was canceled by the user.')
def delete(self):
view = navigate_to(self, "Details")
@@ -441,7 +441,7 @@ def delete(self):
wait_for(lambda: False, silent_failure=True, timeout=5)
assert credentials_list_page.is_displayed
credentials_list_page.flash.assert_success_message(
- 'Deletion of Credential "{}" was successfully initiated.'.format(self.name))
+ f'Deletion of Credential "{self.name}" was successfully initiated.')
wait_for(
lambda: not self.exists,
delay=10,
@@ -479,7 +479,7 @@ def create(self, name, credential_type, **credentials):
wait_for(lambda: False, silent_failure=True, timeout=5)
assert credentials_list_page.is_displayed
credentials_list_page.flash.assert_success_message(
- 'Add of Credential "{}" has been successfully queued.'.format(name))
+ f'Add of Credential "{name}" has been successfully queued.')
credential = self.instantiate(name, credential_type, **credentials)
diff --git a/cfme/ansible/repositories.py b/cfme/ansible/repositories.py
index e5306c00b9..24bf8ba793 100644
--- a/cfme/ansible/repositories.py
+++ b/cfme/ansible/repositories.py
@@ -216,7 +216,7 @@ def _wait_until_changes_applied():
wait_for(_wait_until_changes_applied, delay=10, timeout="5m")
else:
view.flash.assert_message(
- 'Edit of Repository "{}" cancelled by the user.'.format(self.name))
+ f'Edit of Repository "{self.name}" cancelled by the user.')
def delete(self):
"""Delete the repository in the UI."""
@@ -227,7 +227,7 @@ def delete(self):
assert repo_list_page.is_displayed
repo_list_page.flash.assert_no_error()
repo_list_page.flash.assert_message(
- 'Delete of Repository "{}" was successfully initiated.'.format(self.name))
+ f'Delete of Repository "{self.name}" was successfully initiated.')
wait_for(
lambda: not self.exists,
delay=10,
@@ -353,7 +353,7 @@ def delete(self, *repositories):
view.flash.assert_no_error()
for repository in checked_repositories:
view.flash.assert_message(
- 'Delete of Repository "{}" was successfully initiated.'.format(repository.name))
+ f'Delete of Repository "{repository.name}" was successfully initiated.')
@navigator.register(RepositoryCollection, 'All')
diff --git a/cfme/ansible_tower/explorer.py b/cfme/ansible_tower/explorer.py
index 554ff737c5..ba1028bf3f 100644
--- a/cfme/ansible_tower/explorer.py
+++ b/cfme/ansible_tower/explorer.py
@@ -218,7 +218,7 @@ def step(self, *args, **kwargs):
try:
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Could not locate template "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Could not locate template "{self.obj.name}"')
row.click()
diff --git a/cfme/automate/__init__.py b/cfme/automate/__init__.py
index c7c2dbe918..b9cf6b498e 100644
--- a/cfme/automate/__init__.py
+++ b/cfme/automate/__init__.py
@@ -97,7 +97,7 @@ class EditDialogView(DialogForm):
def is_displayed(self):
return (
self.in_customization and self.service_dialogs.is_opened and
- self.title.text == "Editing Dialog {}".format(self.label)
+ self.title.text == f"Editing Dialog {self.label}"
)
diff --git a/cfme/automate/buttons.py b/cfme/automate/buttons.py
index 1b4d296b29..60d6d2db9c 100644
--- a/cfme/automate/buttons.py
+++ b/cfme/automate/buttons.py
@@ -253,7 +253,7 @@ def simulate(
# Group and User are EVM type objects. workaround for <5.11
target_type = (
- "EVM {}".format(self.group.type)
+ f"EVM {self.group.type}"
if self.group.type in ["Group", "User"] and self.appliance.version < "5.11"
else self.group.type
)
@@ -644,9 +644,9 @@ def is_displayed(self):
expected_title = '{} Button Group "{}"'.format(obj.type, "Unassigned Buttons")
else:
expected_title = (
- 'Button Group "{}"'.format(obj.text)
+ f'Button Group "{obj.text}"'
if self.browser.product_version < "5.11"
- else '{} Button Group "{}"'.format(obj.type, obj.text)
+ else f'{obj.type} Button Group "{obj.text}"'
)
return (
diff --git a/cfme/automate/dialogs/__init__.py b/cfme/automate/dialogs/__init__.py
index 737f4f0754..9637a0e535 100644
--- a/cfme/automate/dialogs/__init__.py
+++ b/cfme/automate/dialogs/__init__.py
@@ -72,7 +72,7 @@ def is_displayed(self):
expected_title = (
"Automate Customization"
if self.browser.product_version < "5.11"
- else 'Editing {} Service Dialog'.format(obj.label)
+ else f'Editing {obj.label} Service Dialog'
)
return (
self.in_customization
@@ -89,12 +89,12 @@ class CopyDialogView(DialogForm):
@property
def is_displayed(self):
obj = self.context["object"]
- expected_label = 'Copy of {}'.format(obj.label)
+ expected_label = f'Copy of {obj.label}'
expected_title = (
"Automate Customization"
if self.browser.product_version < "5.11"
- else 'Editing {} Service Dialog'.format(obj.label)
+ else f'Editing {obj.label} Service Dialog'
)
return (
self.in_customization
diff --git a/cfme/automate/dialogs/dialog_box.py b/cfme/automate/dialogs/dialog_box.py
index f37c93b1b0..d3435f2b4b 100644
--- a/cfme/automate/dialogs/dialog_box.py
+++ b/cfme/automate/dialogs/dialog_box.py
@@ -18,7 +18,7 @@ class EditBoxView(BoxForm):
def is_displayed(self):
return (
self.in_customization and
- self.title.text == "Editing Dialog {} [Box Information]".format(self.box_label)
+ self.title.text == f"Editing Dialog {self.box_label} [Box Information]"
)
diff --git a/cfme/automate/dialogs/dialog_tab.py b/cfme/automate/dialogs/dialog_tab.py
index 2459c9bd0d..60283d8c95 100644
--- a/cfme/automate/dialogs/dialog_tab.py
+++ b/cfme/automate/dialogs/dialog_tab.py
@@ -18,7 +18,7 @@ class EditTabView(TabForm):
def is_displayed(self):
return (
self.in_customization and
- self.title.text == "Editing Dialog {} [Tab Information]".format(self.tab_label)
+ self.title.text == f"Editing Dialog {self.tab_label} [Tab Information]"
)
diff --git a/cfme/automate/dialogs/service_dialogs.py b/cfme/automate/dialogs/service_dialogs.py
index 12d8e23a8f..38aa416f5d 100644
--- a/cfme/automate/dialogs/service_dialogs.py
+++ b/cfme/automate/dialogs/service_dialogs.py
@@ -89,7 +89,7 @@ def delete(self):
assert view.is_displayed
view.flash.assert_no_error()
view.flash.assert_success_message(
- 'Dialog "{}": Delete successful'.format(self.label))
+ f'Dialog "{self.label}": Delete successful')
def copy(self):
view = navigate_to(self, "Copy")
diff --git a/cfme/automate/explorer/common.py b/cfme/automate/explorer/common.py
index 2703dbb456..06de1c79fd 100644
--- a/cfme/automate/explorer/common.py
+++ b/cfme/automate/explorer/common.py
@@ -23,7 +23,7 @@ class CopyViewBase(View):
cancel_button = Button('Cancel')
-class Copiable(object):
+class Copiable:
# TODO: Namespace!
def copy_to(self, domain, new_name=None, replace=None, cancel=False):
copy_page = navigate_to(self, 'Copy')
diff --git a/cfme/automate/explorer/domain.py b/cfme/automate/explorer/domain.py
index acdae7a3bb..8ee8604645 100644
--- a/cfme/automate/explorer/domain.py
+++ b/cfme/automate/explorer/domain.py
@@ -116,7 +116,7 @@ def __init__(
git_repository=None, git_checkout_type=None, git_checkout_value=None, db_id=None):
from cfme.automate.explorer.namespace import NamespaceCollection
self._collections = {'namespaces': NamespaceCollection}
- super(Domain, self).__init__(collection)
+ super().__init__(collection)
self.name = name
self.description = description
if db_id is not None:
@@ -149,7 +149,7 @@ def db_id(self):
table.name == self.name,
table.parent_id == None)[0] # noqa
except IndexError:
- raise ItemNotFound('Domain named {} not found in the database'.format(self.name))
+ raise ItemNotFound(f'Domain named {self.name} not found in the database')
@cached_property
def git_repository(self):
@@ -200,27 +200,27 @@ def tree_display_name(self):
name = self.name
if self.locked and not self.enabled:
- return '{} (Locked & Disabled)'.format(name)
+ return f'{name} (Locked & Disabled)'
elif self.locked and self.enabled:
- return '{} (Locked)'.format(name)
+ return f'{name} (Locked)'
elif not self.locked and not self.enabled:
- return '{} (Disabled)'.format(name)
+ return f'{name} (Disabled)'
else:
return name
@property
def table_display_name(self):
if self.git_repository:
- name = '{name} ({ref})'.format(name=self.name, ref=self.git_checkout_value)
+ name = f'{self.name} ({self.git_checkout_value})'
else:
name = self.name
if self.locked and not self.enabled:
- return '{} (Locked & Disabled)'.format(name)
+ return f'{name} (Locked & Disabled)'
elif self.locked and self.enabled:
- return '{} (Locked)'.format(name)
+ return f'{name} (Locked)'
elif not self.locked and not self.enabled:
- return '{} (Disabled)'.format(name)
+ return f'{name} (Disabled)'
else:
return name
diff --git a/cfme/automate/explorer/instance.py b/cfme/automate/explorer/instance.py
index fc4b31e59f..582ffefe84 100644
--- a/cfme/automate/explorer/instance.py
+++ b/cfme/automate/explorer/instance.py
@@ -153,7 +153,7 @@ class Instance(BaseEntity, Copiable):
ICON_NAME = 'fa-file-text-o'
def __init__(self, collection, name, display_name=None, description=None, fields=None):
- super(Instance, self).__init__(collection)
+ super().__init__(collection)
self.name = name
if display_name is not None:
@@ -180,7 +180,7 @@ def db_id(self):
table.name == self.name,
table.class_id == self.klass.db_id)[0] # noqa
except IndexError:
- raise ItemNotFound('Instance named {} not found in the database'.format(self.name))
+ raise ItemNotFound(f'Instance named {self.name} not found in the database')
@property
def db_object(self):
@@ -207,7 +207,7 @@ def domain(self):
def tree_path(self):
if self.display_name:
return self.parent_obj.tree_path + [
- (self.ICON_NAME, '{} ({})'.format(self.display_name, self.name))]
+ (self.ICON_NAME, f'{self.display_name} ({self.name})')]
else:
return self.parent_obj.tree_path + [(self.ICON_NAME, self.name)]
@@ -235,7 +235,7 @@ def update(self, updates):
'Automate Instance "{}" was saved'.format(updates.get('name', self.name)))
else:
view.flash.assert_message(
- 'Edit of Automate Instance "{}" was cancelled by the user'.format(self.name))
+ f'Edit of Automate Instance "{self.name}" was cancelled by the user')
def delete(self, cancel=False):
# Ensure this has correct data
@@ -288,7 +288,7 @@ def create(self, name=None, display_name=None, description=None, fields=None, ca
else:
add_page.add_button.click()
add_page.flash.assert_no_error()
- add_page.flash.assert_message('Automate Instance "{}" was added'.format(name))
+ add_page.flash.assert_message(f'Automate Instance "{name}" was added')
# TODO(BZ-1704439): Remove the work-around once this BZ got fixed
if BZ(1704439).blocks:
@@ -334,7 +334,7 @@ def delete(self, *instances):
all_page.flash.assert_no_error()
for instance in checked_instances:
all_page.flash.assert_message(
- 'Automate Instance "{}": Delete successful'.format(instance.name))
+ f'Automate Instance "{instance.name}": Delete successful')
# TODO(BZ-1704439): Remove the work-around once this BZ got fixed
if BZ(1704439).blocks:
diff --git a/cfme/automate/explorer/klass.py b/cfme/automate/explorer/klass.py
index a219febbc8..f106cc410d 100644
--- a/cfme/automate/explorer/klass.py
+++ b/cfme/automate/explorer/klass.py
@@ -119,7 +119,7 @@ def __init__(self, collection, name, display_name=None, description=None):
'instances': InstanceCollection,
'methods': MethodCollection
}
- super(Class, self).__init__(collection)
+ super().__init__(collection)
self.name = name
if display_name is not None:
@@ -145,7 +145,7 @@ def db_id(self):
table.name == self.name,
table.namespace_id == self.namespace.db_id)[0] # noqa
except IndexError:
- raise ItemNotFound('Class named {} not found in the database'.format(self.name))
+ raise ItemNotFound(f'Class named {self.name} not found in the database')
@property
def db_object(self):
@@ -175,7 +175,7 @@ def domain(self):
@property
def tree_path(self):
if self.display_name:
- return self.parent_obj.tree_path + ['{} ({})'.format(self.display_name, self.name)]
+ return self.parent_obj.tree_path + [f'{self.display_name} ({self.name})']
else:
return self.parent_obj.tree_path + [self.name]
@@ -235,10 +235,10 @@ def update(self, updates):
fqdn = self.fqdn.rsplit('/', 1)[0] + '/{}'.format(updates['name'])
else:
fqdn = self.fqdn
- view.flash.assert_message('Automate Class "{}" was saved'.format(fqdn))
+ view.flash.assert_message(f'Automate Class "{fqdn}" was saved')
else:
view.flash.assert_message(
- 'Edit of Automate Class "{}" was cancelled by the user'.format(self.name))
+ f'Edit of Automate Class "{self.name}" was cancelled by the user')
@attr.s
@@ -491,7 +491,7 @@ def add_field(self, **kwargs):
page.schema.save_button.click()
page.flash.assert_no_error()
page.flash.assert_message(
- 'Schema for Automate Class "{}" was saved'.format(self.klass.name))
+ f'Schema for Automate Class "{self.klass.name}" was saved')
else:
page.schema.cancel_button.click()
page.flash.assert_no_error()
@@ -509,7 +509,7 @@ def add_fields(self, *fields):
page.schema.save_button.click()
page.flash.assert_no_error()
page.flash.assert_message(
- 'Schema for Automate Class "{}" was saved'.format(self.klass.name))
+ f'Schema for Automate Class "{self.klass.name}" was saved')
else:
page.schema.cancel_button.click()
page.flash.assert_no_error()
@@ -530,7 +530,7 @@ def delete_field(self, field):
page.schema.save_button.click()
page.flash.assert_no_error()
page.flash.assert_message(
- 'Schema for Automate Class "{}" was saved'.format(self.klass.name))
+ f'Schema for Automate Class "{self.klass.name}" was saved')
else:
page.schema.cancel_button.click()
page.flash.assert_no_error()
@@ -548,7 +548,7 @@ def delete_fields(self, *fields):
page.schema.save_button.click()
page.flash.assert_no_error()
page.flash.assert_message(
- 'Schema for Automate Class "{}" was saved'.format(self.klass.name))
+ f'Schema for Automate Class "{self.klass.name}" was saved')
else:
page.schema.cancel_button.click()
page.flash.assert_no_error()
diff --git a/cfme/automate/explorer/method.py b/cfme/automate/explorer/method.py
index fb3f7cbf78..623ff3ae61 100644
--- a/cfme/automate/explorer/method.py
+++ b/cfme/automate/explorer/method.py
@@ -108,7 +108,7 @@ def fill(self, value):
new_value['name'] = key
self.add_field.wait_displayed()
self.add_field.click()
- super(Inputs, self).fill(new_value)
+ super().fill(new_value)
self.finish_add_field.click()
changed = True
@@ -313,10 +313,10 @@ class MethodEditView(AutomateExplorerView):
def before_fill(self, values):
location = self.context['object'].location.lower()
if 'display_name' in values and location in ['inline', 'playbook']:
- values['{}_display_name'.format(location)] = values['display_name']
+ values[f'{location}_display_name'] = values['display_name']
del values['display_name']
elif 'name' in values and location in ['inline', 'playbook']:
- values['{}_name'.format(location)] = values['name']
+ values[f'{location}_name'] = values['name']
del values['name']
@property
@@ -340,7 +340,7 @@ def __init__(self, collection, name=None, display_name=None, location='inline',
max_ttl=None, logging_output=None, escalate_privilege=None, verbosity=None,
playbook_input_parameters=None, cancel=False, validate=True, inputs=None,
embedded_method=None):
- super(Method, self).__init__(collection)
+ super().__init__(collection)
self.name = name
if display_name is not None:
@@ -374,7 +374,7 @@ def db_id(self):
table.name == self.name,
table.class_id == self.klass.db_id)[0] # noqa
except IndexError:
- raise ItemNotFound('Method named {} not found in the database'.format(self.name))
+ raise ItemNotFound(f'Method named {self.name} not found in the database')
@property
def db_object(self):
@@ -433,7 +433,7 @@ def delete(self, cancel=False):
result_view = self.create_view(ClassDetailsView, self.parent_obj, wait='10s')
result_view.flash.assert_no_error()
result_view.flash.assert_message(
- 'Automate Method "{}": Delete successful'.format(self.name))
+ f'Automate Method "{self.name}": Delete successful')
@attr.s
@@ -502,7 +502,7 @@ def create(
# TODO(BZ-1704439): Remove the work-around once this BZ got fixed
if BZ(1704439).blocks:
view = self.create_view(ClassDetailsView)
- view.flash.assert_message('Automate Method "{}" was added'.format(name))
+ view.flash.assert_message(f'Automate Method "{name}" was added')
self.browser.refresh()
return self.instantiate(
@@ -556,7 +556,7 @@ def delete(self, *methods):
all_page.flash.assert_no_error()
for method in checked_methods:
all_page.flash.assert_message(
- 'Automate Method "{}": Delete successful'.format(method.name))
+ f'Automate Method "{method.name}": Delete successful')
# TODO(BZ-1704439): Remove the work-around once this BZ got fixed
if BZ(1704439).blocks:
diff --git a/cfme/automate/explorer/namespace.py b/cfme/automate/explorer/namespace.py
index 7382207ebb..a5a05a6774 100644
--- a/cfme/automate/explorer/namespace.py
+++ b/cfme/automate/explorer/namespace.py
@@ -85,7 +85,7 @@ def __init__(self, collection, name, description=None):
'namespaces': NamespaceCollection,
'classes': ClassCollection
}
- super(Namespace, self).__init__(collection)
+ super().__init__(collection)
self.name = name
if description is not None:
self.description = description
@@ -107,7 +107,7 @@ def db_id(self):
table.name == self.name,
table.parent_id == self.parent_obj.db_id)[0] # noqa
except IndexError:
- raise ItemNotFound('Namespace named {} not found in the database'.format(self.name))
+ raise ItemNotFound(f'Namespace named {self.name} not found in the database')
@property
def db_object(self):
@@ -175,10 +175,10 @@ def update(self, updates):
view.flash.assert_no_error()
if changed:
text = (updates.get('description', self.description) or updates.get('name', self.name))
- view.flash.assert_message('Automate Namespace "{}" was saved'.format(text))
+ view.flash.assert_message(f'Automate Namespace "{text}" was saved')
else:
view.flash.assert_message(
- 'Edit of Automate Namespace "{}" was cancelled by the user'.format(self.name))
+ f'Edit of Automate Namespace "{self.name}" was cancelled by the user')
@attr.s
diff --git a/cfme/automate/provisioning_dialogs.py b/cfme/automate/provisioning_dialogs.py
index bca3e95961..40c35f5a49 100644
--- a/cfme/automate/provisioning_dialogs.py
+++ b/cfme/automate/provisioning_dialogs.py
@@ -152,7 +152,7 @@ def update(self, updates, cancel=False, reset=False):
btn = view.form.reset
view = self.create_view(ProvDiagDetailsView)
if cancel:
- flash_msg = 'Edit of Dialog "{}" was cancelled by the user'.format(self.description)
+ flash_msg = f'Edit of Dialog "{self.description}" was cancelled by the user'
btn = view.form.cancel
view = self.create_view(ProvDiagDetailsView)
else:
@@ -199,7 +199,7 @@ def create(self, diag_type=None, name=None, description=None, content=None, canc
flash_msg = 'Add of new Dialog was cancelled by the user'
btn = view.form.cancel
else:
- flash_msg = 'Dialog "{}" was added'.format(dialog.description)
+ flash_msg = f'Dialog "{dialog.description}" was added'
btn = view.form.add
btn.click()
view = dialog.create_view(ProvDiagAllView if cancel else ProvDiagDetailsView, wait='10s')
diff --git a/cfme/base/__init__.py b/cfme/base/__init__.py
index 8f0a4d8b13..ad3707b93e 100644
--- a/cfme/base/__init__.py
+++ b/cfme/base/__init__.py
@@ -422,9 +422,9 @@ def _api_settings_url(self):
KeyError if the region resource isn't found by the filter
AssertionError if more than one region matches the filter
"""
- filter_query = '?expand=resources&filter[]=region={}'.format(self.number)
+ filter_query = f'?expand=resources&filter[]=region={self.number}'
region_filter = self.appliance.rest_api.get(
- '{}{}'.format(self.appliance.rest_api.collections.regions._href, filter_query)
+ f'{self.appliance.rest_api.collections.regions._href}{filter_query}'
)
region, = region_filter['resources']
return '/'.join([self.appliance.rest_api.collections.regions._href,
diff --git a/cfme/base/credential.py b/cfme/base/credential.py
index 3946c41ede..f2c6441449 100644
--- a/cfme/base/credential.py
+++ b/cfme/base/credential.py
@@ -5,7 +5,7 @@
from cfme.utils.update import Updateable
-class FromConfigMixin(object):
+class FromConfigMixin:
@staticmethod
def rename_properties(creds):
"""
@@ -81,9 +81,9 @@ def __getattribute__(self, attr):
elif attr == 'principal':
domain = object.__getattribute__(self, 'domain')
principal = object.__getattribute__(self, 'principal')
- return r'{}\{}'.format(domain, principal) if domain else principal
+ return fr'{domain}\{principal}' if domain else principal
else:
- return super(Credential, self).__getattribute__(attr)
+ return super().__getattribute__(attr)
@property
def view_value_mapping(self):
@@ -155,7 +155,7 @@ def __getattribute__(self, attr):
else:
return object.__getattribute__(self, 'token')
else:
- return super(TokenCredential, self).__getattribute__(attr)
+ return super().__getattribute__(attr)
def __eq__(self, other):
return self.token == other.token and self.verify_token == other.verify_token
@@ -185,7 +185,7 @@ class ServiceAccountCredential(Pretty, Updateable):
pretty_attrs = ['service_account']
def __init__(self, service_account):
- super(ServiceAccountCredential, self)
+ super()
self.service_account = service_account
@property
diff --git a/cfme/base/ssui.py b/cfme/base/ssui.py
index 8141507d66..7423531bdc 100644
--- a/cfme/base/ssui.py
+++ b/cfme/base/ssui.py
@@ -101,7 +101,7 @@ def submit_login(self, method='click_on_login'):
elif method == 'press_enter_after_password':
self.browser.send_keys(Keys.ENTER, self.password)
else:
- raise ValueError('Unknown method {}'.format(method))
+ raise ValueError(f'Unknown method {method}')
if self.flash.is_displayed:
self.flash.assert_no_error()
diff --git a/cfme/base/ui.py b/cfme/base/ui.py
index d1c1bdcb11..994f1ceba6 100644
--- a/cfme/base/ui.py
+++ b/cfme/base/ui.py
@@ -107,7 +107,7 @@ def submit_login(self, method='click_on_login'):
elif method == '_js_auth_fn':
self.browser.execute_script('miqAjaxAuth();')
else:
- raise ValueError('Unknown method {}'.format(method))
+ raise ValueError(f'Unknown method {method}')
if self.flash.is_displayed:
self.flash.assert_no_error()
@@ -1004,8 +1004,7 @@ class RegionChangeNameView(RegionView):
@property
def is_displayed(self):
- return self.region_description.is_displayed and super(RegionChangeNameView,
- self).is_displayed
+ return self.region_description.is_displayed and super().is_displayed
class HelpMenuView(RegionView):
@@ -1626,7 +1625,7 @@ def update(self, updates):
'Zone "{}" was saved'.format(updates.get('name', self.name)))
else:
view.flash.assert_message(
- 'Edit of Zone "{}" was cancelled by the user'.format(self.name))
+ f'Edit of Zone "{self.name}" was cancelled by the user')
@MiqImplementationContext.external_for(Zone.delete, ViaUI)
@@ -1639,7 +1638,7 @@ def delete(self, cancel=False):
view = navigate_to(self, 'Zone')
view.zone.configuration.item_select('Delete this Zone', handle_alert=not cancel)
if not cancel:
- view.flash.assert_message('Zone "{}": Delete successful'.format(self.name))
+ view.flash.assert_message(f'Zone "{self.name}": Delete successful')
@MiqImplementationContext.external_for(ZoneCollection.create, ViaUI)
@@ -1674,7 +1673,7 @@ def create(self, name=None, description=None, smartproxy_ip=None, ntp_servers=No
else:
add_page.add_button.click()
add_page.flash.assert_no_error()
- add_page.flash.assert_message('Zone "{}" was added'.format(name))
+ add_page.flash.assert_message(f'Zone "{name}" was added')
return self.instantiate(
name=name, description=description, smartproxy_ip=smartproxy_ip,
ntp_servers=ntp_servers, max_scans=max_scans, user=user
diff --git a/cfme/cloud/instance/__init__.py b/cfme/cloud/instance/__init__.py
index 5744ab123d..9112ad5d90 100644
--- a/cfme/cloud/instance/__init__.py
+++ b/cfme/cloud/instance/__init__.py
@@ -154,7 +154,7 @@ def is_displayed(self):
relationship_provider_name = relationships.get_text_of('Cloud Provider')
return (
self.in_cloud_instance and
- self.entities.title.text == 'Instance "{}"'.format(expected_name) and
+ self.entities.title.text == f'Instance "{expected_name}"' and
relationship_provider_name == expected_provider
)
except (NameError, NoSuchElementException):
@@ -163,7 +163,7 @@ def is_displayed(self):
# table
return (
self.in_cloud_instance and
- self.entities.title.text == 'Instance "{}"'.format(expected_name)
+ self.entities.title.text == f'Instance "{expected_name}"'
)
toolbar = View.nested(InstanceDetailsToolbar)
@@ -268,8 +268,8 @@ def wait_for_instance_state_change(self, desired_state, timeout=900):
def _looking_for_state_change():
view = navigate_to(self, 'Details')
current_state = view.entities.summary("Power Management").get_text_of("Power State")
- logger.info('Current Instance state: {}'.format(current_state))
- logger.info('Desired Instance state: {}'.format(desired_state))
+ logger.info(f'Current Instance state: {current_state}')
+ logger.info(f'Desired Instance state: {desired_state}')
if isinstance(desired_state, (list, tuple)):
return current_state in desired_state
else:
@@ -294,7 +294,7 @@ def find_quadicon(self, **kwargs):
try:
return view.entities.get_entity(name=self.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound("Instance '{}' not found in UI!".format(self.name))
+ raise ItemNotFound(f"Instance '{self.name}' not found in UI!")
def power_control_from_cfme(self, *args, **kwargs):
"""Power controls a VM from within CFME using details or collection
@@ -316,7 +316,7 @@ def power_control_from_cfme(self, *args, **kwargs):
row = view.entities.get_entity(name=self.name, surf_pages=True)
except ItemNotFound:
raise ItemNotFound(
- 'Failed to find instance in table: {}'.format(self.name)
+ f'Failed to find instance in table: {self.name}'
)
row.ensure_checked()
@@ -402,7 +402,7 @@ def vm_default_args_rest(self):
resource_group_id = None
if self.provider.one_of(AzureProvider):
resource_groups = self.appliance.rest_api.get(
- '{}?attributes=resource_groups'.format(provider_rest._href))['resource_groups']
+ f'{provider_rest._href}?attributes=resource_groups')['resource_groups']
resource_group_id = None
resource_group_name = provisioning.get('resource_group')
for res_group in resource_groups:
@@ -568,7 +568,7 @@ def step(self, *args, **kwargs):
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True,
use_search=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate instance with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate instance with name "{self.obj.name}"')
row.click()
def resetter(self, *args, **kwargs):
@@ -585,7 +585,7 @@ def step(self, *args, **kwargs):
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True,
use_search=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate instance with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate instance with name "{self.obj.name}"')
row.click()
def resetter(self, *args, **kwargs):
diff --git a/cfme/cloud/instance/azure.py b/cfme/cloud/instance/azure.py
index 60d2dc8cc2..7eb699ef7d 100644
--- a/cfme/cloud/instance/azure.py
+++ b/cfme/cloud/instance/azure.py
@@ -42,7 +42,7 @@ def ui_powerstates_unavailable(self):
@property
def vm_default_args(self):
- inst_args = super(AzureInstance, self).vm_default_args
+ inst_args = super().vm_default_args
provisioning = self.provider.data['provisioning']
vm_user = provisioning.get('customize_username')
vm_password = provisioning.get('customize_password')
@@ -64,7 +64,7 @@ def vm_default_args(self):
@property
def vm_default_args_rest(self):
- inst_args = super(AzureInstance, self).vm_default_args_rest
+ inst_args = super().vm_default_args_rest
provisioning = self.provider.data['provisioning']
vm_user = provisioning.get('customize_username')
vm_password = provisioning.get('customize_password')
diff --git a/cfme/cloud/instance/gce.py b/cfme/cloud/instance/gce.py
index aafdbf8e16..4db183b0f6 100644
--- a/cfme/cloud/instance/gce.py
+++ b/cfme/cloud/instance/gce.py
@@ -41,14 +41,14 @@ def ui_powerstates_unavailable(self):
@property
def vm_default_args(self):
"""Represents dictionary used for Vm/Instance provision with GCE mandatory default args"""
- inst_args = super(GCEInstance, self).vm_default_args
+ inst_args = super().vm_default_args
provisioning = self.provider.data['provisioning']
inst_args['properties']['boot_disk_size'] = provisioning.get('boot_disk_size', '10 GB')
return inst_args
@property
def vm_default_args_rest(self):
- inst_args = super(GCEInstance, self).vm_default_args_rest
+ inst_args = super().vm_default_args_rest
provisioning = self.provider.data['provisioning']
recursive_update(inst_args, {
'vm_fields': {
diff --git a/cfme/cloud/instance/image.py b/cfme/cloud/instance/image.py
index a63386f675..0eb8cef16b 100644
--- a/cfme/cloud/instance/image.py
+++ b/cfme/cloud/instance/image.py
@@ -83,7 +83,7 @@ def is_displayed(self):
provider = self.context['object'].provider.name
except AttributeError:
provider = self.context['object'].filters['provider'].name
- expected_title = 'Images under Provider "{}"'.format(provider)
+ expected_title = f'Images under Provider "{provider}"'
accordion = self.sidebar.images_by_provider
return (
self.in_cloud_instance and
@@ -222,7 +222,7 @@ def step(self, *args, **kwargs):
try:
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate image with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate image with name "{self.obj.name}"')
row.click()
diff --git a/cfme/cloud/instance/openstack.py b/cfme/cloud/instance/openstack.py
index 4fccd3cd10..b93d716066 100644
--- a/cfme/cloud/instance/openstack.py
+++ b/cfme/cloud/instance/openstack.py
@@ -95,7 +95,7 @@ def volume_count(self):
@property
def vm_default_args(self):
- inst_args = super(OpenStackInstance, self).vm_default_args
+ inst_args = super().vm_default_args
provisioning = self.provider.data['provisioning']
recursive_update(inst_args, {
'environment': {
diff --git a/cfme/cloud/keypairs.py b/cfme/cloud/keypairs.py
index 9d92b09483..772b72cb94 100644
--- a/cfme/cloud/keypairs.py
+++ b/cfme/cloud/keypairs.py
@@ -247,7 +247,7 @@ def create(self, name, provider, public_key=None, cancel=False):
flash_message = 'Add of new Key Pair was cancelled by the user'
else:
view.form.add.click()
- flash_message = 'Key Pair "{}" created'.format(name)
+ flash_message = f'Key Pair "{name}" created'
# add/cancel should redirect, new view
view = self.create_view(KeyPairAllView)
diff --git a/cfme/cloud/provider/__init__.py b/cfme/cloud/provider/__init__.py
index e7b79a26f4..b85c616d00 100644
--- a/cfme/cloud/provider/__init__.py
+++ b/cfme/cloud/provider/__init__.py
@@ -145,7 +145,7 @@ class CloudProvider(BaseProvider, CloudInfraProviderMixin, Pretty, PolicyProfile
zone = attr.ib(default=None)
def __attrs_post_init__(self):
- super(CloudProvider, self).__attrs_post_init__()
+ super().__attrs_post_init__()
self.parent = self.appliance.collections.cloud_providers
def as_fill_value(self):
diff --git a/cfme/cloud/provider/openstack.py b/cfme/cloud/provider/openstack.py
index ff159d7286..2328214ae9 100644
--- a/cfme/cloud/provider/openstack.py
+++ b/cfme/cloud/provider/openstack.py
@@ -47,14 +47,14 @@ def create(self, *args, **kwargs):
self.infra_provider.create(validate_credentials=True, validate_inventory=True,
check_existing=True)
kwargs['validate_credentials'] = kwargs.get('validate_credentials', True)
- return super(OpenStackProvider, self).create(*args, **kwargs)
+ return super().create(*args, **kwargs)
def create_rest(self, *args, **kwargs):
# Override the standard behaviour to actually create the underlying infra first.
if self.infra_provider:
self.infra_provider.create_rest(validate_inventory=True,
check_existing=True)
- return super(OpenStackProvider, self).create_rest(*args, **kwargs)
+ return super().create_rest(*args, **kwargs)
@property
def view_value_mapping(self):
diff --git a/cfme/cloud/provider/vcloud.py b/cfme/cloud/provider/vcloud.py
index f64fdbd0bc..8c1022257d 100644
--- a/cfme/cloud/provider/vcloud.py
+++ b/cfme/cloud/provider/vcloud.py
@@ -15,13 +15,13 @@
class VmwareCloudCredential(Credential):
def __init__(self, organization=None, **kwargs):
- super(VmwareCloudCredential, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.organization = organization
@property
def view_value_mapping(self):
- d = super(VmwareCloudCredential, self).view_value_mapping
- d['username'] = '{}@{}'.format(self.principal, self.organization)
+ d = super().view_value_mapping
+ d['username'] = f'{self.principal}@{self.organization}'
return d
diff --git a/cfme/cloud/security_groups.py b/cfme/cloud/security_groups.py
index 46c3a2bdc7..4fe0375eb9 100644
--- a/cfme/cloud/security_groups.py
+++ b/cfme/cloud/security_groups.py
@@ -179,7 +179,7 @@ def create(self, name, description, provider, cancel=False, wait=False):
"""
view = navigate_to(self, 'Add')
- changed = view.form.fill({'network_manager': "{} Network Manager".format(provider.name),
+ changed = view.form.fill({'network_manager': f"{provider.name} Network Manager",
'name': name,
'description': description,
'cloud_tenant': 'admin'})
@@ -189,7 +189,7 @@ def create(self, name, description, provider, cancel=False, wait=False):
flash_message = 'Add of new Security Group was cancelled by the user'
else:
view.form.add.click()
- flash_message = 'Security Group "{}" created'.format(name)
+ flash_message = f'Security Group "{name}" created'
# add/cancel should redirect, new view
view = self.create_view(SecurityGroupAllView)
diff --git a/cfme/cloud/tenant.py b/cfme/cloud/tenant.py
index 23dfd72797..ab7460cc5a 100644
--- a/cfme/cloud/tenant.py
+++ b/cfme/cloud/tenant.py
@@ -286,7 +286,7 @@ def delete(self, wait=True):
except NoSuchElementException as ex:
# Catch general navigation exceptions and raise
raise ItemNotFound(
- 'Exception while navigating to Tenant details: {}'.format(ex))
+ f'Exception while navigating to Tenant details: {ex}')
view.toolbar.configuration.item_select('Delete Cloud Tenant')
result = view.flash.assert_success_message(
@@ -321,7 +321,7 @@ def create(self, name, provider, wait=True):
all_view.flash.assert_success_message("Add of Cloud Tenant was cancelled by the user")
else:
all_view.flash.assert_success_message(
- 'Cloud Tenant "{}" created'.format(name))
+ f'Cloud Tenant "{name}" created')
tenant = self.instantiate(name, provider)
@@ -467,7 +467,7 @@ def step(self, *args, **kwargs):
item = 'Cloud Subnets'
if not int(self.prerequisite_view.entities.relationships.get_text_of(item)):
raise DestinationNotFound(
- 'Cloud Tenant {} has a 0 count for {} relationships'.format(self.obj, item))
+ f'Cloud Tenant {self.obj} has a 0 count for {item} relationships')
self.prerequisite_view.entities.relationships.click_at(item)
@@ -481,6 +481,6 @@ def step(self, *args, **kwargs):
item = 'Network Routers'
if not int(self.prerequisite_view.entities.relationships.get_text_of(item)):
raise DestinationNotFound(
- 'Cloud Tenant {} has a 0 count for {} relationships'.format(self.obj, item))
+ f'Cloud Tenant {self.obj} has a 0 count for {item} relationships')
self.prerequisite_view.entities.relationships.click_at(item)
diff --git a/cfme/common/__init__.py b/cfme/common/__init__.py
index 43e56d959f..7708d96bc1 100644
--- a/cfme/common/__init__.py
+++ b/cfme/common/__init__.py
@@ -176,7 +176,7 @@ class ManagePoliciesView(BaseLoggedInPage):
is_displayed = displayed_not_implemented
-class PolicyProfileAssignable(object):
+class PolicyProfileAssignable:
"""This class can be inherited by anything that provider load_details method.
It provides functionality to assign and unassign Policy Profiles
@@ -187,7 +187,7 @@ def assigned_policy_profiles(self):
try:
return self._assigned_policy_profiles
except AttributeError:
- self._assigned_policy_profiles = set([])
+ self._assigned_policy_profiles = set()
return self._assigned_policy_profiles
def assign_policy_profiles(self, *policy_profile_names):
@@ -425,7 +425,7 @@ def is_displayed(self):
)
-class TaggableCommonBase(object):
+class TaggableCommonBase:
"""Class represents common functionality for tagging via collection and entities pages"""
def _set_random_tag(self, view):
@@ -463,7 +463,7 @@ def _assign_tag_action(self, view, tag):
# Handle nested view.form and where the view contains form widgets
try:
updated = view.form.fill({
- "tag_category": '{} *'.format(category_name),
+ "tag_category": f'{category_name} *',
"tag_name": tag_name
})
except (NoSuchElementException, SelectItemNotFound):
@@ -484,7 +484,7 @@ def _unassign_tag_action(self, view, tag):
tag = tag.display_name
if self.appliance.version < '5.11':
try:
- row = view.form.tags.row(category="{} *".format(category), assigned_value=tag)
+ row = view.form.tags.row(category=f"{category} *", assigned_value=tag)
except RowNotFound:
row = view.form.tags.row(category=category, assigned_value=tag)
row[0].click()
@@ -622,9 +622,9 @@ def get_tags(self, tenant="My Company Tags"):
try:
view = navigate_to(self, 'Details', force=True)
except (NavigationDestinationNotFound, DestinationNotFound):
- raise ItemNotFound('Details page does not exist for: {}'.format(self))
+ raise ItemNotFound(f'Details page does not exist for: {self}')
except TimedOutError:
- raise ItemNotFound('Timed out navigating to details for: {}'.format(self))
+ raise ItemNotFound(f'Timed out navigating to details for: {self}')
tags_objs = []
entities = view.entities
if hasattr(entities, 'smart_management'):
@@ -632,7 +632,7 @@ def get_tags(self, tenant="My Company Tags"):
else:
tag_table = entities.summary('Smart Management')
tags_text = tag_table.get_text_of(tenant)
- if tags_text != 'No {} have been assigned'.format(tenant):
+ if tags_text != f'No {tenant} have been assigned':
# check for users/groups page in case one tag string is returned
for tag in [tags_text] if isinstance(tags_text, str) else list(tags_text):
tag_category, tag_name = tag.split(':')
@@ -786,7 +786,7 @@ def step(self, *args):
"Edit 'My Company' Tags for this {}".format(type(self.obj).__name__))
-class Validatable(object):
+class Validatable:
"""Mixin for various validations. Requires the class to be also :py:class:`Taggable`.
:var :py:attr:`property_tuples`: Tuples which first value is the provider class's attribute
@@ -833,10 +833,10 @@ def validate_tags(self, reference_tags):
if ref_tag.category.display_name == tag.category.display_name \
and ref_tag.display_name == tag.display_name:
found = True
- assert found, ("Tag '{}' not found in UI".format(ref_tag))
+ assert found, (f"Tag '{ref_tag}' not found in UI")
-class UtilizationMixin(object):
+class UtilizationMixin:
"""Use this mixin to have simple access to the Utilization information of an object.
Requires that the class(page) has ``load_details(refresh)`` method
@@ -883,7 +883,7 @@ def is_displayed(self):
)
-class CustomButtonEventsMixin(object):
+class CustomButtonEventsMixin:
def get_button_events(self):
try:
view = navigate_to(self, "ButtonEvents")
diff --git a/cfme/common/host_views.py b/cfme/common/host_views.py
index eb45b788c0..d5ab70a860 100644
--- a/cfme/common/host_views.py
+++ b/cfme/common/host_views.py
@@ -49,7 +49,7 @@ def _host_page(title):
class HostEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(HostEntity, self).data
+ data_dict = super().data
try:
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
diff --git a/cfme/common/physical_server_views.py b/cfme/common/physical_server_views.py
index cf758145aa..12dbbc659e 100644
--- a/cfme/common/physical_server_views.py
+++ b/cfme/common/physical_server_views.py
@@ -35,7 +35,7 @@ def in_compute_physical_infrastructure_servers(self):
class PhysicalServerEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(PhysicalServerEntity, self).data
+ data_dict = super().data
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
data_dict['no_host'] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text)
diff --git a/cfme/common/physical_switch_views.py b/cfme/common/physical_switch_views.py
index 51f77a59f6..1e32a26247 100644
--- a/cfme/common/physical_switch_views.py
+++ b/cfme/common/physical_switch_views.py
@@ -30,7 +30,7 @@ def in_compute_physical_infrastructure_switches(self):
class PhysicalSwitchEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(PhysicalSwitchEntity, self).data
+ data_dict = super().data
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
data_dict['no_port'] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text)
diff --git a/cfme/common/provider.py b/cfme/common/provider.py
index b6855a7848..3c04783f0a 100644
--- a/cfme/common/provider.py
+++ b/cfme/common/provider.py
@@ -58,7 +58,7 @@ def provider_types(category):
if category not in _provider_types_cache:
_provider_types_cache[category] = {
ep.name: ep.resolve() for ep in iter_entry_points(
- 'manageiq.provider_types.{}'.format(category))
+ f'manageiq.provider_types.{category}')
}
return _provider_types_cache[category]
@@ -132,7 +132,7 @@ def data(self):
return conf.cfme_data['management_systems'][self.key]
else:
raise ProviderHasNoKey(
- 'Provider {} has no key, so cannot get yaml data'.format(self.name))
+ f'Provider {self.name} has no key, so cannot get yaml data')
@property
def mgmt(self):
@@ -147,7 +147,7 @@ def mgmt(self):
return get_mgmt(self.provider_data)
else:
raise ProviderHasNoKey(
- 'Provider {} has no key, so cannot get mgmt system'.format(self.name))
+ f'Provider {self.name} has no key, so cannot get mgmt system')
@property
def type(self):
@@ -602,7 +602,7 @@ def update(self, updates, cancel=False, validate_credentials=True):
if updates:
self.name = updates.get('name', self.name)
- success_text = '{} Provider "{}" was saved'.format(self.string_name, self.name)
+ success_text = f'{self.string_name} Provider "{self.name}" was saved'
if main_view.is_displayed:
# since 5.8.1 main view is displayed when edit starts from main view
main_view.flash.assert_message(success_text)
@@ -636,7 +636,7 @@ def delete_rest(self):
try:
provider_rest.action.delete()
except APIException as err:
- raise AssertionError("Provider wasn't deleted: {}".format(err))
+ raise AssertionError(f"Provider wasn't deleted: {err}")
response = self.appliance.rest_api.response
if not response:
@@ -830,9 +830,9 @@ def _do_stats_match(self, client, stats_to_match=None, refresh_timer=None, ui=Fa
return False
except KeyError:
raise HostStatsNotContains(
- "Host stats information does not contain '{}'".format(stat))
+ f"Host stats information does not contain '{stat}'")
except AttributeError:
- raise ProviderHasNoProperty("Provider does not know how to get '{}'".format(stat))
+ raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'")
else:
return True
@@ -1026,7 +1026,7 @@ def get_all_template_ids(self):
def get_provider_details(self, provider_id):
"""Returns the name, and type associated with the provider_id"""
# TODO: Move to ProviderCollection.find
- logger.debug('Retrieving the provider details for ID: {}'.format(provider_id))
+ logger.debug(f'Retrieving the provider details for ID: {provider_id}')
details = {}
try:
@@ -1045,7 +1045,7 @@ def get_vm_details(self, vm_id):
the vm_id.
"""
# TODO: Move to VMCollection.find
- logger.debug('Retrieving the VM details for ID: {}'.format(vm_id))
+ logger.debug(f'Retrieving the VM details for ID: {vm_id}')
details = {}
try:
@@ -1096,7 +1096,7 @@ def get_vm_id(self, vm_name):
Return the ID associated with the specified VM name
"""
# TODO: Get Provider object from VMCollection.find, then use VM.id to get the id
- logger.debug('Retrieving the ID for VM: {}'.format(vm_name))
+ logger.debug(f'Retrieving the ID for VM: {vm_name}')
for vm_id in self.get_all_vm_ids():
details = self.get_vm_details(vm_id)
if details['name'] == vm_name:
@@ -1140,7 +1140,7 @@ def get_template_guids(self, template_dict):
return result_list
-class CloudInfraProviderMixin(object):
+class CloudInfraProviderMixin:
detail_page_suffix = 'provider'
edit_page_suffix = 'provider_edit'
refresh_text = "Refresh Relationships and Power States"
@@ -1231,7 +1231,7 @@ def load_all_provider_templates(self):
return True
-class DefaultEndpoint(object):
+class DefaultEndpoint:
credential_class = Credential
name = 'default'
diff --git a/cfme/common/provider_views.py b/cfme/common/provider_views.py
index a5a4564d27..be0c61e06f 100644
--- a/cfme/common/provider_views.py
+++ b/cfme/common/provider_views.py
@@ -34,7 +34,7 @@
class ProviderEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(ProviderEntity, self).data
+ data_dict = super().data
try:
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
@@ -120,7 +120,7 @@ class InfraProviderDetailsView(ProviderDetailsView):
"""
@property
def is_displayed(self):
- return (super(InfraProviderDetailsView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Infrastructure', 'Providers'])
@@ -130,7 +130,7 @@ class CloudProviderDetailsView(ProviderDetailsView):
"""
@property
def is_displayed(self):
- return (super(CloudProviderDetailsView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Clouds', 'Providers'])
@@ -140,7 +140,7 @@ class PhysicalProviderDetailsView(ProviderDetailsView):
"""
@property
def is_displayed(self):
- return (super(PhysicalProviderDetailsView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute',
'Physical Infrastructure',
'Providers'])
@@ -345,7 +345,7 @@ def paginator(self):
@property
def is_displayed(self):
- return (super(ContainerProvidersView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Containers', 'Providers'] and
self.entities.title.text == self.SUMMARY_TEXT)
@@ -360,7 +360,7 @@ class InfraProvidersView(ProvidersView):
"""
@property
def is_displayed(self):
- return (super(InfraProvidersView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Infrastructure', 'Providers'] and
self.entities.title.text == 'Infrastructure Providers')
@@ -371,7 +371,7 @@ class CloudProvidersView(ProvidersView):
"""
@property
def is_displayed(self):
- return (super(CloudProvidersView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Clouds', 'Providers'] and
self.entities.title.text == 'Cloud Providers')
@@ -382,7 +382,7 @@ class NetworkProvidersView(ProvidersView):
"""
@property
def is_displayed(self):
- return (super(NetworkProvidersView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Networks', 'Providers'] and
self.entities.title.text == 'Network Managers')
@@ -393,13 +393,13 @@ class PhysicalProvidersView(ProvidersView):
"""
@property
def is_displayed(self):
- return (super(PhysicalProvidersView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == [
'Compute', 'Physical Infrastructure', 'Providers'] and
self.entities.title.text == 'Physical Infrastructure Providers')
-class BeforeFillMixin(object):
+class BeforeFillMixin:
"""
this mixin is used to activate appropriate tab before filling this tab
"""
@@ -442,7 +442,7 @@ class InfraProviderAddView(ProviderAddView):
@property
def is_displayed(self):
- return (super(InfraProviderAddView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Infrastructure', 'Providers'] and
self.title.text == 'Add New Infrastructure Provider')
@@ -465,7 +465,7 @@ class CloudProviderAddView(ProviderAddView):
@property
def is_displayed(self):
- return (super(CloudProviderAddView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Clouds', 'Providers'] and
self.title.text == 'Add New Cloud Provider')
@@ -526,7 +526,7 @@ class PhysicalProviderAddView(ProviderAddView):
@property
def is_displayed(self):
- return (super(PhysicalProviderAddView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == [
'Compute', 'Physical Infrastructure', 'Providers'] and
self.title.text == 'Add New Physical Infrastructure Provider')
diff --git a/cfme/common/vm.py b/cfme/common/vm.py
index 1f2ad3349f..714c69d041 100644
--- a/cfme/common/vm.py
+++ b/cfme/common/vm.py
@@ -46,7 +46,7 @@ def base_types(template=False):
from pkg_resources import iter_entry_points
search = "template" if template else "vm"
return {
- ep.name: ep.resolve() for ep in iter_entry_points('manageiq.{}_categories'.format(search))
+ ep.name: ep.resolve() for ep in iter_entry_points(f'manageiq.{search}_categories')
}
@@ -55,7 +55,7 @@ def instance_types(category, template=False):
search = "template" if template else "vm"
return {
ep.name: ep.resolve() for ep in iter_entry_points(
- 'manageiq.{}_types.{}'.format(search, category))
+ f'manageiq.{search}_types.{category}')
}
@@ -66,7 +66,7 @@ def all_types(template=False):
return all_types
-class RetirementMixin(object):
+class RetirementMixin:
def post_set_retirement(self):
raise NotImplementedError('Implement post_set_retirement.')
@@ -153,7 +153,7 @@ def set_retirement_date(self, **kwargs):
self.post_set_retirement()
-class _TemplateMixin(object):
+class _TemplateMixin:
pass
@@ -227,7 +227,7 @@ def check_compliance(self, timeout=240):
view.flash.assert_no_error()
wait_for(
lambda: self.compliance_status != original_state,
- num_sec=timeout, delay=5, message="compliance of {} checked".format(self.name)
+ num_sec=timeout, delay=5, message=f"compliance of {self.name} checked"
)
@property
@@ -255,7 +255,7 @@ def compliant(self):
elif text.startswith("compliant"):
return True
else:
- raise ValueError("{} is not a known state for compliance".format(text))
+ raise ValueError(f"{text} is not a known state for compliance")
def delete(self, cancel=False, from_details=False):
"""Deletes the VM/Instance from the VMDB.
@@ -345,7 +345,7 @@ def find_quadicon(self, from_any_provider=False, from_archived_all=False,
try:
return view.entities.get_entity(name=self.name, surf_pages=True, use_search=use_search)
except ItemNotFound:
- raise ItemNotFound("VM '{}' not found in UI!".format(self.name))
+ raise ItemNotFound(f"VM '{self.name}' not found in UI!")
def open_console(self, console='VM Console', invokes_alert=None):
"""
@@ -362,7 +362,7 @@ def open_console(self, console='VM Console', invokes_alert=None):
setting this to true will handle this.
"""
if console not in ['VM Console', 'VMRC Console']:
- raise NotImplementedError('Not supported console type: {}'.format(console))
+ raise NotImplementedError(f'Not supported console type: {console}')
view = navigate_to(self, 'Details')
@@ -477,7 +477,7 @@ def smartstate_scan(self, cancel=False, from_details=False, wait_for_task_result
handle_alert=not cancel)
if wait_for_task_result:
task = self.appliance.collections.tasks.instantiate(
- name='Scan from Vm {}'.format(self.name), tab='AllTasks')
+ name=f'Scan from Vm {self.name}', tab='AllTasks')
task.wait_for_finished()
return task
@@ -556,7 +556,7 @@ def unset_ownership(self):
})
if fill_result:
view.form.save_button.click()
- msg = 'Ownership saved for selected {}'.format(self.VM_TYPE)
+ msg = f'Ownership saved for selected {self.VM_TYPE}'
else:
view.form.cancel_button.click()
logger.warning('No change during unset_ownership')
@@ -773,7 +773,7 @@ def create_rest(self, vm_name, provider, form_values=None, check_existing=False)
provision_request.wait_for_request(num_sec=900)
if provision_request.is_succeeded():
wait_for(lambda: provider.mgmt.does_vm_exist(vm.name), num_sec=1000, delay=5,
- message="VM {} becomes visible".format(vm.name))
+ message=f"VM {vm.name} becomes visible")
else:
logger.error("Provisioning failed with the message {}".
format(provision_request.rest.message))
diff --git a/cfme/common/vm_console.py b/cfme/common/vm_console.py
index 060d744a75..81fb16cb10 100644
--- a/cfme/common/vm_console.py
+++ b/cfme/common/vm_console.py
@@ -18,7 +18,7 @@
from cfme.utils.pretty import Pretty
-class ConsoleMixin(object):
+class ConsoleMixin:
"""
A mixin to provide methods to get a vm console object
"""
@@ -34,7 +34,7 @@ def console_handle(cls, browser):
br_wt = browser.widgetastic
appliance_handle = br_wt.window_handle
cur_handles = br_wt.selenium.window_handles
- logger.info("Current Window Handles: {}".format(cur_handles))
+ logger.info(f"Current Window Handles: {cur_handles}")
for handle in cur_handles:
if handle != appliance_handle:
@@ -53,9 +53,9 @@ def vm_console(self):
appliance_handle = self.appliance.browser.widgetastic.window_handle
logger.info("Creating VMConsole:")
- logger.info(" appliance_handle: {}".format(appliance_handle))
- logger.info(" console_handle: {}".format(console_handle))
- logger.info(" name: {}".format(self.name))
+ logger.info(f" appliance_handle: {appliance_handle}")
+ logger.info(f" console_handle: {console_handle}")
+ logger.info(f" name: {self.name}")
return VMConsole(appliance_handle=appliance_handle,
console_handle=console_handle,
@@ -135,7 +135,7 @@ def _get_canvas_element(provider):
canvas, wait = wait_for(func=_get_canvas_element, func_args=[self.provider],
delay=1, handle_exceptions=True,
num_sec=timeout)
- logger.info("canvas: {}\n".format(canvas))
+ logger.info(f"canvas: {canvas}\n")
# Now run some java script to get the contents of the canvas element
# base 64 encoded.
@@ -181,7 +181,7 @@ def get_screen_text(self):
config='--user-words eng.user-words'))
tmp_file.close()
- logger.info('screen text:{}'.format(text))
+ logger.info(f'screen text:{text}')
return text
def is_connected(self):
@@ -196,7 +196,7 @@ def send_keys(self, text):
self.switch_to_console()
canvas = self.provider.get_remote_console_canvas()
canvas.click()
- logger.info("Sending following Keys to Console {}".format(text))
+ logger.info(f"Sending following Keys to Console {text}")
for character in text:
self.browser.send_keys_to_focused_element(character)
# time.sleep() is used as a short delay between two keystrokes.
@@ -231,19 +231,19 @@ def send_fullscreen(self):
def switch_to_appliance(self):
"""Switch focus to appliance tab/window."""
- logger.info("Switching to appliance: window handle = {}".format(self.appliance_handle))
+ logger.info(f"Switching to appliance: window handle = {self.appliance_handle}")
self.browser.selenium.switch_to.window(self.appliance_handle)
def switch_to_console(self):
"""Switch focus to console tab/window."""
- logger.info("Switching to console: window handle = {}".format(self.console_handle))
+ logger.info(f"Switching to console: window handle = {self.console_handle}")
if (self.console_handle and self.console_handle in self.browser.selenium.window_handles):
self.browser.selenium.switch_to_window(self.console_handle)
def wait_for_connect(self, timeout=30):
"""Wait for as long as the specified/default timeout for the console to be connected."""
try:
- logger.info('Waiting for console connection (timeout={})'.format(timeout))
+ logger.info(f'Waiting for console connection (timeout={timeout})')
wait_for(func=lambda: self.is_connected(),
delay=1, handle_exceptions=True,
num_sec=timeout)
@@ -292,7 +292,7 @@ def wait_for_text(self, timeout=45, text_to_find="", to_disappear=False):
return None
try:
if to_disappear:
- logger.info("Waiting for {} to disappear from screen".format(text_to_find))
+ logger.info(f"Waiting for {text_to_find} to disappear from screen")
result = wait_for(func=lambda: to_disappear != self.find_text_on_screen(text_to_find),
delay=5,
diff --git a/cfme/common/vm_views.py b/cfme/common/vm_views.py
index 7d1789c4c9..007a53bf12 100644
--- a/cfme/common/vm_views.py
+++ b/cfme/common/vm_views.py
@@ -41,7 +41,7 @@
class InstanceEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(InstanceEntity, self).data
+ data_dict = super().data
if 'quadicon' in data_dict and data_dict['quadicon']:
try:
quad_data = document_fromstring(data_dict['quadicon'])
@@ -130,7 +130,7 @@ def read(self):
def read_content(self):
"""This is a default Table.read() method for those who will need table content"""
- return super(SelectTable, self).read()
+ return super().read()
class VMToolbar(View):
@@ -557,7 +557,7 @@ def is_displayed(self):
getattr(self.context["object"], "VM_TYPE", None) or
getattr(self.context["object"].ENTITY, "VM_TYPE", None)
)
- expected_title = "{} Policy Simulation".format(vm_type)
+ expected_title = f"{vm_type} Policy Simulation"
return self.title.text == expected_title and len(self.form.entities.get_all()) > 0
diff --git a/cfme/configure/about.py b/cfme/configure/about.py
index 3a30a1871c..d23e0f7332 100644
--- a/cfme/configure/about.py
+++ b/cfme/configure/about.py
@@ -50,7 +50,7 @@ def get_detail(field, server):
# this is AboutModal.items function, TODO rename
return view.modal.items()[field]
except (KeyError, AttributeError):
- raise ItemNotFound('No field named {} found in "About" modal.'.format(field))
+ raise ItemNotFound(f'No field named {field} found in "About" modal.')
finally:
# close since its a blocking modal and will break further navigation
view.modal.close()
diff --git a/cfme/configure/access_control/__init__.py b/cfme/configure/access_control/__init__.py
index 71ead51520..3e262c7e98 100644
--- a/cfme/configure/access_control/__init__.py
+++ b/cfme/configure/access_control/__init__.py
@@ -230,7 +230,7 @@ def copy(self):
view.toolbar.configuration.item_select('Copy this User to a new User')
view = self.create_view(AddUserView)
new_user = self.parent.instantiate(
- name="{}copy".format(self.name),
+ name=f"{self.name}copy",
credential=Credential(principal='redhat', secret='redhat')
)
view.fill({
@@ -241,7 +241,7 @@ def copy(self):
})
view.add_button.click()
view = self.create_view(AllUserView)
- view.flash.assert_success_message('User "{}" was saved'.format(new_user.name))
+ view.flash.assert_success_message(f'User "{new_user.name}" was saved')
assert view.is_displayed
return new_user
@@ -256,8 +256,8 @@ def delete(self, cancel=True):
not having appropriate permissions OR delete is not allowed
for currently selected user
"""
- flash_success_msg = 'EVM User "{}": Delete successful'.format(self.name)
- flash_blocked_msg = "Default EVM User \"{}\" cannot be deleted".format(self.name)
+ flash_success_msg = f'EVM User "{self.name}": Delete successful'
+ flash_blocked_msg = f"Default EVM User \"{self.name}\" cannot be deleted"
delete_user_txt = 'Delete this User'
view = navigate_to(self, 'Details')
@@ -368,7 +368,7 @@ def create(self, name=None, credential=None, email=None, groups=None, cost_cente
flash_message = 'Add of new User was cancelled by the user'
else:
view.add_button.click()
- flash_message = 'User "{}" was saved'.format(user.name)
+ flash_message = f'User "{user.name}" was saved'
try:
view.flash.assert_message(user_blocked_msg)
@@ -525,7 +525,7 @@ class DetailsGroupView(ConfigurationView):
def is_displayed(self):
return (
self.accordions.accesscontrol.is_opened and
- self.title.text == u'EVM Group "{}"'.format(self.context['object'].description)
+ self.title.text == 'EVM Group "{}"'.format(self.context['object'].description)
)
@@ -635,7 +635,7 @@ def _fill_ldap_group_lookup(self, view):
'group_tenant': self.tenant})
view.add_button.click()
view = self.create_view(AllGroupView)
- view.flash.assert_success_message(u'Group "{}" was saved'.format(self.description))
+ view.flash.assert_success_message(f'Group "{self.description}" was saved')
assert view.is_displayed
def add_group_from_ldap_lookup(self):
@@ -699,11 +699,11 @@ def delete(self, cancel=True):
not having appropriate permissions OR delete is not allowed
for currently selected group
"""
- flash_success_msg = u'EVM Group "{}": Delete successful'.format(self.description)
+ flash_success_msg = f'EVM Group "{self.description}": Delete successful'
flash_blocked_msg_list = [
- (u'EVM Group "{}": Error during delete: '
+ ('EVM Group "{}": Error during delete: '
'A read only group cannot be deleted.'.format(self.description)),
- (u'EVM Group "{}": Error during delete: '
+ ('EVM Group "{}": Error during delete: '
'The group has users assigned that do not '
'belong to any other group'.format(self.description))]
delete_group_txt = 'Delete this Group'
@@ -732,7 +732,7 @@ def delete(self, cancel=True):
else:
view = self.create_view(DetailsGroupView)
assert view.is_displayed, (
- "Access Control Group {} Detail View is not displayed".format(self.description))
+ f"Access Control Group {self.description} Detail View is not displayed")
def set_group_order(self, updated_order):
""" Sets group order for group lookup
@@ -861,7 +861,7 @@ def create(self, description=None, role=None, tenant="My Company", ldap_credenti
flash_message = 'Add of new Group was cancelled by the user'
else:
view.add_button.click()
- flash_message = 'Group "{}" was saved'.format(group.description)
+ flash_message = f'Group "{group.description}" was saved'
try:
view.flash.assert_message(flash_blocked_msg)
@@ -1025,7 +1025,7 @@ def update(self, updates):
Note: In case updates is the same as original role data, update will be canceled,
as 'Save' button will not be active
"""
- flash_blocked_msg = "Read Only Role \"{}\" can not be edited".format(self.name)
+ flash_blocked_msg = f"Read Only Role \"{self.name}\" can not be edited"
edit_role_txt = 'Edit this Role'
view = navigate_to(self, 'Details')
# TODO: Remove following code when toolbar disappear issue (BZ1630012) get patched
@@ -1069,7 +1069,7 @@ def delete(self, cancel=True):
"""
flash_blocked_msg = ("Role \"{}\": Error during delete: Cannot delete record "
"because of dependent entitlements".format(self.name))
- flash_success_msg = 'Role "{}": Delete successful'.format(self.name)
+ flash_success_msg = f'Role "{self.name}": Delete successful'
delete_role_txt = 'Delete this Role'
view = navigate_to(self, 'Details')
@@ -1102,7 +1102,7 @@ def copy(self, name=None, vm_restriction=None):
Returns: Role object of copied role
"""
if name is None:
- name = "{}_copy".format(self.name)
+ name = f"{self.name}_copy"
view = navigate_to(self, 'Details')
view.toolbar.configuration.item_select('Copy this Role to a new Role')
view = self.create_view(AddRoleView, wait=10) # implicit assert
@@ -1110,7 +1110,7 @@ def copy(self, name=None, vm_restriction=None):
view.fill({'name_txt': new_role.name, "vm_restriction_select": vm_restriction})
view.add_button.click()
view = self.create_view(AllRolesView, wait=10) # implicit assert
- view.flash.assert_success_message('Role "{}" was saved'.format(new_role.name))
+ view.flash.assert_success_message(f'Role "{new_role.name}" was saved')
return new_role
@staticmethod
@@ -1167,7 +1167,7 @@ def create(self, name, vm_restriction=None, product_features=None, cancel=False)
flash_message = 'Add of new Role was cancelled by the user'
else:
view.add_button.click()
- flash_message = 'Role "{}" was saved'.format(role.name)
+ flash_message = f'Role "{role.name}" was saved'
view = self.create_view(AllRolesView, wait=10) # implicit assert
try:
@@ -1376,7 +1376,7 @@ def update(self, updates):
new_name = updates.get('name', self.name)
if changed:
view.save_button.click()
- flash_message = '{} "{}" has been successfully saved.'.format(self.obj_type, new_name)
+ flash_message = f'{self.obj_type} "{new_name}" has been successfully saved.'
else:
view.cancel_button.click()
flash_message = ('Edit of {} "{}" was canceled by the user.'
@@ -1397,7 +1397,7 @@ def delete(self, cancel=True):
if cancel:
view = self.create_view(ParentDetailsTenantView)
view.flash.assert_success_message(
- 'Tenant "{}": Delete successful'.format(self.description))
+ f'Tenant "{self.description}": Delete successful')
else:
view = self.create_view(DetailsRoleView)
assert view.is_displayed
@@ -1417,7 +1417,7 @@ def set_quota(self, **kwargs):
'template_txt': kwargs.get('template')})
if changed:
view.save_button.click()
- expected_msg = 'Quotas for {} "{}" were saved'.format(self.obj_type, self.name)
+ expected_msg = f'Quotas for {self.obj_type} "{self.name}" were saved'
else:
view.cancel_button.click()
expected_msg = ('Manage quotas for {} "{}" was cancelled by the user'
@@ -1488,7 +1488,7 @@ def create(self, name, description, parent):
view.form.cancel_button.click()
view = self.create_view(ParentDetailsTenantView)
- view.flash.assert_success_message('Tenant "{}" has been successfully added.'.format(name))
+ view.flash.assert_success_message(f'Tenant "{name}" has been successfully added.')
return tenant
def delete(self, *tenants):
@@ -1589,7 +1589,7 @@ def create(self, name, description, parent):
view.form.cancel_button.click()
view = self.create_view(ParentDetailsTenantView)
- view.flash.assert_success_message('Project "{}" has been successfully added.'.format(name))
+ view.flash.assert_success_message(f'Project "{name}" has been successfully added.')
return project
diff --git a/cfme/configure/configuration/analysis_profile.py b/cfme/configure/configuration/analysis_profile.py
index a56d025337..964ec5717a 100644
--- a/cfme/configure/configuration/analysis_profile.py
+++ b/cfme/configure/configuration/analysis_profile.py
@@ -40,7 +40,7 @@ class EventsTable(DynamicTable):
def _is_header_in_body(self):
"""Checks whether the header is erroneously specified in the body of table."""
bz = BZ(1703141, forced_streams=['5.10'])
- return False if bz.blocks else super(EventsTable, self)._is_header_in_body
+ return False if bz.blocks else super()._is_header_in_body
class AnalysisProfileToolbar(View):
@@ -307,7 +307,7 @@ def copy(self, new_name=None, cancel=False):
# TODO revisit this method when BZ is fixed:
# https://bugzilla.redhat.com/show_bug.cgi?id=1485953
if not new_name:
- new_name = '{}-copy'.format(self.name)
+ new_name = f'{self.name}-copy'
new_profile = self.parent.instantiate(
name=new_name,
description=self.description,
diff --git a/cfme/configure/configuration/diagnostics_settings.py b/cfme/configure/configuration/diagnostics_settings.py
index 9dc1e77a13..3c3fa4b3ed 100644
--- a/cfme/configure/configuration/diagnostics_settings.py
+++ b/cfme/configure/configuration/diagnostics_settings.py
@@ -301,7 +301,7 @@ def _collect(self, selection):
secondary_server = secondary_servers[0] if secondary_servers else None
if self.zone_collect:
- message = "Zone {}".format(self.appliance.server.zone.name)
+ message = f"Zone {self.appliance.server.zone.name}"
elif self.second_server_collect:
message = "MiqServer {} [{}]".format(
secondary_server.name,
diff --git a/cfme/configure/configuration/system_schedules.py b/cfme/configure/configuration/system_schedules.py
index 5a8fd024f6..8f4aa993b1 100644
--- a/cfme/configure/configuration/system_schedules.py
+++ b/cfme/configure/configuration/system_schedules.py
@@ -352,7 +352,7 @@ def create(self, name, description, active=True, action_type=None, run_type=None
elif updated:
view.add_button.click()
view = self.create_view(ScheduleAllView)
- view.flash.assert_message('Schedule "{}" was saved'.format(name))
+ view.flash.assert_message(f'Schedule "{name}" was saved')
schedule = self.instantiate(name, description, active=active, action_type=action_type,
run_type=run_type, run_every=run_type, time_zone=time_zone,
start_date=start_date, start_hour=start_hour,
diff --git a/cfme/configure/documentation.py b/cfme/configure/documentation.py
index d09e4e875b..74b12e3515 100644
--- a/cfme/configure/documentation.py
+++ b/cfme/configure/documentation.py
@@ -13,62 +13,62 @@ class LinksView(View):
@View.nested
class policies(View): # noqa
TEXT = 'Defining Policies Profiles Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class general(View): # noqa
TEXT = 'General Configuration Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class inventory(View): # noqa
TEXT = 'Infrastructure Inventory Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class automation(View): # noqa
TEXT = 'Methods For Automation Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class monitoring(View): # noqa
TEXT = 'Monitoring Alerts Reporting Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class providers(View): # noqa
TEXT = 'Providers Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class rest(View): # noqa
TEXT = 'Rest Api Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class scripting(View): # noqa
TEXT = 'Scripting Actions Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class vm_instances(View): # noqa
# TODO: title must be changed once BZ 1723813 is resolved.
TEXT = 'Virtual Machines Hosts Guide'
- link = img_anchor = Text('//a[@title="View the {}"]'.format(TEXT))
- img = Image(locator='//img[@alt="View the {}"]'.format(TEXT))
+ link = img_anchor = Text(f'//a[@title="View the {TEXT}"]')
+ img = Image(locator=f'//img[@alt="View the {TEXT}"]')
@View.nested
class customer_portal(View): # noqa
TEXT = 'Red Hat Customer Portal'
- link = Text('//a[normalize-space(.)="{}"]'.format(TEXT))
+ link = Text(f'//a[normalize-space(.)="{TEXT}"]')
class DocView(View):
diff --git a/cfme/configure/settings.py b/cfme/configure/settings.py
index 9be1bae222..6a592cb1dd 100644
--- a/cfme/configure/settings.py
+++ b/cfme/configure/settings.py
@@ -119,11 +119,11 @@ def copy(self, description=None, cancel=False):
})
else:
new_time_profile = self.parent.instantiate(
- description="{} copy".format(self.description),
+ description=f"{self.description} copy",
scope=self.scope
)
changed = view.form.fill({
- 'description': "{} copy".format(self.description),
+ 'description': f"{self.description} copy",
'scope': self.scope,
})
diff --git a/cfme/configure/tasks.py b/cfme/configure/tasks.py
index 78c2f27331..9a5369df77 100644
--- a/cfme/configure/tasks.py
+++ b/cfme/configure/tasks.py
@@ -160,9 +160,9 @@ def is_successfully_finished(self):
message = self.message.lower()
if self.status == self.ERROR:
if 'timed out' in message:
- raise TimedOutError("Task {} timed out: {}".format(self.name, message))
+ raise TimedOutError(f"Task {self.name} timed out: {message}")
else:
- raise Exception("Task {} error: {}".format(self.name, message))
+ raise Exception(f"Task {self.name} error: {message}")
if self.state.lower() == 'finished' and self.status == self.OK:
return True
@@ -248,12 +248,12 @@ def is_successfully_finished(self, silent_failure=False, *tasks):
if row[1].browser.is_displayed('i[@class="pficon pficon-error-circle-o"]',
parent=row[1]):
if silent_failure:
- logger.warning("Task {} error: {}".format(row.task_name.text, message))
+ logger.warning(f"Task {row.task_name.text} error: {message}")
return False
elif 'timed out' in message:
- raise TimedOutError("Task {} timed out: {}".format(row.task_name.text, message))
+ raise TimedOutError(f"Task {row.task_name.text} timed out: {message}")
else:
- Exception("Task {} error: {}".format(row.task_name.text, message))
+ Exception(f"Task {row.task_name.text} error: {message}")
return True
def wait_for_finished(self, delay=5, timeout='5m', *tasks):
diff --git a/cfme/containers/container.py b/cfme/containers/container.py
index 860461bf4b..6d3a31852f 100644
--- a/cfme/containers/container.py
+++ b/cfme/containers/container.py
@@ -58,7 +58,7 @@ def __init__(self, parent, logger=None):
@property
def is_displayed(self):
- return self.in_containers and super(ContainerAllView, self).is_displayed
+ return self.in_containers and super().is_displayed
class ContainerDetailsView(ContainerObjectDetailsBaseView):
diff --git a/cfme/containers/image.py b/cfme/containers/image.py
index 7eb3a31359..ea2e3e886a 100644
--- a/cfme/containers/image.py
+++ b/cfme/containers/image.py
@@ -87,7 +87,7 @@ def perform_smartstate_analysis(self, wait_for_finish=False, timeout='20M'):
if wait_for_finish:
try:
task = self.appliance.collections.tasks.instantiate(
- name="Container Image Analysis: '{}'".format(self.name), tab='AllTasks')
+ name=f"Container Image Analysis: '{self.name}'", tab='AllTasks')
task.wait_for_finished(timeout=timeout)
except TimedOutError:
raise TimedOutError('Timeout exceeded, Waited too much time for SSA to finish ({}).'
@@ -128,7 +128,7 @@ def compliant(self):
elif text.startswith("compliant"):
return True
else:
- raise ValueError("{} is not a known state for compliance".format(text))
+ raise ValueError(f"{text} is not a known state for compliance")
def scan(self):
""" Start SmartState Analysis Scan of OCP Image.
@@ -243,9 +243,9 @@ def perform_smartstate_analysis_multiple_images(
images_view.toolbar.configuration.item_select(
'Perform SmartState Analysis', handle_alert=True)
for image_entity in image_entities:
- image_entities_names.append("Container Image Analysis: '{}'".format(image_entity.name))
+ image_entities_names.append(f"Container Image Analysis: '{image_entity.name}'")
images_view.flash.assert_success_message(
- '"{}": Analysis successfully initiated'.format(image_entity.name), partial=True
+ f'"{image_entity.name}": Analysis successfully initiated', partial=True
)
if wait_for_finish:
diff --git a/cfme/containers/node.py b/cfme/containers/node.py
index 6f730bbc77..be98191d98 100644
--- a/cfme/containers/node.py
+++ b/cfme/containers/node.py
@@ -52,7 +52,7 @@ class NodeAllView(NodeView):
@property
def is_displayed(self):
- return self.in_node and super(NodeAllView, self).is_displayed
+ return self.in_node and super().is_displayed
class NodeDetailsView(ContainerObjectDetailsBaseView):
diff --git a/cfme/containers/provider/__init__.py b/cfme/containers/provider/__init__.py
index 9d09461d15..395d44c97e 100644
--- a/cfme/containers/provider/__init__.py
+++ b/cfme/containers/provider/__init__.py
@@ -167,7 +167,7 @@ class ContainerProviderDetailsView(ProviderDetailsView, LoggingableView):
@property
def is_displayed(self):
- return (super(ContainerProviderDetailsView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == ['Compute', 'Containers', 'Providers'])
@property
@@ -225,7 +225,7 @@ class ContainersProvider(BaseProvider, Pretty, PolicyProfileAssignable):
provider_data = attr.ib(default=None)
def __attrs_post_init__(self):
- super(ContainersProvider, self).__attrs_post_init__()
+ super().__attrs_post_init__()
self.parent = self.appliance.collections.containers_providers
@property
@@ -653,7 +653,7 @@ def summary_text(self):
# Common methods:
-class ContainersTestItem(object):
+class ContainersTestItem:
"""This is a generic test item. Especially used for parametrized functions
"""
__test__ = False
@@ -693,7 +693,7 @@ def get_pretty_id(cls, obj):
return pretty_id
-class LoadDetailsMixin(object):
+class LoadDetailsMixin:
"""Embed load details functionality for objects -
required for some classes like PolicyProfileAssignable"""
@@ -703,7 +703,7 @@ def load_details(self, refresh=False):
view.browser.refresh()
-class Labelable(object):
+class Labelable:
"""Provide the functionality to set labels"""
_LABEL_NAMEVAL_PATTERN = re.compile(r'^[A-Za-z0-9_.]+$')
@@ -777,7 +777,7 @@ def navigate_and_get_rows(provider, obj, count, silent_failure=False):
return sample(rows, min(count, len(rows)))
-class GetRandomInstancesMixin(object):
+class GetRandomInstancesMixin:
def get_random_instances(self, count=1):
"""Getting random instances of the object."""
diff --git a/cfme/containers/provider/openshift.py b/cfme/containers/provider/openshift.py
index 8f6fd1d9f9..501b0ffb13 100644
--- a/cfme/containers/provider/openshift.py
+++ b/cfme/containers/provider/openshift.py
@@ -22,7 +22,7 @@
from cfme.utils.wait import wait_for
-class CustomAttribute(object):
+class CustomAttribute:
def __init__(self, name, value, field_type=None, href=None):
self.name = name
self.value = value
@@ -122,7 +122,7 @@ def create(self, **kwargs):
for profile in [provider_profile, node_profile]:
profile.assign_to("The Enterprise")
- super(OpenshiftProvider, self).create(**kwargs)
+ super().create(**kwargs)
@cached_property
def cli(self):
@@ -203,7 +203,7 @@ def from_config(cls, prov_config, prov_key, appliance=None):
elif AlertsEndpoint.name == endp:
endpoints[endp] = AlertsEndpoint(**prov_config['endpoints'][endp])
else:
- raise Exception('Unsupported endpoint type "{}".'.format(endp))
+ raise Exception(f'Unsupported endpoint type "{endp}".')
settings = prov_config.get('settings', {})
advanced = settings.get('advanced', {})
@@ -404,7 +404,7 @@ def get_metrics(self, **kwargs):
name=self.name, id=mgmt_system_id))
if filters:
- logger.info("Filtering by: {f}".format(f=filters))
+ logger.info(f"Filtering by: {filters}")
filters["parent_ems_id"] = mgmt_system_id
return self.appliance.db.client.session.query(metrics_tbl).filter_by(**filters)
@@ -420,7 +420,7 @@ def wait_for_collected_metrics(self, timeout="50m", table_name="metrics"):
def is_collected():
metrics_count = self.get_metrics(table=table_name).count()
- logger.info("Current metrics found count is {count}".format(count=metrics_count))
+ logger.info(f"Current metrics found count is {metrics_count}")
return metrics_count > 0
logger.info("Monitoring DB for metrics collection")
diff --git a/cfme/containers/service.py b/cfme/containers/service.py
index 78f4112627..04b4da7624 100644
--- a/cfme/containers/service.py
+++ b/cfme/containers/service.py
@@ -34,7 +34,7 @@ class ServiceAllView(ServiceView):
@property
def is_displayed(self):
- return self.in_service and super(ServiceAllView, self).is_displayed
+ return self.in_service and super().is_displayed
class ServiceDetailsView(ContainerObjectDetailsBaseView):
diff --git a/cfme/control/explorer/actions.py b/cfme/control/explorer/actions.py
index df81cb62f8..674f1174d9 100644
--- a/cfme/control/explorer/actions.py
+++ b/cfme/control/explorer/actions.py
@@ -203,7 +203,7 @@ def update(self, updates):
'Action "{}" was saved'.format(updates.get("description", self.description)))
else:
view.flash.assert_message(
- 'Edit of Action "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Action "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Action in UI.
@@ -219,7 +219,7 @@ def delete(self, cancel=False):
else:
view = self.create_view(ActionsAllView, wait="15s")
view.flash.assert_success_message(
- 'Action "{}": Delete successful'.format(self.description))
+ f'Action "{self.description}": Delete successful')
@property
def exists(self):
@@ -270,7 +270,7 @@ def create(self, description, action_type, action_values=None):
view.add_button.click()
action = self.instantiate(description, action_type, action_values=action_values)
view = action.create_view(ActionDetailsView, wait='10s')
- view.flash.assert_success_message('Action "{}" was added'.format(action.description))
+ view.flash.assert_success_message(f'Action "{action.description}" was added')
return action
diff --git a/cfme/control/explorer/alert_profiles.py b/cfme/control/explorer/alert_profiles.py
index d59337d17c..4097c0c57f 100644
--- a/cfme/control/explorer/alert_profiles.py
+++ b/cfme/control/explorer/alert_profiles.py
@@ -144,7 +144,7 @@ def update(self, updates):
updates.get("description", self.description)))
else:
view.flash.assert_message(
- 'Edit of Alert Profile "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Alert Profile "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Alert Profile in UI.
@@ -222,7 +222,7 @@ def create(self, alert_profile_class, description, alerts=None, notes=None):
view = alert_profile.create_view(AlertProfileDetailsView)
assert view.is_displayed
view.flash.assert_success_message(
- 'Alert Profile "{}" was added'.format(alert_profile.description))
+ f'Alert Profile "{alert_profile.description}" was added')
return alert_profile
@@ -242,9 +242,9 @@ class AlertProfileNew(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.alert_profiles.tree.click_path("All Alert Profiles",
- "{} Alert Profiles".format(self.obj.TYPE))
+ f"{self.obj.TYPE} Alert Profiles")
self.prerequisite_view.configuration.item_select(
- "Add a New {} Alert Profile".format(self.obj.TYPE))
+ f"Add a New {self.obj.TYPE} Alert Profile")
@navigator.register(BaseAlertProfile, "Edit")
@@ -272,7 +272,7 @@ class AlertProfileDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.alert_profiles.tree.click_path("All Alert Profiles",
- "{} Alert Profiles".format(self.obj.TYPE), self.obj.description)
+ f"{self.obj.TYPE} Alert Profiles", self.obj.description)
class ClusterAlertProfile(BaseAlertProfile):
diff --git a/cfme/control/explorer/alerts.py b/cfme/control/explorer/alerts.py
index a127bd1d93..1fa739c90c 100644
--- a/cfme/control/explorer/alerts.py
+++ b/cfme/control/explorer/alerts.py
@@ -260,7 +260,7 @@ def update(self, updates):
'Alert "{}" was saved'.format(updates.get("description", self.description)))
else:
view.flash.assert_message(
- 'Edit of Alert "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Alert "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Alert in UI.
@@ -277,7 +277,7 @@ def delete(self, cancel=False):
view = self.create_view(AlertsAllView)
assert view.is_displayed
view.flash.assert_success_message(
- 'Alert "{}": Delete successful'.format(self.description))
+ f'Alert "{self.description}": Delete successful')
def copy(self, **updates):
"""Copy this Alert in UI.
@@ -385,7 +385,7 @@ def create(self, description, severity=None, active=None, based_on=None, evaluat
alert._fill(view)
view.add_button.click()
view = alert.create_view(AlertDetailsView, wait='10s')
- view.flash.assert_success_message('Alert "{}" was added'.format(alert.description))
+ view.flash.assert_success_message(f'Alert "{alert.description}" was added')
return alert
def all(self):
diff --git a/cfme/control/explorer/conditions.py b/cfme/control/explorer/conditions.py
index f869609b24..38b87e3ab5 100644
--- a/cfme/control/explorer/conditions.py
+++ b/cfme/control/explorer/conditions.py
@@ -219,7 +219,7 @@ def delete(self, cancel=False):
cancel: Whether to cancel the deletion (default False).
"""
view = navigate_to(self, "Details")
- view.configuration.item_select("Delete this {} Condition".format(self.FIELD_VALUE),
+ view.configuration.item_select(f"Delete this {self.FIELD_VALUE} Condition",
handle_alert=not cancel)
if cancel:
assert view.is_displayed
@@ -271,7 +271,7 @@ def create(self, condition_class, description, expression=None, scope=None, note
view.wait_displayed()
view.add_button.click()
view = condition.create_view(ConditionDetailsView, wait="10s")
- view.flash.assert_success_message('Condition "{}" was added'.format(condition.description))
+ view.flash.assert_success_message(f'Condition "{condition.description}" was added')
return condition
def all(self):
@@ -295,10 +295,10 @@ class ConditionNew(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.conditions.tree.click_path(
"All Conditions",
- "{} Conditions".format(self.obj.TREE_NODE)
+ f"{self.obj.TREE_NODE} Conditions"
)
self.prerequisite_view.configuration.item_select(
- "Add a New {} Condition".format(self.obj.PRETTY))
+ f"Add a New {self.obj.PRETTY} Condition")
@navigator.register(BaseCondition, "Edit")
@@ -309,7 +309,7 @@ class ConditionEdit(CFMENavigateStep):
def step(self, *args, **kwargs):
self.view.conditions.tree.click_path(
"All Conditions",
- "{} Conditions".format(self.obj.TREE_NODE),
+ f"{self.obj.TREE_NODE} Conditions",
self.obj.description
)
self.prerequisite_view.configuration.item_select("Edit this Condition")
@@ -323,7 +323,7 @@ class ConditionDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.conditions.tree.click_path(
"All Conditions",
- "{} Conditions".format(self.obj.TREE_NODE),
+ f"{self.obj.TREE_NODE} Conditions",
self.obj.description
)
@@ -336,7 +336,7 @@ class PolicyConditionDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.policies.tree.click_path(
"All Policies",
- "{} Policies".format(self.obj.context_policy.TYPE),
+ f"{self.obj.context_policy.TYPE} Policies",
"{} {} Policies".format(
self.obj.context_policy.TREE_NODE,
self.obj.context_policy.TYPE
diff --git a/cfme/control/explorer/policies.py b/cfme/control/explorer/policies.py
index a90e13e408..91b4aa7556 100644
--- a/cfme/control/explorer/policies.py
+++ b/cfme/control/explorer/policies.py
@@ -274,7 +274,7 @@ def __str__(self):
@property
def name_for_policy_profile(self):
- return "{} {}: {}".format(self.PRETTY, self.TYPE, self.description)
+ return f"{self.PRETTY} {self.TYPE}: {self.description}"
def update(self, updates):
"""Update this Policy in UI.
@@ -297,7 +297,7 @@ def update(self, updates):
'Policy "{}" was saved'.format(updates.get("description", self.description)))
else:
view.flash.assert_message(
- 'Edit of Policy "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Policy "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Policy in UI.
@@ -307,7 +307,7 @@ def delete(self, cancel=False):
"""
view = navigate_to(self, "Details")
view.configuration.item_select(
- "Delete this {} Policy".format(self.PRETTY),
+ f"Delete this {self.PRETTY} Policy",
handle_alert=not cancel
)
if cancel:
@@ -322,13 +322,13 @@ def copy(self, cancel=False):
cancel: Whether to cancel the copying (default False).
"""
view = navigate_to(self, "Details")
- view.configuration.item_select("Copy this {} Policy".format(self.PRETTY),
+ view.configuration.item_select(f"Copy this {self.PRETTY} Policy",
handle_alert=not cancel)
view = self.create_view(PolicyDetailsView)
assert view.is_displayed
- view.flash.assert_success_message('Policy "Copy of {}" was added'.format(self.description))
+ view.flash.assert_success_message(f'Policy "Copy of {self.description}" was added')
policy_copy = copy(self)
- policy_copy.description = "Copy of {}".format(self.description)
+ policy_copy.description = f"Copy of {self.description}"
return policy_copy
def assign_events(self, *events, **kwargs):
@@ -352,11 +352,11 @@ def assign_events(self, *events, **kwargs):
changed = view.fill({"events": events})
if changed:
view.save_button.click()
- view.flash.assert_success_message('Policy "{}" was saved'.format(self.description))
+ view.flash.assert_success_message(f'Policy "{self.description}" was saved')
else:
view.cancel_button.click()
view.flash.assert_success_message(
- 'Edit of Policy "{}" was cancelled by the user'.format(self.description)
+ f'Edit of Policy "{self.description}" was cancelled by the user'
)
def unassign_events(self, *events, **kwargs):
@@ -379,11 +379,11 @@ def unassign_events(self, *events, **kwargs):
changed = view.fill({"events": events})
if changed:
view.save_button.click()
- view.flash.assert_success_message('Policy "{}" was saved'.format(self.description))
+ view.flash.assert_success_message(f'Policy "{self.description}" was saved')
else:
view.cancel_button.click()
view.flash.assert_success_message(
- 'Edit of Policy "{}" was cancelled by the user'.format(self.description)
+ f'Edit of Policy "{self.description}" was cancelled by the user'
)
def is_event_assigned(self, event):
@@ -401,10 +401,10 @@ def assign_conditions(self, *conditions):
changed = view.fill({"conditions": [condition.description for condition in conditions]})
if changed:
view.save_button.click()
- flash_message = 'Policy "{}" was saved'.format(self.description)
+ flash_message = f'Policy "{self.description}" was saved'
else:
view.cancel_button.click()
- flash_message = 'Edit of Policy "{}" was cancelled by the user'.format(self.description)
+ flash_message = f'Edit of Policy "{self.description}" was cancelled by the user'
view.flash.assert_success_message(flash_message)
def is_condition_assigned(self, condition):
@@ -440,7 +440,7 @@ def assign_actions_to_event(self, event, actions):
# Check whether we have all necessary events assigned
if not self.is_event_assigned(event):
self.assign_events(event, extend=True)
- assert self.is_event_assigned(event), "Could not assign event {}!".format(event)
+ assert self.is_event_assigned(event), f"Could not assign event {event}!"
# And now we can assign actions
self.context_event = event
view = navigate_to(self, "Event Details")
@@ -641,7 +641,7 @@ def create(self, policy_class, description, active=True, scope=None, notes=None)
view.add_button.click()
view = policy.create_view(PolicyDetailsView, o=policy, wait='10s')
- view.flash.assert_success_message('Policy "{}" was added'.format(policy.description))
+ view.flash.assert_success_message(f'Policy "{policy.description}" was added')
return policy
def all(self):
@@ -670,8 +670,8 @@ class PolicyNew(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.policies.tree.click_path(
"All Policies",
- "{} Policies".format(self.obj.TYPE),
- "{} {} Policies".format(self.obj.TREE_NODE, self.obj.TYPE)
+ f"{self.obj.TYPE} Policies",
+ f"{self.obj.TREE_NODE} {self.obj.TYPE} Policies"
)
self.prerequisite_view.configuration.item_select("Add a New {} {} Policy".format(
self.obj.PRETTY, self.obj.TYPE))
@@ -694,8 +694,8 @@ class PolicyDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.policies.tree.click_path(
"All Policies",
- "{} Policies".format(self.obj.TYPE),
- "{} {} Policies".format(self.obj.TREE_NODE, self.obj.TYPE),
+ f"{self.obj.TYPE} Policies",
+ f"{self.obj.TREE_NODE} {self.obj.TYPE} Policies",
self.obj.description
)
@@ -708,8 +708,8 @@ class PolicyEventDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.view.policies.tree.click_path(
"All Policies",
- "{} Policies".format(self.obj.TYPE),
- "{} {} Policies".format(self.obj.TREE_NODE, self.obj.TYPE),
+ f"{self.obj.TYPE} Policies",
+ f"{self.obj.TREE_NODE} {self.obj.TYPE} Policies",
self.obj.description,
self.obj.context_event
)
diff --git a/cfme/control/explorer/policy_profiles.py b/cfme/control/explorer/policy_profiles.py
index 4dfefec767..aaaf03315a 100644
--- a/cfme/control/explorer/policy_profiles.py
+++ b/cfme/control/explorer/policy_profiles.py
@@ -108,7 +108,7 @@ def update(self, updates):
updates.get("description", self.description)))
else:
view.flash.assert_message(
- 'Edit of Policy Profile "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Policy Profile "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Policy Profile in UI.
@@ -125,7 +125,7 @@ def delete(self, cancel=False):
view = self.create_view(PolicyProfilesAllView)
assert view.is_displayed
view.flash.assert_success_message(
- 'Policy Profile "{}": Delete successful'.format(self.description))
+ f'Policy Profile "{self.description}": Delete successful')
@property
def exists(self):
diff --git a/cfme/dashboard.py b/cfme/dashboard.py
index 5b5c1ee8f0..c0fe293434 100644
--- a/cfme/dashboard.py
+++ b/cfme/dashboard.py
@@ -45,7 +45,7 @@ class Kebab(Widget):
ITEMS = './ul/li/a'
def __init__(self, parent, button_id=None, logger=None):
- super(Kebab, self).__init__(parent, logger=logger)
+ super().__init__(parent, logger=logger)
if button_id is not None:
self.locator = (
'.//div[contains(@class, "dropdown-kebab-pf") and ./button[@id={}]]'.format(
@@ -230,7 +230,7 @@ class ParticularDashboardView(DashboardView):
@property
def is_displayed(self):
return (
- super(ParticularDashboardView, self).is_displayed and
+ super().is_displayed and
self.dashboards(title=self.context['object'].name).is_active)
@@ -324,7 +324,7 @@ def minimize(self):
self.close_zoom()
view = self.widget_view
if 'Maximize' not in view.menu.items and 'Minimize' not in view.menu.items:
- raise ValueError('The widget {} cannot be maximized or minimized'.format(self.name))
+ raise ValueError(f'The widget {self.name} cannot be maximized or minimized')
if 'Minimize' in view.menu.items:
view.menu.select('Minimize')
@@ -334,7 +334,7 @@ def restore(self):
view = self.widget_view
view.parent.parent.ensure_zoom_closed()
if 'Maximize' not in view.menu.items and 'Minimize' not in view.menu.items:
- raise ValueError('The widget {} cannot be maximized or minimized'.format(self.name))
+ raise ValueError(f'The widget {self.name} cannot be maximized or minimized')
if 'Maximize' in view.menu.items:
view.menu.select('Maximize')
diff --git a/cfme/exceptions.py b/cfme/exceptions.py
index 63218329ad..725e4af01a 100644
--- a/cfme/exceptions.py
+++ b/cfme/exceptions.py
@@ -17,7 +17,7 @@ def __init__(self, msg, version):
self.version = version
def __str__(self):
- return "Version {} not supported. {}".format(self.version, self.msg)
+ return f"Version {self.version} not supported. {self.msg}"
class BugException(CFMEException):
@@ -27,7 +27,7 @@ def __init__(self, bug_no, operation):
self.operation = operation
def __str__(self):
- return "Bug {} blocks the operation [{}]".format(self.bug_no, self.operation)
+ return f"Bug {self.bug_no} blocks the operation [{self.operation}]"
class ConsoleNotSupported(CFMEException):
@@ -51,7 +51,7 @@ def __init__(self, console_type):
self.console_type = console_type
def __str__(self):
- return "Console type not supported: {}".format(self.console_type)
+ return f"Console type not supported: {self.console_type}"
class TaskFailedException(CFMEException):
@@ -62,7 +62,7 @@ def __init__(self, task_name, message):
self.message = message
def __str__(self):
- return "Task {} error: {}".format(self.task_name, self.message)
+ return f"Task {self.task_name} error: {self.message}"
class CFMEExceptionOccured(CFMEException):
@@ -122,7 +122,7 @@ def __init__(self, page_name):
self.page_name = page_name
def __str__(self):
- return 'Unable to navigate to page "{}"'.format(self.page_name)
+ return f'Unable to navigate to page "{self.page_name}"'
pass
diff --git a/cfme/fixtures/ansible_tower.py b/cfme/fixtures/ansible_tower.py
index 7026ad74ff..462e95e76a 100644
--- a/cfme/fixtures/ansible_tower.py
+++ b/cfme/fixtures/ansible_tower.py
@@ -12,7 +12,7 @@ def ansible_tower_dialog_rest(request, appliance):
"""Creates service dialog using REST API."""
uid = fauxfactory.gen_alphanumeric()
data = {
- "description": "my ansible dialog {}".format(uid),
+ "description": f"my ansible dialog {uid}",
"buttons": "submit,cancel",
"label": uid,
"dialog_tabs": [
diff --git a/cfme/fixtures/appliance.py b/cfme/fixtures/appliance.py
index 6d92a2dcb9..e1d3ce5ad2 100644
--- a/cfme/fixtures/appliance.py
+++ b/cfme/fixtures/appliance.py
@@ -267,7 +267,7 @@ def get_vddk_url(provider):
except ValueError:
major = str(provider.version)
minor = "0"
- vddk_version = "v{}_{}".format(major, minor)
+ vddk_version = f"v{major}_{minor}"
try:
vddk_urls = conf.cfme_data.basic_info.vddk_url
@@ -281,7 +281,7 @@ def get_vddk_url(provider):
url = vddk_urls.get(vddk_version)
if url is None:
- pytest.skip("VDDK {} is unavailable, skipping test".format(vddk_version))
+ pytest.skip(f"VDDK {vddk_version} is unavailable, skipping test")
return url
diff --git a/cfme/fixtures/artifactor_plugin.py b/cfme/fixtures/artifactor_plugin.py
index 5839f619d5..819b9e4c93 100644
--- a/cfme/fixtures/artifactor_plugin.py
+++ b/cfme/fixtures/artifactor_plugin.py
@@ -68,7 +68,7 @@ def get_name(obj):
str(obj))
-class DummyClient(object):
+class DummyClient:
def fire_hook(self, *args, **kwargs):
return
diff --git a/cfme/fixtures/blockers.py b/cfme/fixtures/blockers.py
index 8b001548b2..4e55db5092 100644
--- a/cfme/fixtures/blockers.py
+++ b/cfme/fixtures/blockers.py
@@ -37,7 +37,7 @@ def blockers(uses_blockers, meta):
result = []
for blocker in meta.get("blockers", []):
if isinstance(blocker, int):
- result.append(Blocker.parse("BZ#{}".format(blocker)))
+ result.append(Blocker.parse(f"BZ#{blocker}"))
elif isinstance(blocker, Blocker):
result.append(blocker)
else:
@@ -52,7 +52,7 @@ def bug(blocker):
Returns:
Instance of :py:class:`utils.bz.BugWrapper` or :py:class:`NoneType` if the bug is closed.
"""
- return lambda bug_id, **kwargs: blocker("BZ#{}".format(bug_id), **kwargs).bugzilla_bug
+ return lambda bug_id, **kwargs: blocker(f"BZ#{bug_id}", **kwargs).bugzilla_bug
def pytest_addoption(parser):
@@ -69,14 +69,14 @@ def pytest_collection_modifyitems(session, config, items):
if not config.getvalue("list_blockers"):
return
store.terminalreporter.write("Loading blockers ...\n", bold=True)
- blocking = set([])
+ blocking = set()
for item in items:
if "blockers" not in item._metadata:
continue
for blocker in item._metadata["blockers"]:
if isinstance(blocker, int):
# TODO: DRY
- blocker_object = Blocker.parse("BZ#{}".format(blocker))
+ blocker_object = Blocker.parse(f"BZ#{blocker}")
else:
blocker_object = Blocker.parse(blocker)
if blocker_object.blocks:
@@ -86,16 +86,16 @@ def pytest_collection_modifyitems(session, config, items):
for blocker in blocking:
if isinstance(blocker, BZ):
bug = blocker.bugzilla_bug
- store.terminalreporter.write("- #{} - {}\n".format(bug.id, bug.status))
- store.terminalreporter.write(" {}\n".format(bug.summary))
+ store.terminalreporter.write(f"- #{bug.id} - {bug.status}\n")
+ store.terminalreporter.write(f" {bug.summary}\n")
store.terminalreporter.write(
" {} -> {}\n".format(str(bug.version), str(bug.target_release)))
store.terminalreporter.write(
- " https://bugzilla.redhat.com/show_bug.cgi?id={}\n\n".format(bug.id))
+ f" https://bugzilla.redhat.com/show_bug.cgi?id={bug.id}\n\n")
elif isinstance(blocker, GH):
bug = blocker.data
store.terminalreporter.write("- {}\n".format(str(bug)))
- store.terminalreporter.write(" {}\n".format(bug.title))
+ store.terminalreporter.write(f" {bug.title}\n")
else:
store.terminalreporter.write("- {}\n".format(str(blocker.data)))
else:
diff --git a/cfme/fixtures/browser.py b/cfme/fixtures/browser.py
index 942c0cf31b..39e08f7cc1 100644
--- a/cfme/fixtures/browser.py
+++ b/cfme/fixtures/browser.py
@@ -65,7 +65,7 @@ def pytest_exception_interact(node, call, report):
exception_filename = str(call.excinfo.traceback[-1].path).replace(
project_path.strpath + "/", ''
)
- exception_location = "{}:{}".format(exception_filename, exception_lineno)
+ exception_location = f"{exception_filename}:{exception_lineno}"
fire_art_test_hook(
node, 'tb_info',
exception=exception_name, file_line=exception_location,
diff --git a/cfme/fixtures/cli.py b/cfme/fixtures/cli.py
index 528711da0a..4e47ec1f95 100644
--- a/cfme/fixtures/cli.py
+++ b/cfme/fixtures/cli.py
@@ -171,14 +171,14 @@ def get_puddle_cfme_version(repo_file_path):
# The urljoin does replace the last bit of url when there is no slash on
# the end, which does happen with the repos we get, therefore we better
# join the urls just by string concatenation.
- repomd_url = '{}/repodata/repomd.xml'.format(cfme_baseurl)
+ repomd_url = f'{cfme_baseurl}/repodata/repomd.xml'
repomd_response = requests.get(repomd_url)
assert repomd_response.ok
repomd_root = etree.fromstring(repomd_response.content)
cfme_primary_path, = repomd_root.xpath(
"repo:data[@type='primary']/repo:location/@href",
namespaces=namespaces)
- cfme_primary_url = '{}/{}'.format(cfme_baseurl, cfme_primary_path)
+ cfme_primary_url = f'{cfme_baseurl}/{cfme_primary_path}'
cfme_primary_response = requests.get(cfme_primary_url)
assert cfme_primary_response.ok
primary_xml = zlib.decompress(cfme_primary_response.content, zlib.MAX_WBITS | 16)
@@ -218,7 +218,7 @@ def get_apps(requests, appliance, old_version, count, preconfigured, pytest_conf
for app in apps:
app.db.extend_partition()
app.ssh_client.run_command(
- "curl {} -o /etc/yum.repos.d/update.repo".format(url)
+ f"curl {url} -o /etc/yum.repos.d/update.repo"
)
yield apps
@@ -384,11 +384,11 @@ def appliance_with_providers(appliance_preupdate):
def provider_app_crud(provider_class, appliance):
try:
prov = list_providers_by_class(provider_class)[0]
- logger.info("using provider {}".format(prov.name))
+ logger.info(f"using provider {prov.name}")
prov.appliance = appliance
return prov
except IndexError:
- pytest.skip("No {} providers available (required)".format(provider_class.type_name))
+ pytest.skip(f"No {provider_class.type_name} providers available (required)")
def provision_vm(request, provider):
@@ -432,7 +432,7 @@ def update_appliance(appliance):
def upgrade_appliances(appliances):
for appliance in appliances:
result = appliance.ssh_client.run_command("yum update -y", timeout=3600)
- assert result.success, "update failed {}".format(result.output)
+ assert result.success, f"update failed {result.output}"
def do_appliance_versions_match(appliance1, appliance2):
diff --git a/cfme/fixtures/datafile.py b/cfme/fixtures/datafile.py
index 17f268be66..34c19c9fef 100644
--- a/cfme/fixtures/datafile.py
+++ b/cfme/fixtures/datafile.py
@@ -92,7 +92,7 @@ def pytest_sessionfinish(session, exitstatus):
if unused_data_files:
# Write the log of unused data files out, minus the data dir prefix
udf_log = ''.join(
- (line[len(str(data_path)):] + '\n' for line in unused_data_files)
+ line[len(str(data_path)):] + '\n' for line in unused_data_files
)
udf_log_file.write(udf_log + '\n')
@@ -107,7 +107,7 @@ def pytest_sessionfinish(session, exitstatus):
)
-class _FixtureDataFile(object):
+class _FixtureDataFile:
def __init__(self, request):
self.base_path = str(request.session.fspath)
self.testmod_path = str(request.fspath)
diff --git a/cfme/fixtures/disable_forgery_protection.py b/cfme/fixtures/disable_forgery_protection.py
index 6760c4e3a2..23ca1b5585 100644
--- a/cfme/fixtures/disable_forgery_protection.py
+++ b/cfme/fixtures/disable_forgery_protection.py
@@ -18,7 +18,7 @@ def disable_forgery_protection():
ssh_client.run_command("service evmserverd restart")
timediff = time.time() - starttime
- logger.info('Turned off "allow_forgery_protection" in: {}'.format(timediff))
+ logger.info(f'Turned off "allow_forgery_protection" in: {timediff}')
yield
@@ -32,4 +32,4 @@ def disable_forgery_protection():
ssh_client.run_command("service evmserverd restart")
timediff = time.time() - starttime
- logger.info('Turned on "allow_forgery_protection" in: {}'.format(timediff))
+ logger.info(f'Turned on "allow_forgery_protection" in: {timediff}')
diff --git a/cfme/fixtures/has_persistent_volume.py b/cfme/fixtures/has_persistent_volume.py
index 96b66cffe1..8af6b5294d 100644
--- a/cfme/fixtures/has_persistent_volume.py
+++ b/cfme/fixtures/has_persistent_volume.py
@@ -9,4 +9,4 @@ def has_persistent_volume(provider, appliance):
if vols_count:
yield
else:
- pytest.skip('No Persistent Volumes Detected on OpenShift Provider {}'.format(provider.name))
+ pytest.skip(f'No Persistent Volumes Detected on OpenShift Provider {provider.name}')
diff --git a/cfme/fixtures/log.py b/cfme/fixtures/log.py
index 6e5317d443..7094427838 100644
--- a/cfme/fixtures/log.py
+++ b/cfme/fixtures/log.py
@@ -32,12 +32,12 @@ def pytest_runtest_setup(item):
def pytest_collection_modifyitems(session, config, items):
log.logger.info(log.format_marker('Starting new test run', mark="="))
expression = config.getvalue('keyword') or False
- expr_string = ', will filter with "{}"'.format(expression) if expression else ''
+ expr_string = f', will filter with "{expression}"' if expression else ''
log.logger.info('Collected {} items{}'.format(len(items), expr_string))
@attr.s(frozen=True)
-class LogExtraData(object):
+class LogExtraData:
config = attr.ib()
@property
@@ -90,7 +90,7 @@ def pytest_sessionfinish(session, exitstatus):
c[_test_status(test)] += 1
# Prepend a total to the summary list
results = ['total: {}'.format(sum(c.values()))] + [
- '{}: {}'.format(k, v) for k, v in c.items()]
+ f'{k}: {v}' for k, v in c.items()]
# Then join it with commas
summary = ', '.join(results)
log.logger.info(log.format_marker('Finished test run', mark='='))
diff --git a/cfme/fixtures/multi_region.py b/cfme/fixtures/multi_region.py
index b69faa84eb..8bd00dcadb 100644
--- a/cfme/fixtures/multi_region.py
+++ b/cfme/fixtures/multi_region.py
@@ -3,7 +3,7 @@
@attr.s
-class ApplianceCluster(object):
+class ApplianceCluster:
"""
Holder for Multi-Region appliances setup.
Appliance from global region is stored in global_appliance.
diff --git a/cfme/fixtures/nelson.py b/cfme/fixtures/nelson.py
index 338bbcac8f..a749484f72 100644
--- a/cfme/fixtures/nelson.py
+++ b/cfme/fixtures/nelson.py
@@ -32,7 +32,7 @@ def pytest_collection_modifyitems(items):
item_param = re.findall(r'\.*(\[.*\])', item_name)
if item_param:
item_name = item_name.replace(item_param[0], '')
- node_name = '{}.{}'.format(item_class, item_name)
+ node_name = f'{item_class}.{item_name}'
output[node_name] = {}
docstring = getattr(item.function, '__doc__') or ''
output[node_name]['docstring'] = docstring.encode('utf-8')
@@ -65,7 +65,7 @@ def pytest_pycollect_makeitem(collector, name, obj):
pytest.mark.meta(from_docs=metadata)(obj)
if metadata:
test_path = get_rel_path(collector.fspath)
- logger.debug('Parsed docstring metadata on {} in {}'.format(name, test_path))
+ logger.debug(f'Parsed docstring metadata on {name} in {test_path}')
logger.trace('{} doc metadata: {}'.format(name, str(metadata)))
@@ -88,10 +88,10 @@ class GoogleDocstring(docstring.GoogleDocstring):
"""Custom version of napoleon's GoogleDocstring that adds some special cases"""
def __init__(self, *args, **kwargs):
self.metadata = {}
- super(GoogleDocstring, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self._sections['usage'] = self._parse_usage_section
self._sections['metadata'] = self._parse_metadata_section
- super(GoogleDocstring, self)._parse()
+ super()._parse()
def _parse(self):
pass
diff --git a/cfme/fixtures/nuage.py b/cfme/fixtures/nuage.py
index d333f74e74..5d40403b94 100644
--- a/cfme/fixtures/nuage.py
+++ b/cfme/fixtures/nuage.py
@@ -72,7 +72,7 @@ def with_nuage_sandbox_modscope(appliance, setup_provider_modscope, provider):
tenant = (appliance.db.client.session
.query(tenants_table.name, tenants_table.ems_ref)
.filter(tenants_table.ems_ref == enterprise.id).first())
- assert tenant is not None, 'Nuage sandbox tenant inventory missing: {}'.format(enterprise.name)
+ assert tenant is not None, f'Nuage sandbox tenant inventory missing: {enterprise.name}'
# Let integration test do whatever it needs to do.
yield sandbox
diff --git a/cfme/fixtures/parallelizer/__init__.py b/cfme/fixtures/parallelizer/__init__.py
index 2127881e16..a7f7902968 100644
--- a/cfme/fixtures/parallelizer/__init__.py
+++ b/cfme/fixtures/parallelizer/__init__.py
@@ -104,7 +104,7 @@ def handle_end_session(signal, frame):
@attr.s(hash=False)
-class SlaveDetail(object):
+class SlaveDetail:
slaveid_generator = (f'slave{i:02d}'.encode('ascii') for i in count())
@@ -140,7 +140,7 @@ def poll(self):
return self.process.poll()
-class ParallelSession(object):
+class ParallelSession:
def __init__(self, config, appliances):
self.config = config
self.session = None
@@ -505,8 +505,7 @@ def pytest_sessionfinish(self):
self.zmq_ctx.destroy()
def _test_item_generator(self):
- for tests in chain(self._serial_item_generator(), self._modscope_item_generator()):
- yield tests
+ yield from chain(self._serial_item_generator(), self._modscope_item_generator())
def _serial_item_generator(self):
# yields list of tests that will run on a single collection
@@ -641,7 +640,7 @@ def report_collection_diff(slaveid, from_collection, to_collection):
return f'{slaveid} diff:\n{deep}\n'
-class TerminalDistReporter(object):
+class TerminalDistReporter:
"""Terminal Reporter for Distributed Testing
trdist reporter exists to make sure we get good distributed logging during the runtest loop,
diff --git a/cfme/fixtures/parallelizer/remote.py b/cfme/fixtures/parallelizer/remote.py
index 10c2dd49ee..c34e32d0db 100644
--- a/cfme/fixtures/parallelizer/remote.py
+++ b/cfme/fixtures/parallelizer/remote.py
@@ -14,7 +14,7 @@
SLAVEID = None
-class SlaveManager(object):
+class SlaveManager:
"""SlaveManager which coordinates with the master process for parallel testing"""
def __init__(self, config, slaveid, zmq_endpoint):
self.config = config
diff --git a/cfme/fixtures/provider.py b/cfme/fixtures/provider.py
index 54603ec02b..14dbe8ae35 100644
--- a/cfme/fixtures/provider.py
+++ b/cfme/fixtures/provider.py
@@ -127,7 +127,7 @@ def _setup_provider_verbose(request, provider, appliance=None):
logger.info('waiting for provider %r to disappear', p.key)
p.wait_for_delete()
store.terminalreporter.write_line(
- "Trying to set up provider {}\n".format(provider.key), green=True)
+ f"Trying to set up provider {provider.key}\n", green=True)
enable_provider_regions(provider)
provider.setup()
return True
@@ -159,12 +159,12 @@ def setup_or_skip(request, provider, appliance=None):
of problematic providers and won't be used by any test until the end of the test run.
"""
if provider in _problematic_providers:
- skip_msg = "Provider {} had been marked as problematic".format(provider.key)
+ skip_msg = f"Provider {provider.key} had been marked as problematic"
_artifactor_skip_providers(request, [provider], skip_msg)
if not _setup_provider_verbose(request, provider, appliance):
_artifactor_skip_providers(
- request, [provider], "Unable to setup provider {}".format(provider.key))
+ request, [provider], f"Unable to setup provider {provider.key}")
def setup_one_or_skip(request, filters=None, use_global_filters=True):
@@ -237,7 +237,7 @@ def _setup_provider(request):
""" Sets up one of the matching providers """
return setup_one_by_class_or_skip(request, prov_class)
return _setup_provider
- fn_name = '{}_provider'.format(prov_type)
+ fn_name = f'{prov_type}_provider'
globals()[fn_name] = gen_setup_provider(prov_class)
def gen_has_no_providers(prov_class):
@@ -246,7 +246,7 @@ def _has_no_providers():
""" Clears all providers of given class from the appliance """
prov_class.clear_providers()
return _has_no_providers
- fn_name = 'has_no_{}_providers'.format(prov_type)
+ fn_name = f'has_no_{prov_type}_providers'
globals()[fn_name] = gen_has_no_providers(prov_class)
diff --git a/cfme/fixtures/pytest_store.py b/cfme/fixtures/pytest_store.py
index 12f1b5980a..c49a65a6c9 100644
--- a/cfme/fixtures/pytest_store.py
+++ b/cfme/fixtures/pytest_store.py
@@ -43,7 +43,7 @@ def __init__(self, config=None, file=None):
self.currentfspath = None
-class Store(object):
+class Store:
"""pytest object store
If a property isn't available for any reason (including being accessed outside of a pytest run),
diff --git a/cfme/fixtures/qa_contact.py b/cfme/fixtures/qa_contact.py
index 9eb620bf5d..58fd97df89 100644
--- a/cfme/fixtures/qa_contact.py
+++ b/cfme/fixtures/qa_contact.py
@@ -13,7 +13,7 @@ def dig_code(node):
lineno = code_data[1]
offset = len(code_data[0])
filename = inspect.getfile(node.function)
- line_param = '-L {},+{}'.format(lineno, offset)
+ line_param = f'-L {lineno},+{offset}'
cmd_params = ['git', 'blame', line_param, filename, '--show-email']
proc = subprocess.run(cmd_params, stdin=subprocess.DEVNULL, capture_output=True)
diff --git a/cfme/fixtures/rbac.py b/cfme/fixtures/rbac.py
index 2d7f50dd7a..de14abecf5 100644
--- a/cfme/fixtures/rbac.py
+++ b/cfme/fixtures/rbac.py
@@ -172,7 +172,7 @@ def pytest_pyfunc_call(pyfuncitem):
if 'rbac_role' in pyfuncitem.fixturenames:
user = pyfuncitem._request.getfixturevalue('rbac_role')
really_logout()
- logger.info("setting user to {}".format(user))
+ logger.info(f"setting user to {user}")
user_obj = current_appliance.collections.users.instantiate(
username=conf.credentials[user]['username'],
password=conf.credentials[user]['password']
diff --git a/cfme/fixtures/rdb.py b/cfme/fixtures/rdb.py
index 9825b3d474..1f3970288f 100644
--- a/cfme/fixtures/rdb.py
+++ b/cfme/fixtures/rdb.py
@@ -130,7 +130,7 @@ def set_trace(self, *args, **kwargs):
"""
host, port = self.sock.getsockname()
- endpoint = 'host {} port {}'.format(store.my_ip_address, port)
+ endpoint = f'host {store.my_ip_address} port {port}'
recipients = kwargs.pop('recipients', None)
if recipients:
@@ -148,10 +148,10 @@ def set_trace(self, *args, **kwargs):
msg['Subject'] = subject
msg['To'] = ', '.join(recipients)
smtp.sendmail('rdb-breakpoint@redhat.com', recipients, msg.as_string())
- except socket.error:
+ except OSError:
logger.critical("Couldn't send email")
- msg = 'Remote debugger listening on {}'.format(endpoint)
+ msg = f'Remote debugger listening on {endpoint}'
logger.critical(msg)
write_line(msg, red=True, bold=True)
self.sock.listen(1)
@@ -160,7 +160,7 @@ def set_trace(self, *args, **kwargs):
Pdb.__init__(self, completekey='tab', stdin=client_fh, stdout=client_fh)
sys.stdout = sys.stdin = client_fh
Pdb.set_trace(self, *args, **kwargs)
- msg = 'Debugger on {} shut down'.format(endpoint)
+ msg = f'Debugger on {endpoint} shut down'
logger.critical(msg)
write_line(msg, green=True, bold=True)
diff --git a/cfme/fixtures/sauce.py b/cfme/fixtures/sauce.py
index b0bccfece6..dbbc3bd84e 100644
--- a/cfme/fixtures/sauce.py
+++ b/cfme/fixtures/sauce.py
@@ -6,5 +6,5 @@ def pytest_runtest_teardown(item, nextitem):
if item.config.getoption('sauce'):
from cfme.utils.browser import ensure_browser_open, quit, browser
ensure_browser_open()
- browser().execute_script("sauce:job-name={}".format(item.name))
+ browser().execute_script(f"sauce:job-name={item.name}")
quit()
diff --git a/cfme/fixtures/screenshots.py b/cfme/fixtures/screenshots.py
index 59f5acbc6b..271435a80f 100644
--- a/cfme/fixtures/screenshots.py
+++ b/cfme/fixtures/screenshots.py
@@ -24,20 +24,20 @@ def take_screenshot(request):
item = request.node
def _take_screenshot(name):
- logger.info("Taking a screenshot named {}".format(name))
+ logger.info(f"Taking a screenshot named {name}")
ss, ss_error = take_browser_screenshot()
g_id = fauxfactory.gen_alpha(length=6)
if ss:
fire_art_test_hook(
item, 'filedump',
- description="Screenshot {}".format(name), file_type="screenshot", mode="wb",
+ description=f"Screenshot {name}", file_type="screenshot", mode="wb",
contents_base64=True, contents=ss, display_glyph="camera",
- group_id="fix-screenshot-{}".format(g_id), slaveid=store.slaveid)
+ group_id=f"fix-screenshot-{g_id}", slaveid=store.slaveid)
if ss_error:
fire_art_test_hook(
item, 'filedump',
- description="Screenshot error {}".format(name), mode="w", contents_base64=False,
+ description=f"Screenshot error {name}", mode="w", contents_base64=False,
contents=ss_error, display_type="danger",
- group_id="fix-screenshot-{}".format(g_id), slaveid=store.slaveid)
+ group_id=f"fix-screenshot-{g_id}", slaveid=store.slaveid)
return _take_screenshot
diff --git a/cfme/fixtures/service_fixtures.py b/cfme/fixtures/service_fixtures.py
index 0956edd444..96155d7220 100644
--- a/cfme/fixtures/service_fixtures.py
+++ b/cfme/fixtures/service_fixtures.py
@@ -84,7 +84,7 @@ def create_catalog_item(appliance, provider, provisioning, dialog, catalog,
('provision_type', 'template', 'host', 'datastore', 'iso_file', 'vlan'))
if console_test:
template = _get_template(provider, 'console_template').name
- logger.info("Console template name : {}".format(template))
+ logger.info(f"Console template name : {template}")
item_name = dialog.label
if provider.one_of(InfraProvider):
catalog_name = template
@@ -196,7 +196,7 @@ def service_vm(appliance, provider, catalog_item):
collection = provider.appliance.provider_based_collection(provider)
vm_name = "{}0001".format(catalog_item.prov_data["catalog"]["vm_name"])
- vm = collection.instantiate("{}".format(vm_name), provider)
+ vm = collection.instantiate(f"{vm_name}", provider)
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
provision_request = service_catalogs.order()
@@ -204,7 +204,7 @@ def service_vm(appliance, provider, catalog_item):
provision_request.wait_for_request()
if not provision_request.is_finished():
- pytest.skip("Failed to provision service '{}'".format(catalog_item.name))
+ pytest.skip(f"Failed to provision service '{catalog_item.name}'")
service = MyService(appliance, catalog_item.name, vm_name=vm_name)
yield service, vm
@@ -228,7 +228,7 @@ def generic_service(appliance, generic_catalog_item):
provision_request.wait_for_request()
if not provision_request.is_finished():
- pytest.skip("Failed to provision service '{}'".format(generic_catalog_item.name))
+ pytest.skip(f"Failed to provision service '{generic_catalog_item.name}'")
service = MyService(appliance, generic_catalog_item.dialog.label)
yield service, generic_catalog_item
diff --git a/cfme/fixtures/soft_assert.py b/cfme/fixtures/soft_assert.py
index 0e79393ce3..5a7b2600d2 100644
--- a/cfme/fixtures/soft_assert.py
+++ b/cfme/fixtures/soft_assert.py
@@ -82,7 +82,7 @@ class SoftAssertionError(AssertionError):
"""
def __init__(self, failed_assertions):
self.failed_assertions = failed_assertions
- super(SoftAssertionError, self).__init__(str(self))
+ super().__init__(str(self))
def __str__(self):
failmsgs = ['']
@@ -199,8 +199,8 @@ def _annotate_failure(fail_message=''):
fail_message = str(frameinfo.code_context[0]).strip()
filename = get_rel_path(frameinfo.filename)
- path = '{}:{!r}'.format(filename, frameinfo.lineno)
- return '{} ({})'.format(fail_message, path)
+ path = f'{filename}:{frameinfo.lineno!r}'
+ return f'{fail_message} ({path})'
@pytest.fixture
diff --git a/cfme/fixtures/tccheck.py b/cfme/fixtures/tccheck.py
index b7fab75a08..926264bf34 100644
--- a/cfme/fixtures/tccheck.py
+++ b/cfme/fixtures/tccheck.py
@@ -36,15 +36,15 @@ def check_tier(item):
strings = []
tier = item.get_closest_marker('tier')
if tier is None:
- strings.append('[TCV-E] MISSING TIER: {}'.format(item.nodeid))
+ strings.append(f'[TCV-E] MISSING TIER: {item.nodeid}')
else:
try:
tier = tier.args[0]
except IndexError:
- strings.append('[TCV-E] BAD TIER SPECIFICATION: {}'.format(item.nodeid))
+ strings.append(f'[TCV-E] BAD TIER SPECIFICATION: {item.nodeid}')
else:
if not 1 <= tier <= 3:
- strings.append('[TCV-E] BAD TIER NUMBER ({}): {}'.format(tier, item.nodeid))
+ strings.append(f'[TCV-E] BAD TIER NUMBER ({tier}): {item.nodeid}')
return strings
@@ -52,16 +52,16 @@ def check_requirement(item, available_requirements):
strings = []
requirement = item.get_closest_marker('requirement')
if requirement is None:
- strings.append('[TCV-E] MISSING REQUIREMENT: {}'.format(item.nodeid))
+ strings.append(f'[TCV-E] MISSING REQUIREMENT: {item.nodeid}')
else:
try:
requirement = requirement.args[0]
except IndexError:
- strings.append('[TCV-E] BAD REQUIREMENT SPECIFICATION: {}'.format(item.nodeid))
+ strings.append(f'[TCV-E] BAD REQUIREMENT SPECIFICATION: {item.nodeid}')
else:
if requirement not in available_requirements:
strings.append(
- '[TCV-E] BAD REQUIREMENT STRING ({}): {}'.format(requirement, item.nodeid))
+ f'[TCV-E] BAD REQUIREMENT STRING ({requirement}): {item.nodeid}')
return strings
diff --git a/cfme/fixtures/templateloader.py b/cfme/fixtures/templateloader.py
index ddae3b3deb..989a869d6e 100644
--- a/cfme/fixtures/templateloader.py
+++ b/cfme/fixtures/templateloader.py
@@ -45,13 +45,13 @@ def pytest_configure(config):
provider_templates = trackerbot.provider_templates(trackerbot.api())
for provider in list_provider_keys():
TEMPLATES[provider] = provider_templates.get(provider, [])
- config.cache.set('miq-trackerbot/{}'.format(provider), TEMPLATES[provider])
+ config.cache.set(f'miq-trackerbot/{provider}', TEMPLATES[provider])
count += len(TEMPLATES[provider])
else:
store.terminalreporter.line("Using templates from cache...", green=True)
provider_templates = None
for provider in list_provider_keys():
- templates = config.cache.get('miq-trackerbot/{}'.format(provider), None)
+ templates = config.cache.get(f'miq-trackerbot/{provider}', None)
if templates is None:
store.terminalreporter.line(
"Loading templates for {} from source as not in cache".format(
@@ -59,7 +59,7 @@ def pytest_configure(config):
if not provider_templates:
provider_templates = trackerbot.provider_templates(trackerbot.api())
templates = provider_templates.get(provider, [])
- config.cache.set('miq-trackerbot/{}'.format(provider), templates)
+ config.cache.set(f'miq-trackerbot/{provider}', templates)
count += len(templates)
TEMPLATES[provider] = templates
- store.terminalreporter.line(" Loaded {} templates successfully!".format(count), green=True)
+ store.terminalreporter.line(f" Loaded {count} templates successfully!", green=True)
diff --git a/cfme/fixtures/templates.py b/cfme/fixtures/templates.py
index e055a56f31..899d52e7f6 100644
--- a/cfme/fixtures/templates.py
+++ b/cfme/fixtures/templates.py
@@ -36,7 +36,7 @@ def template(template_location, provider):
logger.info("Cannot apply %r to %r in the template specification, ignoring.", field, o)
else:
if not isinstance(o, str):
- raise ValueError("{!r} is not a string! (for template)".format(o))
+ raise ValueError(f"{o!r} is not a string! (for template)")
if not TEMPLATES:
# There is nothing in TEMPLATES, that means no trackerbot URL and no data pulled.
# This should normally not constitute an issue so continue.
@@ -70,7 +70,7 @@ def _get_template(provider, template_type_name):
template_type = provider.data.templates.get(template_type_name)
except (AttributeError, KeyError):
logger.error("Wanted template %s on %s but it is not there!", template, provider.key)
- pytest.skip('No {} for provider {}'.format(template_type_name, provider.key))
+ pytest.skip(f'No {template_type_name} for provider {provider.key}')
if not isinstance(template_type, Mapping):
pytest.skip('Template mapping is incorrect, {} on provider {}'
.format(template_type_name, provider.key))
diff --git a/cfme/fixtures/ui_coverage.py b/cfme/fixtures/ui_coverage.py
index 8ea33efdfb..e47ca03b20 100644
--- a/cfme/fixtures/ui_coverage.py
+++ b/cfme/fixtures/ui_coverage.py
@@ -111,11 +111,11 @@ def manager():
# you probably don't want to instantiate this manually
# instead, use the "manager" function above
-class CoverageManager(object):
+class CoverageManager:
def __init__(self, ipappliance):
self.ipapp = ipappliance
if store.slave_manager:
- sublogger_name = '{} coverage'.format(store.slave_manager.slaveid)
+ sublogger_name = f'{store.slave_manager.slaveid} coverage'
else:
sublogger_name = 'coverage'
self.log = create_sublogger(sublogger_name)
@@ -132,7 +132,7 @@ def collection_appliance(self):
def print_message(self, message):
self.log.info(message)
- message = 'coverage: {}'.format(message)
+ message = f'coverage: {message}'
if store.slave_manager:
store.slave_manager.message(message)
elif store.parallel_session:
@@ -181,7 +181,7 @@ def _gem_install():
# bundle install for old downstream and upstream builds
def _bundle_install():
self.ipapp.ssh_client.run_command('yum -y install git')
- self.ipapp.ssh_client.run_command('cd {}; bundle'.format(rails_root))
+ self.ipapp.ssh_client.run_command(f'cd {rails_root}; bundle')
VersionPicker({
LOWEST: _gem_install,
@@ -190,14 +190,14 @@ def _bundle_install():
def _install_coverage_hook(self):
# Clean appliance coverage dir
- self.ipapp.ssh_client.run_command('rm -rf {}'.format(appliance_coverage_root.strpath))
+ self.ipapp.ssh_client.run_command(f'rm -rf {appliance_coverage_root.strpath}')
# Put the coverage hook in the miq config path
self.ipapp.ssh_client.put_file(
coverage_hook.strpath,
rails_root.join('config', coverage_hook_file_name).strpath
)
result = self.ipapp.ssh_client.run_command(
- 'cd {}; [ -e lib/code_coverage.rb ]'.format(rails_root)
+ f'cd {rails_root}; [ -e lib/code_coverage.rb ]'
)
return result.success
@@ -206,7 +206,7 @@ def _collect_reports(self):
self.ipapp.ssh_client.run_command('systemctl stop evmserverd')
# collect back to the collection appliance if parallelized
if store.current_appliance != self.collection_appliance:
- self.print_message('sending reports to {}'.format(self.collection_appliance.hostname))
+ self.print_message(f'sending reports to {self.collection_appliance.hostname}')
result = self.ipapp.ssh_client.run_command(
'sshpass -p {passwd} '
'scp -o StrictHostKeyChecking=no '
@@ -246,7 +246,7 @@ def _retrieve_merged_reports(self):
'-C', coverage_output_dir.strpath]).wait()
-class UiCoveragePlugin(object):
+class UiCoveragePlugin:
def pytest_configure(self, config):
if config.getoption('--help'):
return
diff --git a/cfme/fixtures/utility_vm.py b/cfme/fixtures/utility_vm.py
index 854fa76379..e03ec03e3b 100644
--- a/cfme/fixtures/utility_vm.py
+++ b/cfme/fixtures/utility_vm.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
""" The utility_vm is a vm that is meant to serve various services that the
tests are requiring.
diff --git a/cfme/fixtures/v2v_fixtures.py b/cfme/fixtures/v2v_fixtures.py
index be57dc54de..01aa824f9b 100644
--- a/cfme/fixtures/v2v_fixtures.py
+++ b/cfme/fixtures/v2v_fixtures.py
@@ -80,7 +80,7 @@ def v2v_provider_setup(request, appliance, source_provider, provider):
if BZ(1753364, forced_streams=['5.11']).blocks:
_start_event_workers_for_osp(appliance, osp_provider)
else:
- pytest.skip("Provider {} is not a valid provider for v2v tests".format(provider.name))
+ pytest.skip(f"Provider {provider.name} is not a valid provider for v2v tests")
v2v_providers = V2vProviders(vmware_provider=vmware_provider,
rhv_provider=rhv_provider,
osp_provider=osp_provider)
@@ -208,7 +208,7 @@ def vddk_url():
url = vddk_urls.get(vddk_version)
if url is None:
- pytest.skip("VDDK {} is unavailable, skipping test".format(vddk_version))
+ pytest.skip(f"VDDK {vddk_version} is unavailable, skipping test")
return url
@@ -275,7 +275,7 @@ def set_conversion_host_api(
"'MiqTask.delete_all; ConversionHost.delete_all'")
if not delete_hosts.success:
pytest.skip(
- "Failed to delete all conversion hosts: {}".format(delete_hosts.output))
+ f"Failed to delete all conversion hosts: {delete_hosts.output}")
conversion_data = get_conversion_data(appliance, target_provider)
if transformation_method == "SSH":
@@ -317,7 +317,7 @@ def delete_conversion_hosts(appliance):
"'MiqTask.delete_all; ConversionHost.delete_all'")
if not delete_hosts.success:
pytest.skip(
- "Failed to delete all conversion hosts: {}".format(delete_hosts.output))
+ f"Failed to delete all conversion hosts: {delete_hosts.output}")
def cleanup_target(provider, migrated_vm):
@@ -401,7 +401,7 @@ def infra_mapping_default_data(source_provider, provider):
"5.10": "rhv" if provider.one_of(RHEVMProvider) else "osp"}).pick()
infra_mapping_data = {
"name": fauxfactory.gen_alphanumeric(15, start="infra_map_"),
- "description": "migration with vmware to {}".format(plan_type),
+ "description": f"migration with vmware to {plan_type}",
"plan_type": plan_type,
"clusters": [component_generator("clusters", source_provider, provider)],
"datastores": [component_generator(
@@ -681,5 +681,5 @@ def component_generator(selector, source_provider, provider, source_type=None, t
skip_test = not (sources and targets and component)
if skip_test:
- pytest.skip("No data for source or target {} in providers.".format(selector))
+ pytest.skip(f"No data for source or target {selector} in providers.")
return component
diff --git a/cfme/fixtures/version_info.py b/cfme/fixtures/version_info.py
index 206177e04c..aa504f0c1d 100644
--- a/cfme/fixtures/version_info.py
+++ b/cfme/fixtures/version_info.py
@@ -34,7 +34,7 @@ def get_system_versions(ssh_client):
system_dict['operating_system'] = operating_system
timediff = time.time() - starttime
- logger.info('Got version info in: {}'.format(timediff))
+ logger.info(f'Got version info in: {timediff}')
return system_dict
@@ -58,7 +58,7 @@ def get_process_versions(ssh_client):
process_dict['httpd'] = httpdv
timediff = time.time() - starttime
- logger.info('Got process version info in: {}'.format(timediff))
+ logger.info(f'Got process version info in: {timediff}')
return process_dict
@@ -78,7 +78,7 @@ def get_gem_versions(ssh_client):
gem_dict[name] = ver
timediff = time.time() - starttime
- logger.info('Got version info in: {}'.format(timediff))
+ logger.info(f'Got version info in: {timediff}')
return gem_dict
@@ -90,7 +90,7 @@ def get_rpm_versions(ssh_client):
"rpm -qa --queryformat='%{N}, %{V}-%{R}\n' | sort")[1]).split('\n') # noqa
timediff = time.time() - starttime
- logger.info('Got version info in: {}'.format(timediff))
+ logger.info(f'Got version info in: {timediff}')
return rpm_list
@@ -104,7 +104,7 @@ def generate_system_file(ssh_client, directory):
csv_file.write('{}, {} \n'.format(key, system_info[key]))
timediff = time.time() - starttime
- logger.info('Generated system file in: {}'.format(timediff))
+ logger.info(f'Generated system file in: {timediff}')
def generate_processes_file(ssh_client, directory):
@@ -117,7 +117,7 @@ def generate_processes_file(ssh_client, directory):
csv_file.write('{}, {} \n'.format(key, process_info[key]))
timediff = time.time() - starttime
- logger.info('Generated processes file in: {}'.format(timediff))
+ logger.info(f'Generated processes file in: {timediff}')
def generate_gems_file(ssh_client, directory):
@@ -130,7 +130,7 @@ def generate_gems_file(ssh_client, directory):
csv_file.write('{}, {} \n'.format(key, gem_info[key]))
timediff = time.time() - starttime
- logger.info('Generated gems file in: {}'.format(timediff))
+ logger.info(f'Generated gems file in: {timediff}')
def generate_rpms_file(ssh_client, directory):
@@ -140,10 +140,10 @@ def generate_rpms_file(ssh_client, directory):
file_name = str(os.path.join(directory, 'rpms.csv'))
with open(file_name, 'w') as csv_file:
for key in rpm_info:
- csv_file.write('{}\n'.format(key))
+ csv_file.write(f'{key}\n')
timediff = time.time() - starttime
- logger.info('Generated rpms file in: {}'.format(timediff))
+ logger.info(f'Generated rpms file in: {timediff}')
@pytest.fixture(scope='session')
@@ -154,7 +154,7 @@ def generate_version_files():
relative_path = os.path.relpath(str(results_path), str(os.getcwd()))
# avoid importing outside perf testing
from cfme.utils.smem_memory_monitor import test_ts
- relative_string = relative_path + '/{}*'.format(test_ts)
+ relative_string = relative_path + f'/{test_ts}*'
directory_list = glob.glob(relative_string)
for directory in directory_list:
@@ -169,5 +169,5 @@ def generate_version_files():
generate_rpms_file(ssh_client, module_path)
timediff = time.time() - starttime
- logger.info('Generated all version files in {}'.format(timediff))
+ logger.info(f'Generated all version files in {timediff}')
ssh_client.close()
diff --git a/cfme/fixtures/vm.py b/cfme/fixtures/vm.py
index cc0d3efcaa..7820851af7 100644
--- a/cfme/fixtures/vm.py
+++ b/cfme/fixtures/vm.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import fauxfactory
import pytest
from pytest_polarion_collect.utils import get_parsed_docstring
diff --git a/cfme/fixtures/xunit_tools.py b/cfme/fixtures/xunit_tools.py
index c5e129336a..4fd4ad2819 100644
--- a/cfme/fixtures/xunit_tools.py
+++ b/cfme/fixtures/xunit_tools.py
@@ -145,7 +145,7 @@ def get_testcase_data(name, tests, processed_test, item, legacy=False):
manual = item.get_closest_marker('manual')
if not manual:
# The master here should probably link the latest "commit" eventually
- automation_script = 'http://github.com/{0}/{1}/blob/master/{2}#L{3}'.format(
+ automation_script = 'http://github.com/{}/{}/blob/master/{}#L{}'.format(
xunit['gh_owner'],
xunit['gh_repo'],
item.location[0],
@@ -156,11 +156,11 @@ def get_testcase_data(name, tests, processed_test, item, legacy=False):
# Description with timestamp and link to test case source.
# The timestamp will not be visible in Polarion, but will cause Polarion
# to update the "Updated" field even when there's no other change.
- description = '{0}
Test Source'.format(
+ description = '{}
Test Source'.format(
description, timestamp, automation_script)
else:
custom_fields['caseautomation'] = "manualonly"
- description = '{}'.format(description)
+ description = f'{description}'
processed_test.append(name)
tests.append(dict(
@@ -190,7 +190,7 @@ def testresult_record(test_name, parameters=None, result=None):
properties.append(testcase_id)
for param, value in parameters.items():
param_el = etree.Element(
- 'property', name="polarion-parameter-{}".format(param), value=value)
+ 'property', name=f"polarion-parameter-{param}", value=value)
properties.append(param_el)
testcase.append(properties)
return testcase
@@ -236,7 +236,7 @@ def testrun_gen(tests, filename, config, collectonly=True):
if prop_value is None:
continue
prop_el = etree.Element(
- 'property', name="polarion-{}".format(prop_name), value=str(prop_value))
+ 'property', name=f"polarion-{prop_name}", value=str(prop_value))
properties.append(prop_el)
testsuites.append(properties)
testsuites.append(testsuite)
@@ -315,7 +315,7 @@ def gen_duplicates_log(items):
with open('duplicates.log', 'w') as f:
for test in sorted(duplicates):
- f.write('{}\n'.format(test))
+ f.write(f'{test}\n')
@pytest.hookimpl(trylast=True)
diff --git a/cfme/generic_objects/definition/associations.py b/cfme/generic_objects/definition/associations.py
index 7d90b3225b..250ef0fe2a 100644
--- a/cfme/generic_objects/definition/associations.py
+++ b/cfme/generic_objects/definition/associations.py
@@ -8,7 +8,7 @@
def get_rest_resource(appliance, association_type, resource):
mapping = _ASSOCIATION_TYPES_MAPPING.get(association_type)
if not mapping:
- raise NotImplementedError('Mapping is not implemented for `{}`.'.format(association_type))
+ raise NotImplementedError(f'Mapping is not implemented for `{association_type}`.')
rest_collection = getattr(appliance.rest_api.collections, mapping['rest_collection'])
return rest_collection.find_by(name=resource.name)
diff --git a/cfme/generic_objects/definition/button_groups.py b/cfme/generic_objects/definition/button_groups.py
index 91ed2e3303..dee3113b4a 100644
--- a/cfme/generic_objects/definition/button_groups.py
+++ b/cfme/generic_objects/definition/button_groups.py
@@ -330,7 +330,7 @@ class ButtonGroupDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.accordion.classes.tree.click_path(
'All Generic Object Classes', self.obj.parent.parent.name, 'Actions',
- '{} (Group)'.format(self.obj.name))
+ f'{self.obj.name} (Group)')
@navigator.register(GenericObjectButtonGroup, "Edit")
diff --git a/cfme/infrastructure/cluster.py b/cfme/infrastructure/cluster.py
index aa0795f5b5..d23565ac5c 100644
--- a/cfme/infrastructure/cluster.py
+++ b/cfme/infrastructure/cluster.py
@@ -261,7 +261,7 @@ def run_smartstate_analysis(self, wait_for_task_result=False):
)
if wait_for_task_result:
task = self.appliance.collections.tasks.instantiate(
- name="SmartState Analysis for [{}]".format(self.name), tab='MyOtherTasks')
+ name=f"SmartState Analysis for [{self.name}]", tab='MyOtherTasks')
task.wait_for_finished()
return task
diff --git a/cfme/infrastructure/config_management/__init__.py b/cfme/infrastructure/config_management/__init__.py
index ef300c7f1e..74e128450d 100644
--- a/cfme/infrastructure/config_management/__init__.py
+++ b/cfme/infrastructure/config_management/__init__.py
@@ -421,7 +421,7 @@ def rest_api_entity(self):
return RestEntity(self.appliance.rest_api.collections.providers, data={
"href": self.appliance.url_path(
- "/api/providers/{}?provider_class=provider".format(provider_id)
+ f"/api/providers/{provider_id}?provider_class=provider"
)
})
@@ -436,7 +436,7 @@ def create_rest(self):
include_ssl = True
payload = {
- "type": "ManageIQ::Providers::{}::Provider".format(config_type),
+ "type": f"ManageIQ::Providers::{config_type}::Provider",
"url": self.url,
"name": self.name,
"credentials": {
@@ -456,12 +456,12 @@ def create_rest(self):
**payload
)
except APIException as err:
- raise AssertionError("Provider wasn't added: {}".format(err))
+ raise AssertionError(f"Provider wasn't added: {err}")
response = self.appliance.rest_api.response
if not response:
raise AssertionError(
- "Provider wasn't added, status code {}".format(response.status_code)
+ f"Provider wasn't added, status code {response.status_code}"
)
assert_response(self.appliance)
@@ -472,12 +472,12 @@ def delete_rest(self):
try:
self.rest_api_entity.action.delete()
except APIException as err:
- raise AssertionError("Provider wasn't deleted: {}".format(err))
+ raise AssertionError(f"Provider wasn't deleted: {err}")
response = self.appliance.rest_api.response
if not response:
raise AssertionError(
- "Provider wasn't deleted, status code {}".format(response.status_code)
+ f"Provider wasn't deleted, status code {response.status_code}"
)
def refresh_relationships(self, cancel=False):
diff --git a/cfme/infrastructure/config_management/ansible_tower.py b/cfme/infrastructure/config_management/ansible_tower.py
index ccd7ce0f1f..9eac167e9e 100644
--- a/cfme/infrastructure/config_management/ansible_tower.py
+++ b/cfme/infrastructure/config_management/ansible_tower.py
@@ -85,7 +85,7 @@ class AnsibleTowerProvider(ConfigManagerProvider):
@property
def ui_name(self):
"""Return the name used in the UI"""
- return '{} Automation Manager'.format(self.name)
+ return f'{self.name} Automation Manager'
@classmethod
def from_config(cls, prov_config, prov_key, appliance=None):
diff --git a/cfme/infrastructure/config_management/config_profiles.py b/cfme/infrastructure/config_management/config_profiles.py
index 4a0d57ba81..35785b60b6 100644
--- a/cfme/infrastructure/config_management/config_profiles.py
+++ b/cfme/infrastructure/config_management/config_profiles.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import attr
from cfme.infrastructure.config_management.config_systems import ConfigSystemsCollection
diff --git a/cfme/infrastructure/config_management/config_systems/__init__.py b/cfme/infrastructure/config_management/config_systems/__init__.py
index 9cebdf81b9..737a62327b 100644
--- a/cfme/infrastructure/config_management/config_systems/__init__.py
+++ b/cfme/infrastructure/config_management/config_systems/__init__.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import attr
from cfme.common import Taggable
diff --git a/cfme/infrastructure/config_management/satellite.py b/cfme/infrastructure/config_management/satellite.py
index db51507e9f..0af3cd0e33 100644
--- a/cfme/infrastructure/config_management/satellite.py
+++ b/cfme/infrastructure/config_management/satellite.py
@@ -87,7 +87,7 @@ class SatelliteProvider(ConfigManagerProvider):
@property
def ui_name(self):
"""Return the name used in the UI"""
- return '{} Configuration Manager'.format(self.name)
+ return f'{self.name} Configuration Manager'
@classmethod
def from_config(cls, prov_config, prov_key, appliance=None):
diff --git a/cfme/infrastructure/datastore.py b/cfme/infrastructure/datastore.py
index e7442124b1..1a5cba327a 100644
--- a/cfme/infrastructure/datastore.py
+++ b/cfme/infrastructure/datastore.py
@@ -68,7 +68,7 @@ class clusters(Accordion): # noqa
class DatastoreEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(DatastoreEntity, self).data
+ data_dict = super().data
try:
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
@@ -336,11 +336,10 @@ def run_smartstate_analysis(self, wait_for_task_result=False):
except TimedOutError:
raise MenuItemNotFound('Smart State analysis is disabled for this datastore')
view.toolbar.configuration.item_select('Perform SmartState Analysis', handle_alert=True)
- view.flash.assert_success_message(('"{}": scan successfully '
- 'initiated'.format(self.name)))
+ view.flash.assert_success_message(f'"{self.name}": scan successfully initiated')
if wait_for_task_result:
task = self.appliance.collections.tasks.instantiate(
- name="SmartState Analysis for [{}]".format(self.name), tab='MyOtherTasks')
+ name=f"SmartState Analysis for [{self.name}]", tab='MyOtherTasks')
task.wait_for_finished()
return task
@@ -407,7 +406,7 @@ def delete(self, *datastores):
view.entities.get_entity(name=datastore.name, surf_pages=True).ensure_checked()
checked_datastores.append(datastore)
except ItemNotFound:
- raise ValueError('Could not find datastore {} in the UI'.format(datastore.name))
+ raise ValueError(f'Could not find datastore {datastore.name} in the UI')
if set(datastores) == set(checked_datastores):
view.toolbar.configuration.item_select('Remove Datastores', handle_alert=True)
@@ -430,12 +429,12 @@ def run_smartstate_analysis(self, *datastores):
view.entities.get_entity(name=datastore.name, surf_pages=True).ensure_checked()
checked_datastores.append(datastore)
except ItemNotFound:
- raise ValueError('Could not find datastore {} in the UI'.format(datastore.name))
+ raise ValueError(f'Could not find datastore {datastore.name} in the UI')
view.toolbar.configuration.item_select('Perform SmartState Analysis', handle_alert=True)
for datastore in datastores:
view.flash.assert_success_message(
- '"{}": scan successfully initiated'.format(datastore.name))
+ f'"{datastore.name}": scan successfully initiated')
@navigator.register(DatastoreCollection, 'All')
diff --git a/cfme/infrastructure/deployment_roles.py b/cfme/infrastructure/deployment_roles.py
index dc56ec9f9e..94d5459d8f 100644
--- a/cfme/infrastructure/deployment_roles.py
+++ b/cfme/infrastructure/deployment_roles.py
@@ -228,7 +228,7 @@ def delete(self, *roles):
try:
view.entities.get_entity(name=role.name).ensure_checked()
except ItemNotFound:
- raise ItemNotFound("Deployment role {} not found".format(role.name))
+ raise ItemNotFound(f"Deployment role {role.name} not found")
view.toolbar.configuration.item_select('Remove selected items',
handle_alert=True)
@@ -265,7 +265,7 @@ def step(self, *args, **kwargs):
self.prerequisite_view.entities.get_entity(name=self.obj.name,
surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound("Deployment Role {} not found".format(self.obj.name))
+ raise ItemNotFound(f"Deployment Role {self.obj.name} not found")
@navigator.register(DeploymentRoles, 'AllForProvider')
@@ -290,4 +290,4 @@ def step(self, *args, **kwargs):
try:
self.prerequisite_view.entities.get_entity(name=self.obj.name).click()
except ItemNotFound:
- raise ItemNotFound("Deployment Role {} not found".format(self.obj.name))
+ raise ItemNotFound(f"Deployment Role {self.obj.name} not found")
diff --git a/cfme/infrastructure/host.py b/cfme/infrastructure/host.py
index 49942b9ab8..a5cbce0fcd 100644
--- a/cfme/infrastructure/host.py
+++ b/cfme/infrastructure/host.py
@@ -300,10 +300,10 @@ def run_smartstate_analysis(self, wait_for_task_result=False):
"""
view = navigate_to(self, "Details")
view.toolbar.configuration.item_select("Perform SmartState Analysis", handle_alert=True)
- view.flash.assert_success_message('"{}": Analysis successfully initiated'.format(self.name))
+ view.flash.assert_success_message(f'"{self.name}": Analysis successfully initiated')
if wait_for_task_result:
task = self.appliance.collections.tasks.instantiate(
- name="SmartState Analysis for '{}'".format(self.name), tab='MyOtherTasks')
+ name=f"SmartState Analysis for '{self.name}'", tab='MyOtherTasks')
task.wait_for_finished()
return task
@@ -316,7 +316,7 @@ def check_compliance(self, timeout=240):
view.flash.assert_no_error()
wait_for(
lambda: self.compliance_status != original_state,
- num_sec=timeout, delay=5, message="compliance of {} checked".format(self.name)
+ num_sec=timeout, delay=5, message=f"compliance of {self.name} checked"
)
@property
@@ -344,7 +344,7 @@ def is_compliant(self):
elif text.startswith("compliant"):
return True
else:
- raise ValueError("{} is not a known state for compliance".format(text))
+ raise ValueError(f"{text} is not a known state for compliance")
def equal_drift_results(self, drift_section, section, *indexes):
"""Compares drift analysis results of a row specified by it's title text.
@@ -491,7 +491,7 @@ def check_hosts(self, hosts):
view.entities.get_entity(name=host.name, surf_pages=True).ensure_checked()
checked_hosts.append(host)
except ItemNotFound:
- raise ItemNotFound('Could not find host {} in the UI'.format(host.name))
+ raise ItemNotFound(f'Could not find host {host.name} in the UI')
return view
def create(self, name, provider=None, credentials=None, hostname=None, ip_address=None,
@@ -527,7 +527,7 @@ def create(self, name, provider=None, credentials=None, hostname=None, ip_addres
view.endpoints.ipmi.validate_button.click()
if not cancel:
view.add_button.click()
- flash_message = 'Host / Node " {}" was added'.format(name)
+ flash_message = f'Host / Node " {name}" was added'
else:
view.cancel_button.click()
flash_message = "Add of new Host / Node was cancelled by the user"
@@ -559,7 +559,7 @@ def run_smartstate_analysis(self, *hosts):
view.toolbar.configuration.item_select('Perform SmartState Analysis', handle_alert=True)
for host in hosts:
view.flash.assert_success_message(
- '"{}": Analysis successfully initiated'.format(host.name))
+ f'"{host.name}": Analysis successfully initiated')
def delete(self, *hosts):
"""Deletes this host from CFME."""
diff --git a/cfme/infrastructure/openstack_node.py b/cfme/infrastructure/openstack_node.py
index b91a72b142..dcc4f63c0c 100644
--- a/cfme/infrastructure/openstack_node.py
+++ b/cfme/infrastructure/openstack_node.py
@@ -17,21 +17,21 @@ def toggle_maintenance_mode(self):
"""Initiate maintenance mode"""
view = navigate_to(self, 'Details')
view.toolbar.configuration.item_select('Toggle Maintenance Mode', handle_alert=True)
- exp_msg = '"{}": Toggle Maintenance successfully initiated'.format(self.name)
+ exp_msg = f'"{self.name}": Toggle Maintenance successfully initiated'
view.flash.assert_success_message(exp_msg)
def provide_node(self):
"""Provide node - make it available"""
view = navigate_to(self, 'Details')
view.toolbar.configuration.item_select('Provide Node', handle_alert=True)
- exp_msg = '"{}": Provide successfully initiated'.format(self.name)
+ exp_msg = f'"{self.name}": Provide successfully initiated'
view.flash.assert_success_message(exp_msg)
def run_introspection(self):
"""Run introspection"""
view = navigate_to(self, 'Details')
view.toolbar.configuration.item_select('Introspect Node', handle_alert=True)
- exp_msg = '"{}": Introspect successfully initiated'.format(self.name)
+ exp_msg = f'"{self.name}": Introspect successfully initiated'
view.flash.assert_success_message(exp_msg)
diff --git a/cfme/infrastructure/provider/__init__.py b/cfme/infrastructure/provider/__init__.py
index 0ad58d43e1..a2a800dc47 100644
--- a/cfme/infrastructure/provider/__init__.py
+++ b/cfme/infrastructure/provider/__init__.py
@@ -107,7 +107,7 @@ class InfraProvider(BaseProvider, CloudInfraProviderMixin, Pretty, Fillable,
_collections = {'hosts': HostsCollection}
def __attrs_post_init__(self):
- super(InfraProvider, self).__attrs_post_init__()
+ super().__attrs_post_init__()
self.parent = self.appliance.collections.infra_providers
@variable(alias='db')
@@ -277,7 +277,7 @@ def discover(self, discover_cls, cancel=False, start_ip=None, end_ip=None):
if start_ip:
# TODO: add support of IPv6
for idx, octet in enumerate(start_ip.split('.'), start=1):
- key = 'from_ip{idx}'.format(idx=idx)
+ key = f'from_ip{idx}'
form_data.update({key: octet})
if end_ip:
end_octet = end_ip.split('.')[-1]
diff --git a/cfme/infrastructure/pxe.py b/cfme/infrastructure/pxe.py
index 6cb1471303..555c6e1926 100644
--- a/cfme/infrastructure/pxe.py
+++ b/cfme/infrastructure/pxe.py
@@ -88,7 +88,7 @@ class PXEServersView(PXEMainView):
"""
@property
def is_displayed(self):
- return (super(PXEServersView, self).is_displayed and
+ return (super().is_displayed and
self.title.text == 'All PXE Servers')
@@ -397,7 +397,7 @@ class PXECustomizationTemplatesView(PXEMainView):
@property
def is_displayed(self):
- return (super(PXECustomizationTemplatesView, self).is_displayed and
+ return (super().is_displayed and
self.title.text == 'All Customization Templates - System Image Types')
@@ -416,7 +416,7 @@ class entities(View): # noqa
def is_displayed(self):
if getattr(self.context['object'], 'name'):
title = 'Customization Template "{name}"'.format(name=self.context['object'].name)
- return (super(PXECustomizationTemplateDetailsView, self).is_displayed and
+ return (super().is_displayed and
self.title.text == title)
else:
return False
@@ -519,8 +519,8 @@ def copy(self, name=None, description=None, cancel=False):
cancel (bool): It's used for flag to cancel or not the copy operation.
"""
view = navigate_to(self, 'Copy')
- name = name or 'Copy of {}'.format(self.name)
- description = description or 'Copy of {}'.format(self.description)
+ name = name or f'Copy of {self.name}'
+ description = description or f'Copy of {self.description}'
view.fill({'name': name, 'description': description})
customization_template = self.parent.instantiate(name, description, self.script_data,
@@ -594,8 +594,9 @@ class CustomizationTemplateAll(CFMENavigateStep):
prerequisite = NavigateToSibling('PXEMainPage')
def step(self, *args, **kwargs):
- self.view.sidebar.templates.tree.click_path(('All Customization Templates - '
- 'System Image Types'))
+ self.view.sidebar.templates.tree.click_path(
+ 'All Customization Templates - System Image Types'
+ )
@navigator.register(CustomizationTemplateCollection, 'Add')
@@ -643,7 +644,7 @@ class PXESystemImageTypesView(PXEMainView):
@property
def is_displayed(self):
- return (super(PXESystemImageTypesView, self).is_displayed and
+ return (super().is_displayed and
self.title.text == 'All System Image Types')
@@ -793,7 +794,7 @@ def delete(self, cancel=True):
handle_alert=not cancel)
if not cancel:
main_view = self.create_view(PXESystemImageTypesView)
- msg = 'System Image Type "{}": Delete successful'.format(self.name)
+ msg = f'System Image Type "{self.name}": Delete successful'
main_view.flash.assert_success_message(msg)
else:
navigate_to(self, 'Details')
@@ -825,7 +826,7 @@ def create(self, name, provision_type, cancel=False):
msg = 'Add of new System Image Type was cancelled by the user'
else:
view.add.click()
- msg = 'System Image Type "{}" was added'.format(name)
+ msg = f'System Image Type "{name}" was added'
main_view = self.create_view(PXESystemImageTypesView)
main_view.flash.assert_success_message(msg)
return system_image_type
@@ -892,7 +893,7 @@ class PXEDatastoresView(PXEMainView):
@property
def is_displayed(self):
- return (super(PXEDatastoresView, self).is_displayed and
+ return (super().is_displayed and
self.title.text == 'All ISO Datastores')
@@ -955,7 +956,7 @@ def create(self, cancel=False, refresh=True, refresh_timeout=120):
msg = 'Add of new ISO Datastore was cancelled by the user'
else:
view.add.click()
- msg = 'ISO Datastore "{}" was added'.format(self.provider)
+ msg = f'ISO Datastore "{self.provider}" was added'
main_view.flash.assert_success_message(msg)
if refresh:
@@ -1013,8 +1014,9 @@ def refresh(self, wait=True, timeout=120):
basic_info = view.entities.basic_information
last_time = basic_info.get_text_of('Last Refreshed On')
view.toolbar.configuration.item_select('Refresh Relationships', handle_alert=True)
- view.flash.assert_success_message(('ISO Datastore "{}": Refresh Relationships successfully '
- 'initiated'.format(self.provider)))
+ view.flash.assert_success_message(
+ f'ISO Datastore "{self.provider}": Refresh Relationships successfully initiated'
+ )
if wait:
wait_for(lambda lt: lt != basic_info.get_text_of('Last Refreshed On'),
func_args=[last_time], fail_func=view.toolbar.reload.click, num_sec=timeout,
diff --git a/cfme/infrastructure/resource_pool.py b/cfme/infrastructure/resource_pool.py
index c5a8d1c1c6..93a0478de0 100644
--- a/cfme/infrastructure/resource_pool.py
+++ b/cfme/infrastructure/resource_pool.py
@@ -230,5 +230,5 @@ def step(self, *args, **kwargs):
try:
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Resource pool {} not found'.format(self.obj.name))
+ raise ItemNotFound(f'Resource pool {self.obj.name} not found')
row.click()
diff --git a/cfme/infrastructure/virtual_machines.py b/cfme/infrastructure/virtual_machines.py
index be02a36b4f..6a78188915 100644
--- a/cfme/infrastructure/virtual_machines.py
+++ b/cfme/infrastructure/virtual_machines.py
@@ -230,7 +230,7 @@ def is_displayed(self):
return (
self.in_infra_vms and
str(self.entities.title.text) ==
- 'VM or Templates under Provider "{}"'.format(expected_provider)
+ f'VM or Templates under Provider "{expected_provider}"'
)
def reset_page(self):
@@ -523,7 +523,7 @@ def size_mb(self):
return self.size * 1024 if self.size_unit == 'GB' else self.size
-class VMHardware(object):
+class VMHardware:
"""Represents VM's hardware, i.e. CPU (cores, sockets) and memory
"""
EQUAL_ATTRS = {'cores_per_socket', 'sockets', 'mem_size_mb'}
@@ -766,7 +766,7 @@ class InfraVm(VM):
@attr.s
# TODO snapshot collections
- class Snapshot(object):
+ class Snapshot:
snapshot_tree = ManageIQTree('snapshot_treebox')
name = attr.ib(default=None)
@@ -803,7 +803,7 @@ def active(self):
child[0].text == 'Active VM (Active)' and
last_snapshot.text == title)
else:
- return has_child(view.tree, '{} (Active)'.format(title), root_item)
+ return has_child(view.tree, f'{title} (Active)', root_item)
@property
def size(self):
@@ -822,7 +822,7 @@ def size(self):
root_item = view.tree.expand_path(self.parent_vm.name)
snapshot_path = find_path(view.tree, title, root_item)
if not snapshot_path:
- raise Exception('Could not find snapshot with name "{}"'.format(title))
+ raise Exception(f'Could not find snapshot with name "{title}"')
else:
view.tree.click_path(*snapshot_path)
return view.size.text
@@ -851,7 +851,7 @@ def delete(self, cancel=False):
root_item = view.tree.expand_path(self.parent_vm.name)
snapshot_path = find_path(view.tree, title, root_item)
if not snapshot_path:
- raise Exception('Could not find snapshot with name "{}"'.format(title))
+ raise Exception(f'Could not find snapshot with name "{title}"')
else:
view.tree.click_path(*snapshot_path)
@@ -883,7 +883,7 @@ def revert_to(self, cancel=False):
root_item = view.tree.expand_path(self.parent_vm.name)
snapshot_path = find_path(view.tree, title, root_item)
if not snapshot_path:
- raise Exception('Could not find snapshot with name "{}"'.format(title))
+ raise Exception(f'Could not find snapshot with name "{title}"')
else:
view.tree.click_path(*snapshot_path)
@@ -923,7 +923,7 @@ def migrate_vm(self, email=None, first_name=None, last_name=None,
view = navigate_to(self, 'Migrate')
first_name = first_name or fauxfactory.gen_alphanumeric()
last_name = last_name or fauxfactory.gen_alphanumeric()
- email = email or "{}@{}.test".format(first_name, last_name)
+ email = email or f"{first_name}@{last_name}.test"
try:
prov_data = cfme_data["management_systems"][self.provider.key]["provisioning"]
host_name = host or prov_data.get("host")
@@ -950,7 +950,7 @@ def clone_vm(self, email=None, first_name=None, last_name=None,
view = navigate_to(self, 'Clone')
first_name = first_name or fauxfactory.gen_alphanumeric()
last_name = last_name or fauxfactory.gen_alphanumeric()
- email = email or "{}@{}.test".format(first_name, last_name)
+ email = email or f"{first_name}@{last_name}.test"
try:
prov_data = cfme_data["management_systems"][self.provider.key]["provisioning"]
except (KeyError, IndexError):
@@ -973,7 +973,7 @@ def publish_to_template(self, template_name, email=None, first_name=None, last_n
view = navigate_to(self, 'Publish')
first_name = first_name or fauxfactory.gen_alphanumeric()
last_name = last_name or fauxfactory.gen_alphanumeric()
- email = email or "{}@{}.test".format(first_name, last_name)
+ email = email or f"{first_name}@{last_name}.test"
try:
prov_data = cfme_data["management_systems"][self.provider.key]["provisioning"]
except (KeyError, IndexError):
@@ -994,7 +994,7 @@ def publish_to_template(self, template_name, email=None, first_name=None, last_n
provisioning_data['environment'] = {'automatic_placement': True}
view.form.fill_with(provisioning_data, on_change=view.form.submit_button)
- cells = {'Description': 'Publish from [{}] to [{}]'.format(self.name, template_name)}
+ cells = {'Description': f'Publish from [{self.name}] to [{template_name}]'}
provision_request = self.appliance.collections.requests.instantiate(cells=cells)
provision_request.wait_for_request()
return self.appliance.collections.infra_templates.instantiate(template_name, self.provider)
@@ -1036,7 +1036,7 @@ def cluster_id(self):
return int(self.rest_api_entity.ems_cluster_id)
@attr.s
- class CfmeRelationship(object):
+ class CfmeRelationship:
vm = attr.ib()
def navigate(self):
@@ -1053,7 +1053,7 @@ def get_relationship(self):
def set_relationship(self, server_name, server_id, cancel=False):
view = self.navigate()
- view.form.fill({'server': '{} ({})'.format(server_name, server_id)})
+ view.form.fill({'server': f'{server_name} ({server_id})'})
if cancel:
view.form.cancel_button.click()
@@ -1363,7 +1363,7 @@ def all(self):
@attr.s
-class Genealogy(object):
+class Genealogy:
"""Class, representing genealogy of an infra object with possibility of data retrieval
and comparison.
@@ -1517,7 +1517,7 @@ def step(self, *args, **kwargs):
entity_item = self.prerequisite_view.entities.get_entity(
name=self.obj.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate VM/Template with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate VM/Template with name "{self.obj.name}"')
entity_item.click()
def resetter(self, *args, **kwargs):
@@ -1535,7 +1535,7 @@ def step(self, *args, **kwargs):
entity_item = self.prerequisite_view.entities.get_entity(
name=self.obj.name, surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate VM/Template with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate VM/Template with name "{self.obj.name}"')
entity_item.click()
def resetter(self, *args, **kwargs):
@@ -1582,7 +1582,7 @@ def step(self, *args, **kwargs):
row = self.prerequisite_view.entities.get_entity(name=self.obj.name,
surf_pages=True)
except ItemNotFound:
- raise ItemNotFound('Failed to locate VM/Template with name "{}"'.format(self.obj.name))
+ raise ItemNotFound(f'Failed to locate VM/Template with name "{self.obj.name}"')
row.click()
def resetter(self, *args, **kwargs):
diff --git a/cfme/intelligence/reports/dashboards.py b/cfme/intelligence/reports/dashboards.py
index 1c9218b023..af8f3b5f6d 100644
--- a/cfme/intelligence/reports/dashboards.py
+++ b/cfme/intelligence/reports/dashboards.py
@@ -163,7 +163,7 @@ def update(self, updates):
view = self.create_view(DashboardDetailsView, override=updates, wait=10)
view.flash.assert_no_error()
if changed:
- view.flash.assert_message('Dashboard "{}" was saved'.format(self.title))
+ view.flash.assert_message(f'Dashboard "{self.title}" was saved')
else:
view.flash.assert_message('Edit of Dashboard "{}" was cancelled by the user'
.format(self.title))
@@ -206,7 +206,7 @@ def create(self, name, group, title=None, locked=None, widgets=None):
})
view.add_button.click()
view = dashboard.create_view(DashboardAllGroupsView, wait=10)
- view.flash.assert_success_message('Dashboard "{}" was saved'.format(dashboard.title))
+ view.flash.assert_success_message(f'Dashboard "{dashboard.title}" was saved')
return dashboard
@@ -302,5 +302,5 @@ class DefaultDashboardDetails(CFMENavigateStep):
def step(self, *args, **kwargs):
self.prerequisite_view.dashboards.tree.click_path(
"All Dashboards",
- "{} ({})".format(self.obj.title, self.obj.name)
+ f"{self.obj.title} ({self.obj.name})"
)
diff --git a/cfme/intelligence/reports/menus.py b/cfme/intelligence/reports/menus.py
index 0970e6f4d5..5dc1047bc1 100644
--- a/cfme/intelligence/reports/menus.py
+++ b/cfme/intelligence/reports/menus.py
@@ -153,7 +153,7 @@ def reset_to_default(self, group):
view.save_button.click()
flash_view = self.create_view(AllReportMenusView)
flash_view.flash.assert_message(
- 'Report Menu for role "{}" was saved'.format(group)
+ f'Report Menu for role "{group}" was saved'
)
@contextmanager
@@ -185,7 +185,7 @@ def manage_subfolder(self, group, folder, subfolder):
view.save_button.click()
flash_view = self.create_view(AllReportMenusView)
flash_view.flash.assert_message(
- 'Report Menu for role "{}" was saved'.format(group)
+ f'Report Menu for role "{group}" was saved'
)
@contextmanager
@@ -221,7 +221,7 @@ def manage_folder(self, group, folder=None):
view.save_button.click()
flash_view = self.create_view(AllReportMenusView)
flash_view.flash.assert_message(
- 'Report Menu for role "{}" was saved'.format(group)
+ f'Report Menu for role "{group}" was saved'
)
def move_reports(self, group, folder, subfolder, *reports):
diff --git a/cfme/intelligence/reports/reports.py b/cfme/intelligence/reports/reports.py
index 265af88b77..99bcb082e0 100644
--- a/cfme/intelligence/reports/reports.py
+++ b/cfme/intelligence/reports/reports.py
@@ -391,14 +391,14 @@ def update(self, updates):
view.flash.assert_no_error()
if changed:
view.flash.assert_message(
- 'Report "{}" was saved'.format(self.menu_name))
+ f'Report "{self.menu_name}" was saved')
else:
view.flash.assert_message(
- 'Edit of Report "{}" was cancelled by the user'.format(self.menu_name))
+ f'Edit of Report "{self.menu_name}" was cancelled by the user')
def copy(self):
""" Copy a report via UI and return a copy of a Report object"""
- menu_name = "Copy of {}".format(self.menu_name)
+ menu_name = f"Copy of {self.menu_name}"
view = navigate_to(self, "Copy")
view.add_button.click()
@@ -423,7 +423,7 @@ def delete(self, cancel=False):
if custom_reports_number > 1:
view = self.create_view(AllCustomReportsView, wait='5s')
view.flash.assert_no_error()
- view.flash.assert_message('Report "{}": Delete successful'.format(self.menu_name))
+ view.flash.assert_message(f'Report "{self.menu_name}": Delete successful')
@cached_property
def saved_reports(self):
diff --git a/cfme/intelligence/reports/schedules.py b/cfme/intelligence/reports/schedules.py
index 8283352363..6e9a5ba0db 100644
--- a/cfme/intelligence/reports/schedules.py
+++ b/cfme/intelligence/reports/schedules.py
@@ -30,7 +30,7 @@
class VolatileBootstrapSelect(BootstrapSelect):
def fill(self, items):
try:
- super(VolatileBootstrapSelect, self).fill(items)
+ super().fill(items)
except NoSuchElementException:
logger.warning(
"fill() operation was successful, but no options are left in BootstrapSelect to"
@@ -56,9 +56,9 @@ class BootstrapSelectRetry(BootstrapSelect):
Retrys the open action
"""
def open(self):
- super(BootstrapSelectRetry, self).open()
+ super().open()
if not self.is_open:
- super(BootstrapSelectRetry, self).open()
+ super().open()
class SchedulesFormCommon(CloudIntelReportsView):
diff --git a/cfme/intelligence/reports/widgets/__init__.py b/cfme/intelligence/reports/widgets/__init__.py
index ab8f27222c..38f1ba6528 100644
--- a/cfme/intelligence/reports/widgets/__init__.py
+++ b/cfme/intelligence/reports/widgets/__init__.py
@@ -79,10 +79,10 @@ def update(self, updates):
view = self.create_view(DashboardWidgetDetailsView, override=updates, wait='10s')
view.flash.assert_no_error()
if changed:
- view.flash.assert_message('Widget "{}" was saved'.format(self.title))
+ view.flash.assert_message(f'Widget "{self.title}" was saved')
else:
view.flash.assert_message(
- 'Edit of Widget "{}" was cancelled by the user'.format(self.description))
+ f'Edit of Widget "{self.description}" was cancelled by the user')
def delete(self, cancel=False):
"""Delete this Widget in the UI.
diff --git a/cfme/intelligence/reports/widgets/report_widgets.py b/cfme/intelligence/reports/widgets/report_widgets.py
index 3e0b3a219d..2f66d5607c 100644
--- a/cfme/intelligence/reports/widgets/report_widgets.py
+++ b/cfme/intelligence/reports/widgets/report_widgets.py
@@ -61,9 +61,9 @@ def __attrs_post_init__(self):
self.filter, self.subfilter, self.repfilter = self.filter
for i in range(1, 5):
try:
- setattr(self, "column{}".format(i), self.columns[i])
+ setattr(self, f"column{i}", self.columns[i])
except IndexError:
- setattr(self, "column{}".format(i), None)
+ setattr(self, f"column{i}", None)
@property
def fill_dict(self):
diff --git a/cfme/markers/composite.py b/cfme/markers/composite.py
index 3a8875e86a..520081207d 100644
--- a/cfme/markers/composite.py
+++ b/cfme/markers/composite.py
@@ -33,7 +33,7 @@ def pytest_collection_modifyitems(session, config, items):
source = 'jenkins'
store.terminalreporter.write(
- 'Attempting Uncollect for build: {} and source: {}\n'.format(build, source), bold=True)
+ f'Attempting Uncollect for build: {build} and source: {source}\n', bold=True)
# The following code assumes slaves collect AFTER master is done, this prevents a parallel
# speed up, but in the future we may move uncollection to a later stage and only do it on
@@ -57,11 +57,11 @@ def pytest_collection_modifyitems(session, config, items):
for item in items:
try:
name, location = get_test_idents(item)
- test_ident = "{}/{}".format(location, name)
+ test_ident = f"{location}/{name}"
status = pl['tests'][test_ident]['statuses']['overall']
if status == 'passed':
- logger.info('Uncollecting {} as it passed last time'.format(item.name))
+ logger.info(f'Uncollecting {item.name} as it passed last time')
continue
else:
new_items.append(item)
diff --git a/cfme/markers/env.py b/cfme/markers/env.py
index f381f365b3..36926afd8d 100644
--- a/cfme/markers/env.py
+++ b/cfme/markers/env.py
@@ -13,7 +13,7 @@
from cfme.utils import testgen
-class EnvironmentMarker(object):
+class EnvironmentMarker:
"""Base Environment Marker"""
PARAM_BY_DEFAULT = False
NAME = None
diff --git a/cfme/markers/env_markers/provider.py b/cfme/markers/env_markers/provider.py
index ef7f76c2bc..dcfdc5e198 100644
--- a/cfme/markers/env_markers/provider.py
+++ b/cfme/markers/env_markers/provider.py
@@ -150,7 +150,7 @@ def data_provider_types(provider):
@attr.s
-class DataProvider(object):
+class DataProvider:
"""A simple holder for a pseudo provider.
This is not a real provider. This is used in place of a real provider to allow things like
@@ -165,15 +165,15 @@ class DataProvider(object):
@cached_property
def the_id(self):
if self.version:
- return "{}-{}".format(self.type_name, self.version)
+ return f"{self.type_name}-{self.version}"
else:
- return "{}".format(self.type_name)
+ return f"{self.type_name}"
def one_of(self, *classes):
return issubclass(self.klass, classes)
def __repr__(self):
- return '{}({})[{}]'.format(self.type_name, self.category, self.version)
+ return f'{self.type_name}({self.category})[{self.version}]'
def all_required(miq_version, filters=None):
@@ -267,7 +267,7 @@ def get_valid_providers(provider):
for a_prov in available_providers:
try:
if not a_prov.version:
- raise ValueError("provider {p} has no version".format(p=a_prov))
+ raise ValueError(f"provider {a_prov} has no version")
elif (a_prov.version == provider.version and
a_prov.type == provider.type_name and
a_prov.category == provider.category):
diff --git a/cfme/markers/meta.py b/cfme/markers/meta.py
index c4f48921ab..45e977ff05 100644
--- a/cfme/markers/meta.py
+++ b/cfme/markers/meta.py
@@ -103,7 +103,7 @@ def meta(request):
Plugin = namedtuple('Plugin', ['name', 'metas', 'function', 'kwargs'])
-class PluginContainer(object):
+class PluginContainer:
SETUP = "setup"
TEARDOWN = "teardown"
BEFORE_RUN = "before_run"
@@ -147,7 +147,7 @@ def run_plugins(item, when):
disabled_plugins = [name.strip() for name in disabled_plugins.split(",")]
for plugin_name, plugin_objects in by_names.items():
if plugin_name in disabled_plugins:
- logger.info("Ignoring plugin {} due to commandline option".format(plugin_name))
+ logger.info(f"Ignoring plugin {plugin_name} due to commandline option")
continue
plugin_objects.sort(key=lambda p: len(p.metas), reverse=True)
plug = plugin_objects[0]
diff --git a/cfme/markers/polarion.py b/cfme/markers/polarion.py
index 5ceadc4a1b..417f46d2b5 100644
--- a/cfme/markers/polarion.py
+++ b/cfme/markers/polarion.py
@@ -29,7 +29,7 @@ def pytest_collection_modifyitems(config, items):
@attr.s(hash=False)
-class ReportPolarionToJunitPlugin(object):
+class ReportPolarionToJunitPlugin:
xml = attr.ib()
node_map = attr.ib()
diff --git a/cfme/markers/requires.py b/cfme/markers/requires.py
index 6e33524299..9db7111c47 100644
--- a/cfme/markers/requires.py
+++ b/cfme/markers/requires.py
@@ -56,5 +56,5 @@ def pytest_runtest_setup(item):
else:
error_verb = 'not yet run or does not exist'
- errmsg = 'required test {} {}'.format(test_id, error_verb)
+ errmsg = f'required test {test_id} {error_verb}'
pytest.skip(errmsg)
diff --git a/cfme/markers/rhv.py b/cfme/markers/rhv.py
index 5b934c2ec0..7e3ad4b2d1 100644
--- a/cfme/markers/rhv.py
+++ b/cfme/markers/rhv.py
@@ -67,7 +67,7 @@ def pytest_runtest_logreport(report):
return
reporter = xml.node_reporter(report)
for tier in RHV_CFME_TIERS:
- tier_marker = 'rhv{}'.format(tier)
+ tier_marker = f'rhv{tier}'
if report.keywords.get(tier_marker):
reporter.add_property('rhv_tier', tier_marker)
break
diff --git a/cfme/markers/sauce.py b/cfme/markers/sauce.py
index e28f20b6d8..ebe3ba6898 100644
--- a/cfme/markers/sauce.py
+++ b/cfme/markers/sauce.py
@@ -15,6 +15,6 @@ def pytest_configure(config):
config.addinivalue_line('markers', __doc__.splitlines()[0])
if config.option.sauce:
if config.option.markexpr:
- config.option.markexpr = 'sauce and ({})'.format(config.option.markexpr)
+ config.option.markexpr = f'sauce and ({config.option.markexpr})'
else:
config.option.markexpr = 'sauce'
diff --git a/cfme/markers/skipper.py b/cfme/markers/skipper.py
index 5447d807f9..4415f6a2d5 100644
--- a/cfme/markers/skipper.py
+++ b/cfme/markers/skipper.py
@@ -53,11 +53,11 @@ def pytest_configure(config):
marks_to_skip.append(dest)
# Build all the marks to skip into one flat mark expression rather than nesting
- skip_mark_expr = ' and '.join(['not {}'.format(mark) for mark in marks_to_skip])
+ skip_mark_expr = ' and '.join([f'not {mark}' for mark in marks_to_skip])
# modify (or set) the mark expression to exclude tests as configured by the commandline flags
if skip_mark_expr:
if config.option.markexpr:
- config.option.markexpr = '({}) and ({})'.format(skip_mark_expr, config.option.markexpr)
+ config.option.markexpr = f'({skip_mark_expr}) and ({config.option.markexpr})'
else:
config.option.markexpr = skip_mark_expr
diff --git a/cfme/markers/smoke.py b/cfme/markers/smoke.py
index 41842ee54c..28f62911fd 100644
--- a/cfme/markers/smoke.py
+++ b/cfme/markers/smoke.py
@@ -70,7 +70,7 @@ def pytest_collection_modifyitems(session, config, items):
smoke_tests.halt_on_fail = config.getvalue('haltonsmokefail')
-class SmokeTests(object):
+class SmokeTests:
# state trackers
run_tests = 0
failed_tests = 0
diff --git a/cfme/metaplugins/blockers.py b/cfme/metaplugins/blockers.py
index 57d20e1b27..303018b6f7 100644
--- a/cfme/metaplugins/blockers.py
+++ b/cfme/metaplugins/blockers.py
@@ -85,12 +85,12 @@ def resolve_blockers(item, blockers):
# Check blockers
use_blockers = []
# Bugzilla shortcut
- blockers = ["BZ#{}".format(b) if isinstance(b, int) else b for b in blockers]
+ blockers = [f"BZ#{b}" if isinstance(b, int) else b for b in blockers]
for blocker in map(Blocker.parse, blockers):
if blocker.blocks:
use_blockers.append(blocker)
# Unblocking
- discard_blockers = set([])
+ discard_blockers = set()
for blocker in use_blockers:
unblock_func = kwargify(blocker.kwargs.get("unblock"))
local_env = {"blocker": blocker}
diff --git a/cfme/metaplugins/server_roles.py b/cfme/metaplugins/server_roles.py
index 8a70d0e3a0..cbd7de097d 100644
--- a/cfme/metaplugins/server_roles.py
+++ b/cfme/metaplugins/server_roles.py
@@ -91,6 +91,6 @@ def add_server_roles(item, server_roles, server_roles_mode="add"):
if not available_roles.issuperset(set(roles_with_vals)):
unknown_roles = ', '.join(set(roles_with_vals) - available_roles)
- raise Exception('Unknown server role(s): {}'.format(unknown_roles))
+ raise Exception(f'Unknown server role(s): {unknown_roles}')
server_settings.update_server_roles_db(roles_with_vals)
diff --git a/cfme/modeling/base.py b/cfme/modeling/base.py
index 2cec533069..6b4d3ecb04 100644
--- a/cfme/modeling/base.py
+++ b/cfme/modeling/base.py
@@ -24,7 +24,7 @@ def load_appliance_collections():
@attr.s
-class EntityCollections(object):
+class EntityCollections:
"""Caches instances of collection objects for use by the collections accessor
The appliance object has a ``collections`` attribute. This attribute is an instance
@@ -55,7 +55,7 @@ def collections(self):
return collections
def __dir__(self):
- internal_dir = dir(super(EntityCollections, self))
+ internal_dir = dir(super())
return internal_dir + list(self._availiable_collections.keys())
def __getattr__(self, name):
@@ -208,7 +208,7 @@ def expected_details_title(self):
.. code-block:: python
expected_title = self.context['object'].expected_details_title
"""
- return "{} (Summary)".format(self.name)
+ return f"{self.name} (Summary)"
@property
def expected_details_breadcrumb(self):
@@ -218,11 +218,11 @@ def expected_details_breadcrumb(self):
.. code-block:: python
expected_breadcrumb = self.context['object'].expected_details_breadcrumb
"""
- return "{} (Summary)".format(self.name)
+ return f"{self.name} (Summary)"
@attr.s
-class CollectionProperty(object):
+class CollectionProperty:
type_or_get_type = attr.ib(validator=attr.validators.instance_of((Callable, type)))
def __get__(self, instance, owner):
diff --git a/cfme/networks/__init__.py b/cfme/networks/__init__.py
index be68964a56..df399475a1 100644
--- a/cfme/networks/__init__.py
+++ b/cfme/networks/__init__.py
@@ -3,7 +3,7 @@
from cfme.utils.appliance.implementations.ui import navigator
-class ValidateStatsMixin(object):
+class ValidateStatsMixin:
# TODO: Move this class to a higher level, where could be useful for thing beyond this
# network module, maybe BaseEntity
diff --git a/cfme/networks/cloud_network.py b/cfme/networks/cloud_network.py
index cfdca45d1a..fbe05601b9 100644
--- a/cfme/networks/cloud_network.py
+++ b/cfme/networks/cloud_network.py
@@ -74,7 +74,7 @@ def edit(self, name, change_external=None, change_admin_state=None, change_share
'administrative_state': change_admin_state,
'shared': change_shared})
view.save.click()
- view.flash.assert_success_message('Cloud Network "{}" updated'.format(name))
+ view.flash.assert_success_message(f'Cloud Network "{name}" updated')
self.name = name
def delete(self):
@@ -130,7 +130,7 @@ def create(self, name, tenant, provider, network_manager, network_type, is_exter
'administrative_state': admin_state,
'shared': is_shared})
view.add.click()
- view.flash.assert_success_message('Cloud Network "{}" created'.format(name))
+ view.flash.assert_success_message(f'Cloud Network "{name}" created')
network = self.instantiate(name, provider)
# Refresh provider's relationships to have new network displayed
wait_for(provider.is_refreshed, func_kwargs=dict(refresh_delta=10), timeout=600)
diff --git a/cfme/networks/network_port.py b/cfme/networks/network_port.py
index 82612af715..0618714121 100644
--- a/cfme/networks/network_port.py
+++ b/cfme/networks/network_port.py
@@ -116,4 +116,4 @@ def prerequisite(self, *args, **kwargs):
if is_filtered:
return navigate_to(filtered, 'NetworkPorts')
else:
- raise DestinationNotFound("Parent filter missing on object {obj}".format(obj=self.obj))
+ raise DestinationNotFound(f"Parent filter missing on object {self.obj}")
diff --git a/cfme/networks/network_router.py b/cfme/networks/network_router.py
index 7076c73441..83fc565371 100644
--- a/cfme/networks/network_router.py
+++ b/cfme/networks/network_router.py
@@ -163,7 +163,7 @@ def create(self, name, provider, tenant, network_manager, has_external_gw=False,
'subnet_name': ext_network_subnet})
view.fill(form_params)
view.add.click()
- view.flash.assert_success_message('Network Router "{}" created'.format(name))
+ view.flash.assert_success_message(f'Network Router "{name}" created')
router = self.instantiate(name, provider, ext_network)
# Refresh provider's relationships to have new router displayed
wait_for(provider.is_refreshed, func_kwargs=dict(refresh_delta=10), timeout=600)
@@ -253,6 +253,6 @@ class CloudSubnets(CFMENavigateStep):
def step(self, *args, **kwargs):
item = 'Cloud Subnets'
if not int(self.prerequisite_view.entities.relationships.get_text_of(item)):
- raise DestinationNotFound("This Network router doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This Network router doesn't have {item}")
self.prerequisite_view.entities.relationships.click_at(item)
diff --git a/cfme/networks/provider/__init__.py b/cfme/networks/provider/__init__.py
index 7d7097543a..fdc508d041 100644
--- a/cfme/networks/provider/__init__.py
+++ b/cfme/networks/provider/__init__.py
@@ -244,7 +244,7 @@ def _post_cancel_edit_checks(self):
def _post_create_checks(self, main_view, add_view=None):
main_view.flash.assert_no_error()
if main_view.is_displayed:
- success_text = '{} Providers "{}" was saved'.format(self.string_name, self.name)
+ success_text = f'{self.string_name} Providers "{self.name}" was saved'
main_view.flash.assert_message(success_text)
else:
add_view.flash.assert_no_error()
@@ -254,7 +254,7 @@ def _post_update_checks(self, edit_view):
details_view = self.create_view(navigator.get_class(self, 'Details').VIEW)
main_view = self.create_view(navigator.get_class(self, 'All').VIEW)
main_view.flash.assert_no_error()
- success_text = '{} Manager "{}" was saved'.format(self.string_name, self.name)
+ success_text = f'{self.string_name} Manager "{self.name}" was saved'
if main_view.is_displayed:
main_view.flash.assert_message(success_text)
elif details_view.is_displayed:
@@ -379,7 +379,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'CloudSubnets')
@@ -393,7 +393,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'CloudNetworks')
@@ -407,7 +407,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'NetworkRouters')
@@ -421,7 +421,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'SecurityGroups')
@@ -435,7 +435,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'FloatingIPs')
@@ -449,7 +449,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'NetworkPorts')
@@ -463,7 +463,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'LoadBalancers')
@@ -477,7 +477,7 @@ def step(self, *args, **kwargs):
if item_amt > 0:
self.prerequisite_view.entities.relationships.click_at(item)
else:
- raise DestinationNotFound("This provider doesn't have {item}".format(item=item))
+ raise DestinationNotFound(f"This provider doesn't have {item}")
@navigator.register(NetworkProvider, 'TopologyFromDetails')
diff --git a/cfme/networks/subnet.py b/cfme/networks/subnet.py
index dce184d2af..343275bfd1 100644
--- a/cfme/networks/subnet.py
+++ b/cfme/networks/subnet.py
@@ -50,7 +50,7 @@ def edit(self, new_name, gateway=None):
view.fill({'subnet_name': new_name,
'gateway': gateway})
view.save.click()
- view.flash.assert_success_message('Cloud Subnet "{}" updated'.format(new_name))
+ view.flash.assert_success_message(f'Cloud Subnet "{new_name}" updated')
self.name = new_name
def delete(self):
@@ -147,7 +147,7 @@ def create(self, name, tenant, provider, network_manager, network_name, cidr, ga
'gateway': gateway,
'cloud_tenant': tenant})
view.add.click()
- view.flash.assert_success_message('Cloud Subnet "{}" created'.format(name))
+ view.flash.assert_success_message(f'Cloud Subnet "{name}" created')
subnet = self.instantiate(name, provider, network_name)
# Refresh provider's relationships to have new subnet displayed
wait_for(provider.is_refreshed, func_kwargs=dict(refresh_delta=10), timeout=600)
@@ -220,6 +220,6 @@ def step(self):
item = 'Network Ports'
if not int(self.prerequisite_view.entities.relationships.get_text_of(item)):
raise DestinationNotFound(
- 'Cloud Subnet {} has a 0 count for {} relationships'.format(self.obj, item))
+ f'Cloud Subnet {self.obj} has a 0 count for {item} relationships')
self.prerequisite_view.entities.relationships.click_at(item)
diff --git a/cfme/networks/views.py b/cfme/networks/views.py
index 3c97456600..803544394a 100644
--- a/cfme/networks/views.py
+++ b/cfme/networks/views.py
@@ -68,7 +68,7 @@ class NetworkProviderAddView(ProviderAddView):
@property
def is_displayed(self):
- return (super(NetworkProviderAddView, self).is_displayed and
+ return (super().is_displayed and
self.navigation.currently_selected == [
'Networks', 'Providers'] and
self.title.text == 'Add New Network Provider')
diff --git a/cfme/optimize/bottlenecks.py b/cfme/optimize/bottlenecks.py
index eb635eaaae..216f72e2c2 100644
--- a/cfme/optimize/bottlenecks.py
+++ b/cfme/optimize/bottlenecks.py
@@ -25,9 +25,9 @@ def is_displayed(self):
region_number = self.browser.appliance.server.zone.region.number
return (
super(BottlenecksView, self).is_displayed and
- self.title.text == 'Region "Region {}" Bottlenecks Summary'.format(region_number) and
+ self.title.text == f'Region "Region {region_number}" Bottlenecks Summary' and
self.bottlenecks.is_opened and
- self.bottlenecks.tree.currently_selected == ["Region {}".format(region_number)]
+ self.bottlenecks.tree.currently_selected == [f"Region {region_number}"]
)
@View.nested
diff --git a/cfme/physical/physical_chassis.py b/cfme/physical/physical_chassis.py
index 383bb798ce..45d1044d36 100644
--- a/cfme/physical/physical_chassis.py
+++ b/cfme/physical/physical_chassis.py
@@ -117,7 +117,7 @@ def validate_stats(self, ui=False):
# Verify that the stats retrieved from wrapanapi match those retrieved
# from the UI
for stat in stats_to_match:
- logger.debug("Validating stat {} of {}".format(stat, self.name))
+ logger.debug(f"Validating stat {stat} of {self.name}")
try:
cfme_stat = int(getattr(self, stat)(method='ui' if ui else None))
chassis_stat = int(chassis_stats[stat])
@@ -128,14 +128,14 @@ def validate_stats(self, ui=False):
raise StatsDoNotMatch(msg.format(stat, self.name, chassis_stat, cfme_stat))
except KeyError:
raise HostStatsNotContains(
- "Chassis stats information does not contain '{}'".format(stat))
+ f"Chassis stats information does not contain '{stat}'")
except AttributeError:
- raise ProviderHasNoProperty("Provider does not know how to get '{}'".format(stat))
+ raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'")
# Verify that the inventory retrieved from wrapanapi match those retrieved
# from the UI
for inventory in inventory_to_match:
- logger.debug("Validating inventory {} of {}".format(inventory, self.name))
+ logger.debug(f"Validating inventory {inventory} of {self.name}")
try:
cfme_inventory = getattr(self, inventory)(method='ui' if ui else None)
chass_inventory = chassis_inventory[inventory]
@@ -147,7 +147,7 @@ def validate_stats(self, ui=False):
cfme_inventory))
except KeyError:
raise HostStatsNotContains(
- "Server inventory information does not contain '{}'".format(inventory))
+ f"Server inventory information does not contain '{inventory}'")
except AttributeError:
msg = "Provider does not know how to get '{}'"
raise ProviderHasNoProperty(msg.format(inventory))
@@ -196,7 +196,7 @@ def is_displayed(self):
class PhysicalChassisEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(PhysicalChassisEntity, self).data
+ data_dict = super().data
if data_dict.get("quadicon", ""):
quad_data = document_fromstring(data_dict["quadicon"])
data_dict["no_host"] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text)
diff --git a/cfme/physical/physical_rack.py b/cfme/physical/physical_rack.py
index 5ee9d0c54f..cff0ac4b8c 100644
--- a/cfme/physical/physical_rack.py
+++ b/cfme/physical/physical_rack.py
@@ -88,7 +88,7 @@ def wait_for_physical_rack_state_change(self, desired_state, timeout=300):
def _looking_for_state_change():
entity = view.entities.get_entity(name=self.name)
- return "currentstate-{}".format(desired_state) in entity.data['state']
+ return f"currentstate-{desired_state}" in entity.data['state']
wait_for(_looking_for_state_change, fail_func=view.browser.refresh, num_sec=timeout)
@@ -130,9 +130,9 @@ def validate_stats(self, ui=False):
raise StatsDoNotMatch(msg.format(stat, self.name, rack_stat, cfme_stat))
except KeyError:
raise RackStatsDoesNotContain(
- "Rack stats information does not contain '{}'".format(stat))
+ f"Rack stats information does not contain '{stat}'")
except AttributeError:
- raise ProviderHasNoProperty("Provider does not know how to get '{}'".format(stat))
+ raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'")
# Verify that the inventory retrieved from wrapanapi match those retrieved
# from the UI
@@ -148,7 +148,7 @@ def validate_stats(self, ui=False):
cfme_inventory))
except KeyError:
raise RackStatsDoesNotContain(
- "Rack inventory information does not contain '{}'".format(inventory))
+ f"Rack inventory information does not contain '{inventory}'")
except AttributeError:
msg = "Provider does not know how to get '{}'"
raise ProviderHasNoProperty(msg.format(inventory))
@@ -206,7 +206,7 @@ def in_compute_physical_infrastructure_racks(self):
class PhysicalRackEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(PhysicalRackEntity, self).data
+ data_dict = super().data
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
data_dict['no_host'] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text)
diff --git a/cfme/physical/physical_server.py b/cfme/physical/physical_server.py
index c2091fcdee..04cc798d83 100644
--- a/cfme/physical/physical_server.py
+++ b/cfme/physical/physical_server.py
@@ -256,9 +256,9 @@ def validate_stats(self, ui=False):
raise StatsDoNotMatch(msg.format(stat, self.name, server_stat, cfme_stat))
except KeyError:
raise HostStatsNotContains(
- "Server stats information does not contain '{}'".format(stat))
+ f"Server stats information does not contain '{stat}'")
except AttributeError:
- raise ProviderHasNoProperty("Provider does not know how to get '{}'".format(stat))
+ raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'")
# Verify that the inventory retrieved from wrapanapi match those retrieved
# from the UI
@@ -274,7 +274,7 @@ def validate_stats(self, ui=False):
cfme_inventory))
except KeyError:
raise HostStatsNotContains(
- "Server inventory information does not contain '{}'".format(inventory))
+ f"Server inventory information does not contain '{inventory}'")
except AttributeError:
msg = "Provider does not know how to get '{}'"
raise ProviderHasNoProperty(msg.format(inventory))
diff --git a/cfme/physical/physical_storage.py b/cfme/physical/physical_storage.py
index b556f986fd..a34c879363 100644
--- a/cfme/physical/physical_storage.py
+++ b/cfme/physical/physical_storage.py
@@ -42,7 +42,7 @@ def in_compute_physical_infrastructure_storages(self):
class PhysicalStorageEntity(JSBaseEntity):
@property
def data(self):
- data_dict = super(PhysicalStorageEntity, self).data
+ data_dict = super().data
if 'quadicon' in data_dict and data_dict['quadicon']:
quad_data = document_fromstring(data_dict['quadicon'])
data_dict['no_port'] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text)
diff --git a/cfme/physical/provider/__init__.py b/cfme/physical/provider/__init__.py
index 14909093ec..ac32f36882 100644
--- a/cfme/physical/provider/__init__.py
+++ b/cfme/physical/provider/__init__.py
@@ -40,7 +40,7 @@ class PhysicalProvider(Pretty, BaseProvider, Fillable):
key = attr.ib(default=None)
def __attrs_post_init__(self):
- super(PhysicalProvider, self).__attrs_post_init__()
+ super().__attrs_post_init__()
self.parent = self.appliance.collections.physical_providers
@property
diff --git a/cfme/physical/provider/redfish.py b/cfme/physical/provider/redfish.py
index 794fb150e3..6c9916e102 100644
--- a/cfme/physical/provider/redfish.py
+++ b/cfme/physical/provider/redfish.py
@@ -85,9 +85,9 @@ def get_detail(self, label):
view = navigate_to(self, 'Details')
try:
stat = view.entities.summary('Relationships').get_text_of(label)
- logger.info("{}: {}".format(label, stat))
+ logger.info(f"{label}: {stat}")
except NoSuchElementException:
- logger.error("Couldn't find number of {}".format(label))
+ logger.error(f"Couldn't find number of {label}")
return stat
@variable(alias='ui')
@@ -117,7 +117,7 @@ class RedfishPhysicalChassis(PhysicalChassis):
STATS_TO_MATCH = ['num_physical_servers']
def __init__(self):
- super(RedfishPhysicalChassis, self)
+ super()
@attr.s
@@ -131,7 +131,7 @@ class RedfishPhysicalRack(PhysicalRack):
STATS_TO_MATCH = []
def __init__(self):
- super(RedfishPhysicalRack, self)
+ super()
def validate_stats(self, ui=False):
""" Validates that the detail page matches the physical rack's information.
@@ -170,9 +170,9 @@ def validate_stats(self, ui=False):
raise StatsDoNotMatch(msg.format(stat, self.name, rack_stat, cfme_stat))
except KeyError:
raise HostStatsNotContains(
- "Server stats information does not contain '{}'".format(stat))
+ f"Server stats information does not contain '{stat}'")
except AttributeError:
- raise ProviderHasNoProperty("Provider does not know how to get '{}'".format(stat))
+ raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'")
# Verify that the inventory retrieved from wrapanapi match those retrieved
# from the UI
@@ -188,7 +188,7 @@ def validate_stats(self, ui=False):
cfme_inventory))
except KeyError:
raise HostStatsNotContains(
- "Server inventory information does not contain '{}'".format(inventory))
+ f"Server inventory information does not contain '{inventory}'")
except AttributeError:
msg = "Provider does not know how to get '{}'"
raise ProviderHasNoProperty(msg.format(inventory))
diff --git a/cfme/provisioning.py b/cfme/provisioning.py
index 15cd831d7c..a8b1ec63a8 100644
--- a/cfme/provisioning.py
+++ b/cfme/provisioning.py
@@ -9,7 +9,7 @@ def do_vm_provisioning(appliance, template_name, provider, vm_name, provisioning
vm = appliance.collections.infra_vms.instantiate(name=vm_name,
provider=provider,
template_name=template_name)
- note = ('template {} to vm {} on provider {}'.format(template_name, vm_name, provider.key))
+ note = (f'template {template_name} to vm {vm_name} on provider {provider.key}')
provisioning_data.update({
'request': {
'email': email,
@@ -26,7 +26,7 @@ def do_vm_provisioning(appliance, template_name, provider, vm_name, provisioning
# Provision Re important in this test
logger.info('Waiting for cfme provision request for vm %s', vm_name)
- request_description = 'Provision from [{}] to [{}]'.format(template_name, vm_name)
+ request_description = f'Provision from [{template_name}] to [{vm_name}]'
provision_request = appliance.collections.requests.instantiate(request_description)
provision_request.wait_for_request(method='ui', num_sec=num_sec)
assert provision_request.is_succeeded(method='ui'), "Provisioning failed: {}".format(
diff --git a/cfme/rest/gen_data.py b/cfme/rest/gen_data.py
index fc35fc332e..5b9739d752 100644
--- a/cfme/rest/gen_data.py
+++ b/cfme/rest/gen_data.py
@@ -51,8 +51,8 @@ def categories(request, appliance, num=1):
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric().lower()
ctg_data.append({
- 'name': 'test_category_{}'.format(uniq),
- 'description': 'test_category_{}'.format(uniq)
+ 'name': f'test_category_{uniq}',
+ 'description': f'test_category_{uniq}'
})
return _creating_skeleton(request, appliance, 'categories', ctg_data)
@@ -65,8 +65,8 @@ def tags(request, appliance, categories):
uniq = fauxfactory.gen_alphanumeric().lower()
refs = [{'id': ctg.id}, {'href': ctg.href}, {'name': ctg.name}]
tags.append({
- 'name': 'test_tag_{}'.format(uniq),
- 'description': 'test_tag_{}'.format(uniq),
+ 'name': f'test_tag_{uniq}',
+ 'description': f'test_tag_{uniq}',
'category': refs[index % 3]
})
@@ -77,23 +77,23 @@ def dialog_rest(request, appliance):
"""Creates service dialog using REST API."""
uid = fauxfactory.gen_alphanumeric()
data = {
- "description": "my dialog {}".format(uid),
+ "description": f"my dialog {uid}",
"label": uid,
"buttons": "submit,cancel",
"dialog_tabs": [{
- "description": "my tab desc {}".format(uid),
+ "description": f"my tab desc {uid}",
"position": 0,
- "label": "tab_{}".format(uid),
+ "label": f"tab_{uid}",
"display": "edit",
"dialog_groups": [{
- "description": "my box desc {}".format(uid),
- "label": "box_{}".format(uid),
+ "description": f"my box desc {uid}",
+ "label": f"box_{uid}",
"display": "edit",
"position": 0,
"dialog_fields": [{
"name": "service_name",
- "description": "my ele desc {}".format(uid),
- "label": "ele_{}".format(uid),
+ "description": f"my ele desc {uid}",
+ "label": f"ele_{uid}",
"data_type": "string",
"display": "edit",
"required": False,
@@ -164,7 +164,7 @@ def _order_finished():
.format(service_request.message))
service_name = get_dialog_service_name(appliance, service_request, service_template.name)
- assert '[{}]'.format(service_name) in service_request.message
+ assert f'[{service_name}]' in service_request.message
provisioned_service = appliance.rest_api.collections.services.get(
service_template_id=service_template.id)
@@ -174,7 +174,7 @@ def _finished():
provisioned_service.action.delete()
except Exception:
# service can be deleted by test
- logger.warning('Failed to delete service `{}`.'.format(service_name))
+ logger.warning(f'Failed to delete service `{service_name}`.')
# tests expect iterable
return [provisioned_service]
@@ -300,8 +300,8 @@ def service_templates_rest(request, appliance, service_dialog=None, service_cata
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric(5)
data.append({
- "name": 'item_{}'.format(uniq),
- "description": "my catalog {}".format(uniq),
+ "name": f'item_{uniq}',
+ "description": f"my catalog {uniq}",
"service_type": "atomic",
"prov_type": "generic",
"display": True,
@@ -449,8 +449,8 @@ def tenants(request, appliance, num=1, **kwargs):
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric()
data.append({
- 'description': kwargs.get("description", 'test_tenants_{}'.format(uniq)),
- 'name': kwargs.get("name", 'test_tenants_{}'.format(uniq)),
+ 'description': kwargs.get("description", f'test_tenants_{uniq}'),
+ 'name': kwargs.get("name", f'test_tenants_{uniq}'),
'divisible': kwargs.get("divisible", 'true'),
'use_config_for_attributes': kwargs.get("use_config_for_attributes", 'false'),
'parent': {'href': parent.href}
@@ -471,10 +471,10 @@ def users(request, appliance, num=1, **kwargs):
uniq = fauxfactory.gen_alphanumeric(4).lower()
data.append(
{
- "userid": kwargs.get("userid", "user_{}".format(uniq)),
- "name": kwargs.get("name", "name_{}".format(uniq)),
+ "userid": kwargs.get("userid", f"user_{uniq}"),
+ "name": kwargs.get("name", f"name_{uniq}"),
"password": kwargs.get("password", fauxfactory.gen_alphanumeric()),
- "email": kwargs.get("email", "{}@example.com".format(uniq)),
+ "email": kwargs.get("email", f"{uniq}@example.com"),
"group": {"description": kwargs.get("group", "EvmGroup-user_self_service")},
}
)
@@ -527,8 +527,8 @@ def orchestration_templates(request, appliance, num=2):
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric(5)
data.append({
- 'name': 'test_{}'.format(uniq),
- 'description': 'Test Template {}'.format(uniq),
+ 'name': f'test_{uniq}',
+ 'description': f'Test Template {uniq}',
'type': 'ManageIQ::Providers::Amazon::CloudManager::OrchestrationTemplate',
'orderable': False,
'draft': False,
@@ -555,8 +555,8 @@ def conditions(request, appliance, num=2):
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric(5)
data_dict = {
- 'name': 'test_condition_{}'.format(uniq),
- 'description': 'Test Condition {}'.format(uniq),
+ 'name': f'test_condition_{uniq}',
+ 'description': f'Test Condition {uniq}',
'expression': {'=': {'field': 'ContainerImage-architecture', 'value': 'dsa'}},
'towhat': 'ExtManagementSystem'
}
@@ -573,8 +573,8 @@ def policies(request, appliance, num=2):
for _ in range(num):
uniq = fauxfactory.gen_alphanumeric(5)
data.append({
- 'name': 'test_policy_{}'.format(uniq),
- 'description': 'Test Policy {}'.format(uniq),
+ 'name': f'test_policy_{uniq}',
+ 'description': f'Test Policy {uniq}',
'mode': 'compliance',
'towhat': 'ExtManagementSystem',
'conditions_ids': [conditions_response[0].id, conditions_response[1].id],
@@ -598,7 +598,7 @@ def get_dialog_service_name(appliance, service_request, *item_names):
"""
def _regex_parse_name(items, message):
for item in items:
- match = re.search(r'\[({}[0-9-]*)\] '.format(item), message)
+ match = re.search(fr'\[({item}[0-9-]*)\] ', message)
if match:
return match.group(1)
else:
@@ -616,7 +616,7 @@ def custom_button_sets(request, appliance, button_type, icon="fa-user", color="#
"name": fauxfactory.gen_alphanumeric(start="grp_"),
"description": fauxfactory.gen_alphanumeric(15, start="grp_desc_"),
"set_data": {
- "button_icon": "ff {}".format(icon),
+ "button_icon": f"ff {icon}",
"button_color": color,
"display": True,
"applies_to_class": button_type,
@@ -638,7 +638,7 @@ def custom_buttons(
"name": fauxfactory.gen_alphanumeric(12, start="btn_desc_"),
"options": {
"button_color": color,
- "button_icon": "ff {}".format(icon),
+ "button_icon": f"ff {icon}",
"display": display,
},
"resource_action": {"ae_class": "PROCESS", "ae_namespace": "SYSTEM"},
diff --git a/cfme/scripting/appliance.py b/cfme/scripting/appliance.py
index 5667a2db92..2d5b867df0 100644
--- a/cfme/scripting/appliance.py
+++ b/cfme/scripting/appliance.py
@@ -47,11 +47,11 @@ def upgrade_appliance(appliance_ip, cfme_only, update_to):
)
update_url = supported_version_repo_map[update_to]
if appliance_ip:
- print('Connecting to {}'.format(appliance_ip))
+ print(f'Connecting to {appliance_ip}')
else:
print('Fetching appliance from env.local.yaml')
app = get_appliance(appliance_ip)
- assert app.version > '5.7', "{} is not supported, must be 5.7 or higher".format(app.version)
+ assert app.version > '5.7', f"{app.version} is not supported, must be 5.7 or higher"
is_major_upgrade = app.version.series() not in update_to
assert not("5.11" in update_to and is_major_upgrade), "Major upgrade for 5.11 Not implemented"
@@ -62,7 +62,7 @@ def upgrade_appliance(appliance_ip, cfme_only, update_to):
urls = cfme_data['basic_info'][update_url]
print('Adding update repo to appliance')
app.ssh_client.run_command(
- "curl {} -o /etc/yum.repos.d/update.repo".format(urls)
+ f"curl {urls} -o /etc/yum.repos.d/update.repo"
)
cfme = '-y'
if cfme_only:
@@ -70,8 +70,8 @@ def upgrade_appliance(appliance_ip, cfme_only, update_to):
print('Stopping EVM')
app.evmserverd.stop()
print('Running yum update')
- result = app.ssh_client.run_command('yum update {}'.format(cfme), timeout=3600)
- assert result.success, "update failed {}".format(result.output)
+ result = app.ssh_client.run_command(f'yum update {cfme}', timeout=3600)
+ assert result.success, f"update failed {result.output}"
if is_major_upgrade:
print('Running database migration')
@@ -94,13 +94,13 @@ def upgrade_appliance(appliance_ip, cfme_only, update_to):
@click.option('--backup', default=None, help='Location of local backup file, including file name')
def backup_migrate(appliance_ip, db_url, keys_url, backup):
"""Restores and migrates database backup on an appliance"""
- print('Connecting to {}'.format(appliance_ip))
+ print(f'Connecting to {appliance_ip}')
app = get_appliance(appliance_ip)
if db_url:
print('Downloading database backup')
result = app.ssh_client.run_command(
- 'curl -o "/evm_db.backup" "{}"'.format(db_url), timeout=30)
- assert result.success, "Failed to download database: {}".format(result.output)
+ f'curl -o "/evm_db.backup" "{db_url}"', timeout=30)
+ assert result.success, f"Failed to download database: {result.output}"
backup = '/evm_db.backup'
else:
backup = backup
@@ -111,18 +111,18 @@ def backup_migrate(appliance_ip, db_url, keys_url, backup):
app.db.create()
print('Restoring database from backup')
result = app.ssh_client.run_command(
- 'pg_restore -v --dbname=vmdb_production {}'.format(backup), timeout=600)
- assert result.success, "Failed to restore new database: {}".format(result.output)
+ f'pg_restore -v --dbname=vmdb_production {backup}', timeout=600)
+ assert result.success, f"Failed to restore new database: {result.output}"
print('Running database migration')
app.db.migrate()
app.db.automate_reset()
if keys_url:
result = app.ssh_client.run_command(
- 'curl -o "/var/www/miq/vmdb/certs/v2_key" "{}v2_key"'.format(keys_url), timeout=15)
- assert result.success, "Failed to download v2_key: {}".format(result.output)
+ f'curl -o "/var/www/miq/vmdb/certs/v2_key" "{keys_url}v2_key"', timeout=15)
+ assert result.success, f"Failed to download v2_key: {result.output}"
result = app.ssh_client.run_command(
- 'curl -o "/var/www/miq/vmdb/GUID" "{}GUID"'.format(keys_url), timeout=15)
- assert result.success, "Failed to download GUID: {}".format(result.output)
+ f'curl -o "/var/www/miq/vmdb/GUID" "{keys_url}GUID"', timeout=15)
+ assert result.success, f"Failed to download GUID: {result.output}"
else:
app.db.fix_auth_key()
app.db.fix_auth_dbyml()
@@ -183,7 +183,7 @@ def fn(method, *args, **kwargs):
for method in methods_to_install:
command = click.Command(
method.replace('_', '-'),
- short_help='Returns the {} property'.format(method),
+ short_help=f'Returns the {method} property',
callback=partial(fn, method), params=[
click.Argument(['appliance_ip'], default=None, required=False)])
main.add_command(command)
diff --git a/cfme/scripting/bz.py b/cfme/scripting/bz.py
index bf20978a58..70a667067c 100644
--- a/cfme/scripting/bz.py
+++ b/cfme/scripting/bz.py
@@ -60,7 +60,7 @@ def get_report(directory):
try:
with open("bz-report.yaml", "r") as stream:
info = yaml.load(stream, Loader=yaml.BaseLoader)
- except IOError:
+ except OSError:
msg = (
"ERROR: File bz-report.yaml not found, something went wrong during report generation.\n"
" Likely no BZs were found in {} with 'automates'/'coverage',"
@@ -273,7 +273,7 @@ def coverage(directory, set_bzs, bz_status):
STATUS[bz_status]["coverage_text"])
)
for bz in bz_list:
- click.echo(" id: {}, qe_test_coverage: {}".format(bz.id, bz.qe_test_coverage))
+ click.echo(f" id: {bz.id}, qe_test_coverage: {bz.qe_test_coverage}")
if set_bzs:
click.echo("Setting qe_test_coverage on the above BZs to '+'...")
diff --git a/cfme/scripting/conf.py b/cfme/scripting/conf.py
index 9af44f4422..753d108fdf 100644
--- a/cfme/scripting/conf.py
+++ b/cfme/scripting/conf.py
@@ -74,7 +74,7 @@ def encrypt(conf_name, delete):
"""Function to encrypt a given conf file"""
conf_name = conf_name.strip()
yaycl_crypt.encrypt_yaml(conf, conf_name, delete=delete)
- print('{} conf encrypted'.format(conf_name))
+ print(f'{conf_name} conf encrypted')
if not delete:
print('WARNING: unencrypted file left which will override encrypted')
@@ -92,12 +92,12 @@ def decrypt(conf_name, delete, skip):
yaycl_crypt.decrypt_yaml(conf, conf_name, delete=delete)
except yaycl_crypt.YayclCryptError as ex:
if skip and 'overwrite' in str(ex):
- print('SKIPPED {} conf decrypt, decrypted file already exists'.format(conf_name))
+ print(f'SKIPPED {conf_name} conf decrypt, decrypted file already exists')
return
else:
raise
- print('{} conf decrypted'.format(conf_name))
+ print(f'{conf_name} conf decrypted')
if __name__ == "__main__":
diff --git a/cfme/scripting/disable_bytecode.py b/cfme/scripting/disable_bytecode.py
index 2acf097248..e8a18ca044 100644
--- a/cfme/scripting/disable_bytecode.py
+++ b/cfme/scripting/disable_bytecode.py
@@ -10,7 +10,7 @@ def ensure_file_contains(target, content):
if path.exists(target):
with open(target) as fp:
if content not in fp.read():
- print('{target!r} has unexpected content'.format(target=target))
+ print(f'{target!r} has unexpected content')
print('please open the file and add the following:')
print(content)
print("# end")
diff --git a/cfme/scripting/ipyshell.py b/cfme/scripting/ipyshell.py
index 622d64a696..9f46ff949c 100644
--- a/cfme/scripting/ipyshell.py
+++ b/cfme/scripting/ipyshell.py
@@ -20,7 +20,7 @@ def main(no_quickstart):
print('Welcome to IPython designed for running CFME QE code.')
ipython = TerminalInteractiveShell.instance()
for code_import in IMPORTS:
- print('> {}'.format(code_import))
+ print(f'> {code_import}')
ipython.run_cell(code_import)
from cfme.utils.path import conf_path
custom_import_path = conf_path.join('miq_python_startup.py')
diff --git a/cfme/scripting/quickstart/__init__.py b/cfme/scripting/quickstart/__init__.py
index 356bc7a0aa..6c37f42f39 100644
--- a/cfme/scripting/quickstart/__init__.py
+++ b/cfme/scripting/quickstart/__init__.py
@@ -90,7 +90,7 @@ def install_requirements(venv_path, quiet=False):
with open(remember_file, 'r') as fp:
last_hash = fp.read()
elif os.path.exists(remember_file):
- sys.exit("ERROR: {} is required to be a file".format(remember_file))
+ sys.exit(f"ERROR: {remember_file} is required to be a file")
else:
last_hash = None
if last_hash == current_hash:
diff --git a/cfme/scripting/quickstart/system.py b/cfme/scripting/quickstart/system.py
index 826934c4a9..210032577b 100644
--- a/cfme/scripting/quickstart/system.py
+++ b/cfme/scripting/quickstart/system.py
@@ -51,7 +51,7 @@
if version:
OS_VERSION = version.group(1).rstrip('\n')
-print('OS_NAME: {}, OS_VERSION: {}'.format(OS_NAME, OS_VERSION))
+print(f'OS_NAME: {OS_NAME}, OS_VERSION: {OS_VERSION}')
RH_BASE = (
" gcc postgresql-devel libxml2-devel libxslt-devel"
diff --git a/cfme/scripting/release.py b/cfme/scripting/release.py
index dd04d5dd1d..f3abf9d1be 100644
--- a/cfme/scripting/release.py
+++ b/cfme/scripting/release.py
@@ -59,7 +59,7 @@
def clean_commit(commit_msg):
replacements = ["1LP", "RFR", "WIP", "WIPTEST", "NOTEST"]
for replacement in replacements:
- commit_msg = commit_msg.replace("[{}]".format(replacement), "")
+ commit_msg = commit_msg.replace(f"[{replacement}]", "")
return commit_msg.strip(" ")
diff --git a/cfme/scripting/setup_env.py b/cfme/scripting/setup_env.py
index 8833de0b2e..5e2471ba64 100644
--- a/cfme/scripting/setup_env.py
+++ b/cfme/scripting/setup_env.py
@@ -68,14 +68,14 @@ def setup_distributed_env(cfme_version, provider_type, provider, lease, desc):
apps[0].appliance_console.run_commands(command_set0)
apps[0].evmserverd.wait_for_running()
apps[0].wait_for_web_ui()
- print("VMDB appliance provisioned and configured {}".format(ip0))
+ print(f"VMDB appliance provisioned and configured {ip0}")
command_set1 = ('ap', '', opt, '2', ip0, '', pwd, '', '3') + port + ('', '',
pwd, TimedCommand(pwd, 360), '')
apps[1].appliance_console.run_commands(command_set1)
apps[1].evmserverd.wait_for_running()
apps[1].wait_for_web_ui()
- print("Non-VMDB appliance provisioned and configured {}".format(ip1))
- print("Appliance pool lease time is {}".format(lease))
+ print(f"Non-VMDB appliance provisioned and configured {ip1}")
+ print(f"Appliance pool lease time is {lease}")
@main.command('ha', help='Sets up high availability environment')
@@ -102,28 +102,28 @@ def setup_ha_env(cfme_version, provider_type, provider, lease, desc):
command_set0 = ('ap', '', '7', '1', '1', '2', 'y', pwd, TimedCommand(pwd, 360), '')
apps[0].appliance_console.run_commands(command_set0)
wait_for(lambda: apps[0].db.is_dedicated_active)
- print("Dedicated database provisioned and configured {}".format(ip0))
+ print(f"Dedicated database provisioned and configured {ip0}")
command_set1 = ('ap', '', '7', '1', '2', '1', 'y') + port + ('', '', pwd,
TimedCommand(pwd, 360), '')
apps[1].appliance_console.run_commands(command_set1)
apps[1].evmserverd.wait_for_running()
apps[1].wait_for_web_ui()
- print("Non-VMDB appliance provisioned and region created {}".format(ip1))
+ print(f"Non-VMDB appliance provisioned and region created {ip1}")
command_set2 = ('ap', '', '8', '1', '1', '', '', pwd, pwd, ip0, 'y', '')
apps[0].appliance_console.run_commands(command_set2)
- print("Primary HA node configured {}".format(ip0))
+ print(f"Primary HA node configured {ip0}")
command_set3 = ('ap', '', '8', '2', '1', '2', '', '', pwd, pwd, ip0, ip2, 'y',
TimedCommand('y', 300), '')
apps[2].appliance_console.run_commands(command_set3)
- print("Secondary HA node provision and configured {}".format(ip2))
+ print(f"Secondary HA node provision and configured {ip2}")
command_set4 = ('ap', '', '10', '1', '')
apps[1].appliance_console.run_commands(command_set4)
print("HA configuration complete")
- print("Appliance pool lease time is {}".format(lease))
+ print(f"Appliance pool lease time is {lease}")
@main.command('replicated', help='Sets up replicated environment')
@@ -165,7 +165,7 @@ def setup_replication_env(cfme_version, provider_type, provider, lease, sprout_p
count=required_app_count, cfme_version=cfme_version,
provider_type=provider_type, provider=provider, lease_time=lease_time
)
- print("Appliance pool lease time is {}".format(lease))
+ print(f"Appliance pool lease time is {lease}")
sprout_client.set_pool_description(request_id, desc)
print("Appliances Provisioned")
print("Configuring Replicated Environment")
@@ -179,7 +179,7 @@ def setup_replication_env(cfme_version, provider_type, provider, lease, sprout_p
apps[0].appliance_console.run_commands(command_set0)
apps[0].evmserverd.wait_for_running()
apps[0].wait_for_web_ui()
- print("Done: Global @ {}".format(ip0))
+ print(f"Done: Global @ {ip0}")
print("Remote Appliance Configuration")
command_set1 = ('ap', '', opt, '2', ip0, '', pwd, '', '1', 'y', '1', 'n', '1', pwd,
@@ -187,7 +187,7 @@ def setup_replication_env(cfme_version, provider_type, provider, lease, sprout_p
apps[1].appliance_console.run_commands(command_set1)
apps[1].evmserverd.wait_for_running()
apps[1].wait_for_web_ui()
- print("Done: Remote @ {}".format(ip1))
+ print(f"Done: Remote @ {ip1}")
if remote_worker:
print("Remote Worker Appliance Configuration")
@@ -196,7 +196,7 @@ def setup_replication_env(cfme_version, provider_type, provider, lease, sprout_p
apps[2].appliance_console.run_commands(command_set2)
apps[2].evmserverd.wait_for_running()
apps[2].wait_for_web_ui()
- print("Done: Remote Worker @ {}".format(ip2))
+ print(f"Done: Remote Worker @ {ip2}")
print("Configuring Replication")
print("Setup - Replication on remote appliance")
@@ -248,7 +248,7 @@ def setup_multiregion_env(cfme_version, provider_type, provider, lease, sprout_p
count=required_app_count, cfme_version=cfme_version,
provider_type=provider_type, provider=provider, lease_time=lease_time
)
- print("Appliance pool lease time is {}".format(lease))
+ print(f"Appliance pool lease time is {lease}")
sprout_client.set_pool_description(request_id, desc)
print("Appliances Provisioned")
print("Configuring Replicated Environment")
@@ -272,7 +272,7 @@ def setup_multiregion_env(cfme_version, provider_type, provider, lease, sprout_p
global_app.evmserverd.wait_for_running()
global_app.wait_for_web_ui()
- print("Done: Global @ {}".format(gip))
+ print(f"Done: Global @ {gip}")
for num, app in enumerate(remote_apps):
region_n = str((num + 1) * 10)
@@ -290,7 +290,7 @@ def setup_multiregion_env(cfme_version, provider_type, provider, lease, sprout_p
app.appliance_console_cli.configure_appliance_internal_fetch_key(**app_params)
app.evmserverd.wait_for_running()
app.wait_for_web_ui()
- print("Done: Remote @ {}, region: {}".format(app.hostname, region_n))
+ print(f"Done: Remote @ {app.hostname}, region: {region_n}")
print("Configuring Replication")
print("Setup - Replication on remote appliance")
@@ -306,7 +306,7 @@ def setup_multiregion_env(cfme_version, provider_type, provider, lease, sprout_p
for app, prov_id in zip(cycle(remote_apps), add_prov):
stack.push(app)
prov = get_crud(prov_id)
- print("Adding provider {} to appliance {}".format(prov_id, app.hostname))
+ print(f"Adding provider {prov_id} to appliance {app.hostname}")
prov.create_rest()
stack.pop()
diff --git a/cfme/services/catalogs/catalog_items/__init__.py b/cfme/services/catalogs/catalog_items/__init__.py
index 418d68bec7..2eb24fee2a 100644
--- a/cfme/services/catalogs/catalog_items/__init__.py
+++ b/cfme/services/catalogs/catalog_items/__init__.py
@@ -366,7 +366,7 @@ def delete(self):
assert view.is_displayed
view.flash.assert_success_message(VersionPick(
{LOWEST: 'The selected Catalog Item was deleted',
- '5.11': 'The catalog item "{}" has been successfully deleted'.format(self.name)}))
+ '5.11': f'The catalog item "{self.name}" has been successfully deleted'}))
def copy(self, name=None):
view = navigate_to(self, 'Copy')
@@ -408,7 +408,7 @@ def button_group_exists(self, name):
path = view.catalog_items.tree.read()
# For 5.11+ no group tagging hover points group or button
- path.extend(["Actions", "{} (Group)".format(name)])
+ path.extend(["Actions", f"{name} (Group)"])
try:
view.catalog_items.tree.fill(path)
@@ -421,7 +421,7 @@ def delete_button_group(self, name):
path = view.catalog_items.tree.read()
# For 5.11+ no group tagging hover points group or button
- path.extend(["Actions", "{} (Group)".format(name)])
+ path.extend(["Actions", f"{name} (Group)"])
view.catalog_items.tree.fill(path)
view.configuration.item_select("Remove this Button Group", handle_alert=True)
view.flash.assert_no_error()
diff --git a/cfme/services/catalogs/catalog_items/ansible_catalog_items.py b/cfme/services/catalogs/catalog_items/ansible_catalog_items.py
index feb9f4024b..1cc7cda6a9 100644
--- a/cfme/services/catalogs/catalog_items/ansible_catalog_items.py
+++ b/cfme/services/catalogs/catalog_items/ansible_catalog_items.py
@@ -36,7 +36,7 @@ def fill(self, value):
# Some BootstrapSelects appears on the page only if another select changed. Therefore we
# should wait until it appears and only then we can fill it.
self.wait_displayed()
- return super(BootstrapSelect, self).fill(value)
+ return super().fill(value)
class ActionsCell(View):
diff --git a/cfme/services/catalogs/catalog_items/catalog_bundles.py b/cfme/services/catalogs/catalog_items/catalog_bundles.py
index 0b2d332db6..818b7c655d 100644
--- a/cfme/services/catalogs/catalog_items/catalog_bundles.py
+++ b/cfme/services/catalogs/catalog_items/catalog_bundles.py
@@ -94,7 +94,7 @@ def update(self, updates):
'Catalog Bundle "{}" was saved'.format(updates.get('name', self.name)))
else:
view.flash.assert_success_message(
- 'Edit of Catalog Bundle"{}" was cancelled by the user'.format(self.name))
+ f'Edit of Catalog Bundle"{self.name}" was cancelled by the user')
view = self.create_view(DetailsCatalogItemView, override=updates, wait='10s')
view.flash.assert_no_error()
@@ -145,7 +145,7 @@ def create(self, name, catalog_items=None, catalog=None, description=None, displ
for cat_item in catalog_items:
view.resources.fill({'select_resource': cat_item})
view.add_button.click()
- view.flash.assert_success_message('Catalog Bundle "{}" was added'.format(name))
+ view.flash.assert_success_message(f'Catalog Bundle "{name}" was added')
view = self.create_view(AllCatalogItemView, wait='10s')
view.flash.assert_no_error()
return self.instantiate(name, catalog_items=catalog_items, catalog=catalog,
diff --git a/cfme/services/catalogs/orchestration_template.py b/cfme/services/catalogs/orchestration_template.py
index dfb9825195..e4028d7bea 100644
--- a/cfme/services/catalogs/orchestration_template.py
+++ b/cfme/services/catalogs/orchestration_template.py
@@ -34,7 +34,7 @@ class OrchestrationTemplatesView(ServicesCatalogView):
@property
def is_displayed(self):
return (
- super(OrchestrationTemplatesView, self).is_displayed and
+ super().is_displayed and
self.title.text == 'All Orchestration Templates' and
self.orchestration_templates.is_opened and
self.orchestration_templates.tree.currently_selected == ["All Orchestration Templates"])
diff --git a/cfme/services/myservice/ssui.py b/cfme/services/myservice/ssui.py
index eb0d1f7b05..d1153fceec 100644
--- a/cfme/services/myservice/ssui.py
+++ b/cfme/services/myservice/ssui.py
@@ -280,7 +280,7 @@ def retire(self):
view.retire.click()
if self.appliance.version < "5.10":
view = self.create_view(MyServicesView, wait='20s')
- assert view.notification.assert_message("{} was retired.".format(self.name))
+ assert view.notification.assert_message(f"{self.name} was retired.")
else:
view = self.create_view(DetailsMyServiceView, wait='20s')
assert view.notification.assert_message("Service Retire - Request Created")
diff --git a/cfme/services/myservice/ui.py b/cfme/services/myservice/ui.py
index e0d47f899d..38d3445a68 100644
--- a/cfme/services/myservice/ui.py
+++ b/cfme/services/myservice/ui.py
@@ -224,7 +224,7 @@ def is_displayed(self):
return (
self.in_myservices and
self.myservice.is_opened and
- self.title.text == 'Reconfigure Service "{}"'.format(name)
+ self.title.text == f'Reconfigure Service "{name}"'
)
@@ -312,7 +312,7 @@ def delete(self):
view.toolbar.configuration.item_select("Remove Service from Inventory", handle_alert=True)
view = self.create_view(MyServicesView, wait='5s')
view.flash.assert_no_error()
- view.flash.assert_success_message('Service "{}": Delete successful'.format(self.name))
+ view.flash.assert_success_message(f'Service "{self.name}": Delete successful')
@MiqImplementationContext.external_for(MyService.status.getter, ViaUI)
@@ -352,7 +352,7 @@ def check_vm_add(self, vm):
@MiqImplementationContext.external_for(MyService.download_file, ViaUI)
def download_file(self, extension):
view = navigate_to(self, 'All')
- view.toolbar.download.item_select('Download as {}'.format(extension))
+ view.toolbar.download.item_select(f'Download as {extension}')
view.flash.assert_no_error()
diff --git a/cfme/services/requests.py b/cfme/services/requests.py
index 79df76e548..cdb829ab84 100644
--- a/cfme/services/requests.py
+++ b/cfme/services/requests.py
@@ -58,7 +58,7 @@ def _finished():
'Retry' not in self.rest.message)
def last_message():
- logger.info("Last Request message: '{}'".format(self.rest.message))
+ logger.info(f"Last Request message: '{self.rest.message}'")
wait_for(_finished, num_sec=num_sec, delay=delay, fail_func=last_message,
message="Request finished")
@@ -71,7 +71,7 @@ def _finished():
'Retry' not in self.row.last_message.text)
def last_message():
- logger.info("Last Request message in UI: '{}'".format(self.row.last_message))
+ logger.info(f"Last Request message in UI: '{self.row.last_message}'")
wait_for(_finished, num_sec=num_sec, delay=delay, fail_func=last_message,
message="Request finished")
@@ -204,7 +204,7 @@ def remove_request_rest(self):
request[0].action.delete()
else:
raise NotImplementedError(
- "{} does not support delete operation via REST".format(self.rest.request_type)
+ f"{self.rest.request_type} does not support delete operation via REST"
)
@variable(alias='rest')
@@ -302,7 +302,7 @@ def find_request(self, cells, partial_check=False):
for key in cells.keys():
for column_name, column_text in column_list.items():
if key == column_text:
- cells['{}{}'.format(column_name, contains)] = cells.pop(key)
+ cells[f'{column_name}{contains}'] = cells.pop(key)
break
for _ in self.paginator.pages():
diff --git a/cfme/storage/manager.py b/cfme/storage/manager.py
index 6a2f3c3dd0..4b00ae651e 100644
--- a/cfme/storage/manager.py
+++ b/cfme/storage/manager.py
@@ -161,7 +161,7 @@ def delete(self):
"""Delete storage manager"""
view = navigate_to(self, 'Details')
view.toolbar.configuration.item_select(
- 'Remove this {} from Inventory'.format(self.storage_title),
+ f'Remove this {self.storage_title} from Inventory',
handle_alert=True
)
@@ -255,7 +255,7 @@ def step(self, *args, **kwargs):
row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True)
row.click()
except NoSuchElementException:
- raise ItemNotFound('Could not locate {}'.format(self.obj.name))
+ raise ItemNotFound(f'Could not locate {self.obj.name}')
@navigator.register(StorageManager, 'Volumes')
@@ -269,7 +269,7 @@ def step(self, *args, **kwargs):
if volume_count > 0:
self.prerequisite_view.entities.relationships.click_at("Cloud Volumes")
else:
- raise ItemNotFound('{} has no volumes'.format(self.obj.name))
+ raise ItemNotFound(f'{self.obj.name} has no volumes')
@navigator.register(StorageManager, 'AddVolume')
diff --git a/cfme/storage/object_store_container.py b/cfme/storage/object_store_container.py
index a6a65ef260..5db5e8bd92 100644
--- a/cfme/storage/object_store_container.py
+++ b/cfme/storage/object_store_container.py
@@ -178,4 +178,4 @@ def step(self, *args, **kwargs):
try:
self.prerequisite_view.entities.get_entity(key=self.obj.key, surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound('Could not locate container {}'.format(self.obj.key))
+ raise ItemNotFound(f'Could not locate container {self.obj.key}')
diff --git a/cfme/storage/object_store_object.py b/cfme/storage/object_store_object.py
index 2fbd443e3a..536e9d7391 100644
--- a/cfme/storage/object_store_object.py
+++ b/cfme/storage/object_store_object.py
@@ -165,7 +165,7 @@ def delete(self, *objects):
try:
view.entities.get_entity(key=obj.key, surf_pages=True).ensure_checked()
except ItemNotFound:
- raise ItemNotFound('Could not locate object {}'.format(obj.key))
+ raise ItemNotFound(f'Could not locate object {obj.key}')
view.toolbar.configuration.item_select('Remove Object Storage Objects', handle_alert=True)
view.flash.assert_no_error()
@@ -190,4 +190,4 @@ def step(self, *args, **kwargs):
try:
self.prerequisite_view.entities.get_entity(key=self.obj.key, surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound('Could not locate object {}'.format(self.obj.key))
+ raise ItemNotFound(f'Could not locate object {self.obj.key}')
diff --git a/cfme/storage/volume.py b/cfme/storage/volume.py
index 020bb054f2..882d728d1c 100644
--- a/cfme/storage/volume.py
+++ b/cfme/storage/volume.py
@@ -317,7 +317,7 @@ def create_backup(self, name, incremental=None, force=None):
view.force.fill(force)
view.save.click()
- view.flash.assert_success_message('Backup for Cloud Volume "{}" created'.format(self.name))
+ view.flash.assert_success_message(f'Backup for Cloud Volume "{self.name}" created')
wait_for(lambda: self.backups_count > initial_backup_count,
delay=20,
@@ -531,7 +531,7 @@ def delete(self, *volumes):
try:
view.entities.get_entity(name=volume.name).ensure_checked()
except ItemNotFound:
- raise ItemNotFound("Volume {} not found".format(volume.name))
+ raise ItemNotFound(f"Volume {volume.name} not found")
view.toolbar.configuration.item_select('Delete selected Cloud Volumes',
handle_alert=True)
@@ -591,7 +591,7 @@ def step(self, *args, **kwargs):
surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound('Volume {} not found'.format(self.obj.name))
+ raise ItemNotFound(f'Volume {self.obj.name} not found')
@navigator.register(VolumeCollection, 'Add')
diff --git a/cfme/storage/volume_backup.py b/cfme/storage/volume_backup.py
index 706c316382..3f64b992b5 100644
--- a/cfme/storage/volume_backup.py
+++ b/cfme/storage/volume_backup.py
@@ -159,7 +159,7 @@ def restore(self, name):
view = navigate_to(self, 'Restore')
view.volume_name.fill(name)
view.save.click()
- view.flash.assert_success_message('Restoring Cloud Volume "{}"'.format(self.name))
+ view.flash.assert_success_message(f'Restoring Cloud Volume "{self.name}"')
def refresh(self):
self.provider.refresh_provider_relationships()
@@ -243,7 +243,7 @@ def delete(self, *backups, **kwargs):
try:
view.entities.get_entity(name=backup.name).ensure_checked()
except ItemNotFound:
- raise ItemNotFound("Volume backup {} not found".format(backup.name))
+ raise ItemNotFound(f"Volume backup {backup.name} not found")
view.toolbar.configuration.item_select('Delete selected Backups', handle_alert=True)
@@ -280,7 +280,7 @@ def step(self, *args, **kwargs):
self.prerequisite_view.entities.get_entity(name=self.obj.name,
surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound('Could not locate volume backup {}'.format(self.obj.name))
+ raise ItemNotFound(f'Could not locate volume backup {self.obj.name}')
@navigator.register(VolumeBackup, 'EditTagsFromDetails')
diff --git a/cfme/storage/volume_snapshot.py b/cfme/storage/volume_snapshot.py
index 8a7fadb0f9..3e04ea1c97 100644
--- a/cfme/storage/volume_snapshot.py
+++ b/cfme/storage/volume_snapshot.py
@@ -256,7 +256,7 @@ def step(self, *args, **kwargs):
surf_pages=True).click()
except ItemNotFound:
raise ItemNotFound(
- 'Could not locate volume snapshot {}'.format(self.obj.name)
+ f'Could not locate volume snapshot {self.obj.name}'
)
diff --git a/cfme/storage/volume_type.py b/cfme/storage/volume_type.py
index edec1c4375..46b428c3b5 100644
--- a/cfme/storage/volume_type.py
+++ b/cfme/storage/volume_type.py
@@ -107,4 +107,4 @@ def step(self, *args, **kwargs):
try:
self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True).click()
except ItemNotFound:
- raise ItemNotFound('Volume Type {} not found'.format(self.obj.name))
+ raise ItemNotFound(f'Volume Type {self.obj.name} not found')
diff --git a/cfme/test_framework/appliance.py b/cfme/test_framework/appliance.py
index 4bc0008e6d..2ff5fd3cd6 100644
--- a/cfme/test_framework/appliance.py
+++ b/cfme/test_framework/appliance.py
@@ -27,7 +27,7 @@ def appliances_from_cli(cli_appliances, appliance_version):
parsed_url = urlparse(appliance_data['hostname'])
if not parsed_url.hostname:
raise ValueError(
- "Invalid appliance url: {}".format(appliance_data)
+ f"Invalid appliance url: {appliance_data}"
)
appliance = appliance_data.copy()
@@ -75,7 +75,7 @@ def pytest_configure(config):
if not stack.top:
for appliance in appliances:
- reporter.write_line('* {!r}'.format(appliance), cyan=True)
+ reporter.write_line(f'* {appliance!r}', cyan=True)
appliance = appliances[0]
stack.push(appliance)
@@ -93,7 +93,7 @@ def pytest_unconfigure(config):
@attr.s(eq=False)
-class ApplianceHolderPlugin(object):
+class ApplianceHolderPlugin:
held_appliance = attr.ib()
appliances = attr.ib(default=attr.Factory(list))
diff --git a/cfme/test_framework/appliance_hooks.py b/cfme/test_framework/appliance_hooks.py
index 99a392d8b1..f97d292b5c 100644
--- a/cfme/test_framework/appliance_hooks.py
+++ b/cfme/test_framework/appliance_hooks.py
@@ -5,7 +5,7 @@ def pytest_addhooks(pluginmanager):
pluginmanager.add_hookspecs(ApplianceHooks)
-class ApplianceHooks(object):
+class ApplianceHooks:
def pytest_appliance_setup(self, config):
holder = config.pluginmanager.getplugin('appliance-holder')
appliance = holder.held_appliance
diff --git a/cfme/test_framework/appliance_log_collector.py b/cfme/test_framework/appliance_log_collector.py
index 05c7ece699..2d0621c6f7 100644
--- a/cfme/test_framework/appliance_log_collector.py
+++ b/cfme/test_framework/appliance_log_collector.py
@@ -89,7 +89,7 @@ def collect_logs(app):
with app.ssh_client as ssh_client:
logger.info(f'Starting log collection on appliance {app.hostname}')
- tarred_dir_name = 'log-collector-{}'.format(app.hostname)
+ tarred_dir_name = f'log-collector-{app.hostname}'
# wrap the files in ls, redirecting stderr, to ignore files that don't exist
tar_dir_path = os.path.join(local_dir.strpath, tarred_dir_name)
tarball_path = f'{tar_dir_path}.tar.gz'
diff --git a/cfme/test_framework/appliance_police.py b/cfme/test_framework/appliance_police.py
index 3eeabe79ac..25a04ddbdd 100644
--- a/cfme/test_framework/appliance_police.py
+++ b/cfme/test_framework/appliance_police.py
@@ -15,7 +15,7 @@ class AppliancePoliceException(Exception):
port = attr.ib()
def __str__(self):
- return "{} (port {})".format(self.message, self.port)
+ return f"{self.message} (port {self.port})"
@pytest.fixture(autouse=True, scope="function")
@@ -65,7 +65,7 @@ def appliance_police(appliance):
# Regardles of the exception raised, we didn't return anywhere above
# time to call a human
- msg = 'Help! My appliance {} crashed with: {}'.format(appliance.url, e_message)
+ msg = f'Help! My appliance {appliance.url} crashed with: {e_message}'
store.slave_manager.message(msg)
if 'appliance_police_recipients' in rdb:
rdb_kwargs = {
diff --git a/cfme/test_framework/config.py b/cfme/test_framework/config.py
index 4d1c948acf..aa93a4af99 100644
--- a/cfme/test_framework/config.py
+++ b/cfme/test_framework/config.py
@@ -8,7 +8,7 @@
import yaycl
-class Configuration(object):
+class Configuration:
"""
holds the current configuration
"""
@@ -48,7 +48,7 @@ def get_config(self, name):
@attr.s(eq=False)
-class DeprecatedConfigWrapper(object):
+class DeprecatedConfigWrapper:
"""
a wrapper that provides the old :code:``utils.conf`` api
"""
@@ -58,7 +58,7 @@ class DeprecatedConfigWrapper(object):
def __getattr__(self, key):
if self._warn:
warnings.warn(
- 'the configuration module {} will be deprecated'.format(key),
+ f'the configuration module {key} will be deprecated',
category=DeprecationWarning,
stacklevel=2,
)
@@ -71,7 +71,7 @@ def runtime(self):
def __getitem__(self, key):
if self._warn:
warnings.warn(
- 'the configuration module {} will be deprecated'.format(key),
+ f'the configuration module {key} will be deprecated',
category=DeprecationWarning,
stacklevel=2,
)
diff --git a/cfme/test_framework/pytest_plugin.py b/cfme/test_framework/pytest_plugin.py
index b6875e7b0b..9cb779dd69 100644
--- a/cfme/test_framework/pytest_plugin.py
+++ b/cfme/test_framework/pytest_plugin.py
@@ -26,7 +26,7 @@ def pytest_collection_finish(session):
for reason, value in store.uncollection_stats.items():
store.terminalreporter.write(
- " {}: {}\n".format(reason, value), bold=True)
+ f" {reason}: {value}\n", bold=True)
store.terminalreporter.write(
" {} tests left after all uncollections\n".format(len(session.items)),
bold=True)
diff --git a/cfme/test_framework/sprout/client.py b/cfme/test_framework/sprout/client.py
index 997bc18aec..9c77d44dc8 100644
--- a/cfme/test_framework/sprout/client.py
+++ b/cfme/test_framework/sprout/client.py
@@ -23,7 +23,7 @@ class AuthException(SproutException):
@attr.s
-class APIMethodCall(object):
+class APIMethodCall:
_client = attr.ib()
_method_name = attr.ib()
@@ -32,7 +32,7 @@ def __call__(self, *args, **kwargs):
@attr.s
-class SproutClient(object):
+class SproutClient:
_proto = attr.ib(default="http")
_host = attr.ib(default="localhost")
_port = attr.ib(default=8000)
@@ -41,7 +41,7 @@ class SproutClient(object):
@property
def api_entry(self):
- return "{}://{}:{}/{}".format(self._proto, self._host, self._port, self._entry)
+ return f"{self._proto}://{self._host}:{self._port}/{self._entry}"
def _post(self, **data):
return requests.post(self.api_entry, data=json.dumps(data))
@@ -62,7 +62,7 @@ def call_method(self, name, *args, **kwargs):
"args": args,
"kwargs": kwargs,
}
- logger.info("SPROUT: Called {} with {} {}".format(name, args, kwargs))
+ logger.info(f"SPROUT: Called {name} with {args} {kwargs}")
if self._auth is not None:
req_data["auth"] = self._auth
result = self._call_post(**req_data)
@@ -127,7 +127,7 @@ def provision_appliances(
wait_for(
lambda: self.call_method('request_check', str(request_id))['finished'],
num_sec=wait_time,
- message='provision {} appliance(s) from sprout'.format(count))
+ message=f'provision {count} appliance(s) from sprout')
data = self.call_method('request_check', str(request_id))
logger.debug(data)
appliances = []
diff --git a/cfme/test_framework/sprout/plugin.py b/cfme/test_framework/sprout/plugin.py
index e20b349f0d..f423d2edd3 100644
--- a/cfme/test_framework/sprout/plugin.py
+++ b/cfme/test_framework/sprout/plugin.py
@@ -191,14 +191,14 @@ def mangle_in_sprout_appliances(config):
conf.runtime["cfme_data"]["basic_info"]["appliance_template"] = template_name
log.info("appliance_template: %s", template_name)
with project_path.join('.appliance_template').open('w') as template_file:
- template_file.write('export appliance_template="{}"'.format(template_name))
+ template_file.write(f'export appliance_template="{template_name}"')
log.info("Sprout setup finished.")
config.pluginmanager.register(ShutdownPlugin())
@attr.s
-class SproutProvisioningRequest(object):
+class SproutProvisioningRequest:
"""data holder for provisioning metadata"""
group = attr.ib()
@@ -236,7 +236,7 @@ def from_config(cls, config):
@attr.s
-class SproutManager(object):
+class SproutManager:
sprout_user_key = attr.ib(default=None)
pool = attr.ib(init=False, default=None)
lease_time = attr.ib(init=False, default=None, repr=False)
@@ -385,7 +385,7 @@ def pytest_addhooks(pluginmanager):
pluginmanager.add_hookspecs(NewHooks)
-class ShutdownPlugin(object):
+class ShutdownPlugin:
def pytest_miq_node_shutdown(self, config, nodeinfo):
if config.getoption('ui_coverage'):
@@ -396,7 +396,7 @@ def pytest_miq_node_shutdown(self, config, nodeinfo):
if nodeinfo:
netloc = urlparse(nodeinfo).netloc
ip_address = netloc.split(":")[0]
- log.debug("Trying to end appliance {}".format(ip_address))
+ log.debug(f"Trying to end appliance {ip_address}")
if config.getoption('--use-sprout'):
try:
call_method = config._sprout_mgr.client.call_method
@@ -413,6 +413,6 @@ def pytest_miq_node_shutdown(self, config, nodeinfo):
log.debug('The IP address was not present - not terminating any appliance')
-class NewHooks(object):
+class NewHooks:
def pytest_miq_node_shutdown(self, config, nodeinfo):
pass
diff --git a/cfme/tests/ansible/test_embedded_ansible_actions.py b/cfme/tests/ansible/test_embedded_ansible_actions.py
index abfd32ec70..4728e8c00c 100644
--- a/cfme/tests/ansible/test_embedded_ansible_actions.py
+++ b/cfme/tests/ansible/test_embedded_ansible_actions.py
@@ -42,7 +42,7 @@ def policy_for_testing(appliance, create_vm_modscope, provider, ansible_action):
policy = appliance.collections.policies.create(
VMControlPolicy,
fauxfactory.gen_alpha(15, start="policy_"),
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name)
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {vm.name})"
)
policy.assign_actions_to_event("Tag Complete", [ansible_action.description])
policy_profile = appliance.collections.policy_profiles.create(
diff --git a/cfme/tests/ansible/test_embedded_ansible_automate.py b/cfme/tests/ansible/test_embedded_ansible_automate.py
index adca72573a..2d870be468 100644
--- a/cfme/tests/ansible/test_embedded_ansible_automate.py
+++ b/cfme/tests/ansible/test_embedded_ansible_automate.py
@@ -111,7 +111,7 @@ def alert(appliance, management_event_instance):
def alert_profile(appliance, alert, create_vm_modscope):
_alert_profile = appliance.collections.alert_profiles.create(
alert_profiles.VMInstanceAlertProfile,
- "Alert profile for {}".format(create_vm_modscope.name),
+ f"Alert profile for {create_vm_modscope.name}",
alerts=[alert]
)
_alert_profile.assign_to("The Enterprise")
@@ -172,7 +172,7 @@ def test_automate_ansible_playbook_method_type(request, appliance, ansible_repos
appliance=appliance,
request="Call_Instance",
attributes_values={
- "namespace": "{}/{}".format(domain.name, namespace.name),
+ "namespace": f"{domain.name}/{namespace.name}",
"class": klass.name,
"instance": instance.name
}
diff --git a/cfme/tests/ansible/test_embedded_ansible_basic.py b/cfme/tests/ansible/test_embedded_ansible_basic.py
index b32c89ac7a..45480e73cd 100644
--- a/cfme/tests/ansible/test_embedded_ansible_basic.py
+++ b/cfme/tests/ansible/test_embedded_ansible_basic.py
@@ -323,7 +323,7 @@ def test_embed_tower_playbooks_list_changed(appliance, wait_for_ansible):
repo_url,
description=fauxfactory.gen_alpha(15, start="repo_desc_")
)
- playbooks.append(set(playbook.name for playbook in repository.playbooks.all()))
+ playbooks.append({playbook.name for playbook in repository.playbooks.all()})
repository.delete()
assert not set(playbooks[1]).issuperset(set(playbooks[0]))
diff --git a/cfme/tests/ansible/test_embedded_ansible_crud.py b/cfme/tests/ansible/test_embedded_ansible_crud.py
index 5e739d0083..79a17f6b7f 100644
--- a/cfme/tests/ansible/test_embedded_ansible_crud.py
+++ b/cfme/tests/ansible/test_embedded_ansible_crud.py
@@ -37,7 +37,7 @@ def test_embedded_ansible_enable(embedded_appliance):
endpoint = "api" if embedded_appliance.is_pod else "ansibleapi"
assert embedded_appliance.ssh_client.run_command(
- 'curl -kL https://localhost/{endp} | grep "AWX REST API"'.format(endp=endpoint),
+ f'curl -kL https://localhost/{endpoint} | grep "AWX REST API"',
container=embedded_appliance.ansible_pod_name,
)
diff --git a/cfme/tests/ansible/test_embedded_ansible_rest.py b/cfme/tests/ansible/test_embedded_ansible_rest.py
index 4bb0d82c55..7074dba073 100644
--- a/cfme/tests/ansible/test_embedded_ansible_rest.py
+++ b/cfme/tests/ansible/test_embedded_ansible_rest.py
@@ -33,7 +33,7 @@ def repository(appliance, ansible):
repo_name = f"test_repo_{uniq}"
data = {
"name": repo_name,
- "description": "Test Repo {}".format(uniq),
+ "description": f"Test Repo {uniq}",
"manager_resource": {"href": ansible.href},
"related": {},
"scm_type": "git",
@@ -57,7 +57,7 @@ def repository(appliance, ansible):
repo_rest.action.delete()
-class TestReposRESTAPI(object):
+class TestReposRESTAPI:
@pytest.mark.parametrize(
'from_collection', [False, True], ids=['from_detail', 'from_collection'])
def test_edit_repository(self, appliance, repository, from_collection):
@@ -137,7 +137,7 @@ def test_delete_repository_from_collection(self, appliance, repository):
delete_resources_from_collection([repository], not_found=False, num_sec=300, delay=5)
-class TestPayloadsRESTAPI(object):
+class TestPayloadsRESTAPI:
def test_payloads_collection(self, appliance, repository):
"""Checks the configuration_script_payloads collection using REST API.
diff --git a/cfme/tests/ansible/test_embedded_ansible_services.py b/cfme/tests/ansible/test_embedded_ansible_services.py
index 9130b13665..b94320cc6b 100644
--- a/cfme/tests/ansible/test_embedded_ansible_services.py
+++ b/cfme/tests/ansible/test_embedded_ansible_services.py
@@ -161,7 +161,7 @@ def ansible_policy_linked_vm(appliance, create_vm, ansible_linked_vm_action):
policy = appliance.collections.policies.create(
VMControlPolicy,
fauxfactory.gen_alpha(15, start="policy_"),
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(create_vm.name),
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {create_vm.name})",
)
policy.assign_actions_to_event(
"Tag Complete", [ansible_linked_vm_action.description]
@@ -842,7 +842,7 @@ def _revert():
# Searching string '"verbosity"=>0' (example) in evm.log as Standard Output
# is being logging in evm.log
assert log.validate(wait="60s")
- logger.info("Pattern found {}".format(log.matched_patterns))
+ logger.info(f"Pattern found {log.matched_patterns}")
view = navigate_to(ansible_service, "Details")
assert verbosity[0] == view.provisioning.details.get_text_of("Verbosity")
diff --git a/cfme/tests/ansible/test_embedded_ansible_tags.py b/cfme/tests/ansible/test_embedded_ansible_tags.py
index 8b17c43494..cdfabad7bc 100644
--- a/cfme/tests/ansible/test_embedded_ansible_tags.py
+++ b/cfme/tests/ansible/test_embedded_ansible_tags.py
@@ -50,14 +50,14 @@ def _check_tag_place(item, tag_place):
tags = item.get_tags()
soft_assert(
tag in tags,
- "{}: {} not in ({})".format(tag.category.display_name, tag.display_name, tags)
+ f"{tag.category.display_name}: {tag.display_name} not in ({tags})"
)
item.remove_tag(tag=tag, details=tag_place)
tags = item.get_tags()
soft_assert(
tag not in tags,
- "{}: {} should not be in ({})".format(tag.category.display_name, tag.display_name, tags)
+ f"{tag.category.display_name}: {tag.display_name} should not be in ({tags})"
)
return _check_tag_place
diff --git a/cfme/tests/automate/custom_button/__init__.py b/cfme/tests/automate/custom_button/__init__.py
index e21b754e0b..04cdc424cc 100644
--- a/cfme/tests/automate/custom_button/__init__.py
+++ b/cfme/tests/automate/custom_button/__init__.py
@@ -88,7 +88,7 @@ def check_log_requests_count(appliance, parse_str=None):
parse_str = "Attributes - Begin"
count = appliance.ssh_client.run_command(
- "grep -c -w '{parse_str}' /var/www/miq/vmdb/log/automation.log".format(parse_str=parse_str)
+ f"grep -c -w '{parse_str}' /var/www/miq/vmdb/log/automation.log"
)
return int(count.output)
diff --git a/cfme/tests/automate/custom_button/test_cloud_objects.py b/cfme/tests/automate/custom_button/test_cloud_objects.py
index 8bd0e115f3..f5c6911fdf 100644
--- a/cfme/tests/automate/custom_button/test_cloud_objects.py
+++ b/cfme/tests/automate/custom_button/test_cloud_objects.py
@@ -95,7 +95,7 @@ def setup_objs(button_group, provider):
elif obj_type == "CLOUD_NETWORK":
obj = [provider.appliance.collections.cloud_networks.all()[0]]
else:
- logger.error("No object collected for custom button object type '{}'".format(obj_type))
+ logger.error(f"No object collected for custom button object type '{obj_type}'")
return obj
@@ -298,7 +298,7 @@ def test_custom_button_automate_cloud_obj(appliance, request, submit, setup_objs
custom_button_group.item_select(button.text)
diff = "executed" if appliance.version < "5.10" else "launched"
- view.flash.assert_message('"{btn}" was {diff}'.format(btn=button.text, diff=diff))
+ view.flash.assert_message(f'"{button.text}" was {diff}')
# Submit all: single request for all entity execution
# One by one: separate requests for all entity execution
diff --git a/cfme/tests/automate/custom_button/test_container_objects.py b/cfme/tests/automate/custom_button/test_container_objects.py
index e4c0dd2a2c..bcbaeca9ed 100644
--- a/cfme/tests/automate/custom_button/test_container_objects.py
+++ b/cfme/tests/automate/custom_button/test_container_objects.py
@@ -64,10 +64,10 @@ def setup_obj(appliance, provider, button_group):
else:
obj = getattr(appliance.collections, obj_type.lower()).all()[0]
except IndexError:
- pytest.skip("Object not found for {obj} type".format(obj=obj_type))
+ pytest.skip(f"Object not found for {obj_type} type")
if not obj.exists:
- pytest.skip("{obj} object not exist".format(obj=obj_type))
+ pytest.skip(f"{obj_type} object not exist")
return obj
diff --git a/cfme/tests/automate/custom_button/test_generic_objects.py b/cfme/tests/automate/custom_button/test_generic_objects.py
index 10dba37e0d..e7788226c0 100644
--- a/cfme/tests/automate/custom_button/test_generic_objects.py
+++ b/cfme/tests/automate/custom_button/test_generic_objects.py
@@ -52,7 +52,7 @@ def setup_obj(appliance, button_group):
elif obj_type == "TENANT":
obj = appliance.collections.tenants.get_root_tenant()
else:
- logger.error("No object collected for custom button object type '{}'".format(obj_type))
+ logger.error(f"No object collected for custom button object type '{obj_type}'")
return obj
@@ -187,7 +187,7 @@ def test_custom_button_automate_evm_obj(appliance, request, submit, setup_obj, b
custom_button_group.item_select(button.text)
diff = "executed" if appliance.version < "5.10" else "launched"
- view.flash.assert_message('"{btn}" was {diff}'.format(btn=button.text, diff=diff))
+ view.flash.assert_message(f'"{button.text}" was {diff}')
# Submit all: single request for all entity execution
# One by one: separate requests for all entity execution
diff --git a/cfme/tests/automate/custom_button/test_infra_objects.py b/cfme/tests/automate/custom_button/test_infra_objects.py
index c3c3ee888f..8202b37b46 100644
--- a/cfme/tests/automate/custom_button/test_infra_objects.py
+++ b/cfme/tests/automate/custom_button/test_infra_objects.py
@@ -112,7 +112,7 @@ def setup_obj(button_group, provider):
else:
obj = getattr(provider.appliance.collections, obj_type.lower()).all()[0]
except IndexError:
- pytest.skip("Object not found for {obj} type".format(obj=obj_type))
+ pytest.skip(f"Object not found for {obj_type} type")
return obj
@@ -247,7 +247,7 @@ def test_custom_button_automate_infra_obj(appliance, request, submit, setup_obj,
custom_button_group.item_select(button.text)
diff = "executed" if appliance.version < "5.10" else "launched"
- view.flash.assert_message('"{btn}" was {diff}'.format(btn=button.text, diff=diff))
+ view.flash.assert_message(f'"{button.text}" was {diff}')
# Submit all: single request for all entity execution
# One by one: separate requests for all entity execution
diff --git a/cfme/tests/automate/custom_button/test_rest_custom_button.py b/cfme/tests/automate/custom_button/test_rest_custom_button.py
index 70da1345c1..1a000327ca 100644
--- a/cfme/tests/automate/custom_button/test_rest_custom_button.py
+++ b/cfme/tests/automate/custom_button/test_rest_custom_button.py
@@ -42,7 +42,7 @@ def buttons_rest(request, appliance, obj_type):
return response
-class TestCustomButtonRESTAPI(object):
+class TestCustomButtonRESTAPI:
@pytest.fixture(params=["custom_button_sets", "custom_buttons"], ids=["Group", "Button"])
def buttons_groups(self, request, appliance, obj_type):
button_type = CLASS_MAP[obj_type]["rest"]
@@ -155,7 +155,7 @@ def test_edit(self, buttons_groups, appliance, from_detail):
entities, _type = buttons_groups
num_entities = len(entities)
uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_entities)]
- new = [{"name": "Edited_{}".format(u), "description": "Edited_{}".format(u)} for u in uniq]
+ new = [{"name": f"Edited_{u}", "description": f"Edited_{u}"} for u in uniq]
if from_detail:
edited = []
for index in range(num_entities):
diff --git a/cfme/tests/automate/custom_button/test_service_objects.py b/cfme/tests/automate/custom_button/test_service_objects.py
index 4cc997daef..09535f9334 100644
--- a/cfme/tests/automate/custom_button/test_service_objects.py
+++ b/cfme/tests/automate/custom_button/test_service_objects.py
@@ -285,7 +285,7 @@ def test_custom_button_automate_service_obj(
# SSUI not support flash messages
if context is ViaUI:
diff = "executed" if appliance.version < "5.10" else "launched"
- view.flash.assert_message('"{btn}" was {diff}'.format(btn=button.text, diff=diff))
+ view.flash.assert_message(f'"{button.text}" was {diff}')
# Submit all: single request for all entity execution
# One by one: separate requests for all entity execution
diff --git a/cfme/tests/automate/custom_button/test_service_vm_custom_button.py b/cfme/tests/automate/custom_button/test_service_vm_custom_button.py
index 2f488277e8..1fd0968f02 100644
--- a/cfme/tests/automate/custom_button/test_service_vm_custom_button.py
+++ b/cfme/tests/automate/custom_button/test_service_vm_custom_button.py
@@ -224,7 +224,7 @@ def test_custom_button_with_dynamic_dialog_vm(
# `$evm.root['vm']` of dynamic dialog by expected service vm name in automation log
log = LogValidator(
"/var/www/miq/vmdb/log/automation.log",
- matched_patterns=["Attributes - Begin", 'name = "{}"'.format(service.vm_name)],
+ matched_patterns=["Attributes - Begin", f'name = "{service.vm_name}"'],
)
log.start_monitoring()
submit = "submit" if context is ViaUI else "submit_request"
diff --git a/cfme/tests/automate/generic_objects/test_definitions.py b/cfme/tests/automate/generic_objects/test_definitions.py
index a6bcf30012..caedb33d66 100644
--- a/cfme/tests/automate/generic_objects/test_definitions.py
+++ b/cfme/tests/automate/generic_objects/test_definitions.py
@@ -50,15 +50,15 @@ def test_generic_object_definition_crud(appliance, context, soft_assert):
if context.name == 'UI':
view = appliance.browser.create_view(BaseLoggedInPage)
view.flash.assert_success_message(
- 'Generic Object Class "{}" has been successfully added.'.format(definition.name))
+ f'Generic Object Class "{definition.name}" has been successfully added.')
assert definition.exists
with update(definition):
- definition.name = '{}_updated'.format(definition.name)
+ definition.name = f'{definition.name}_updated'
definition.attributes = {"new_address": "string"}
if context.name == 'UI':
view.flash.assert_success_message(
- 'Generic Object Class "{}" has been successfully saved.'.format(definition.name))
+ f'Generic Object Class "{definition.name}" has been successfully saved.')
view = navigate_to(definition, 'Details')
soft_assert(view.summary('Attributes (2)').get_text_of('new_address'))
soft_assert(view.summary('Attributes (2)').get_text_of('addr01'))
@@ -72,7 +72,7 @@ def test_generic_object_definition_crud(appliance, context, soft_assert):
definition.delete()
if context.name == 'UI' and not BZ(bug_id=1644658, forced_streams=["5.10"]).blocks:
view.flash.assert_success_message(
- 'Generic Object Class:"{}" was successfully deleted'.format(definition.name))
+ f'Generic Object Class:"{definition.name}" was successfully deleted')
assert not definition.exists
@@ -146,24 +146,24 @@ def test_import_export_generic_object_definition(request, appliance, gen_obj_def
4. Generic object definition once again exists on the appliance
"""
# Create the generic object directory
- assert appliance.ssh_client.run_command("mkdir {}".format(GEN_OBJ_DIRECTORY)).success
+ assert appliance.ssh_client.run_command(f"mkdir {GEN_OBJ_DIRECTORY}").success
@request.addfinalizer
def cleanup():
- assert appliance.ssh_client.run_command("rm -rf {}".format(GEN_OBJ_DIRECTORY)).success
+ assert appliance.ssh_client.run_command(f"rm -rf {GEN_OBJ_DIRECTORY}").success
# Export the user defined generic object definitions
assert appliance.ssh_client.run_rake_command(
- "evm:export:generic_object_definitions -- --directory {}".format(GEN_OBJ_DIRECTORY)
+ f"evm:export:generic_object_definitions -- --directory {GEN_OBJ_DIRECTORY}"
).success
# Verify the file's information
try:
with appliance.ssh_client.open_sftp().open(
- "{}/{}.yaml".format(GEN_OBJ_DIRECTORY, gen_obj_def_import_export.name)
+ f"{GEN_OBJ_DIRECTORY}/{gen_obj_def_import_export.name}.yaml"
) as f:
data = yaml.safe_load(f)[0]["GenericObjectDefinition"]
- except IOError:
+ except OSError:
pytest.fail(
"IOError: {}/{}.yaml not found on the appliance, "
"exporting the generic object definition failed".format(
diff --git a/cfme/tests/automate/generic_objects/test_instances.py b/cfme/tests/automate/generic_objects/test_instances.py
index d2ccfe38c3..8b080cb8c8 100644
--- a/cfme/tests/automate/generic_objects/test_instances.py
+++ b/cfme/tests/automate/generic_objects/test_instances.py
@@ -96,7 +96,7 @@ def test_generic_objects_crud(appliance, context, request):
instance.attributes = {'addr01': 'Changed'}
instance.associations = {'services': myservices}
rest_instance = appliance.rest_api.collections.generic_objects.get(name=instance.name)
- rest_data = appliance.rest_api.get('{}?associations=services'.format(rest_instance.href))
+ rest_data = appliance.rest_api.get(f'{rest_instance.href}?associations=services')
assert len(rest_data['services']) == 2
assert rest_data['property_attributes']['addr01'] == 'Changed'
instance.delete()
diff --git a/cfme/tests/automate/test_ansible_tower_automate.py b/cfme/tests/automate/test_ansible_tower_automate.py
index 2ddd12a57f..d69ad95535 100644
--- a/cfme/tests/automate/test_ansible_tower_automate.py
+++ b/cfme/tests/automate/test_ansible_tower_automate.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import fauxfactory
import pytest
@@ -106,7 +105,7 @@ def delete():
provision_request.remove_request()
provision_request.wait_for_request()
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
diff --git a/cfme/tests/automate/test_customization_paginator.py b/cfme/tests/automate/test_customization_paginator.py
index b385111e88..b92a3522a5 100644
--- a/cfme/tests/automate/test_customization_paginator.py
+++ b/cfme/tests/automate/test_customization_paginator.py
@@ -19,18 +19,18 @@ def some_dialogs(appliance, request):
random_str = fauxfactory.gen_alphanumeric(16)
element_data = {
'element_information': {
- 'ele_label': "ele_{}".format(random_str),
+ 'ele_label': f"ele_{random_str}",
'ele_name': format(random_str),
'ele_desc': format(random_str),
'choose_type': "Check Box"
}
}
service_dialogs = appliance.collections.service_dialogs
- sd = service_dialogs.create(label='test_paginator_{}'.format(random_str),
+ sd = service_dialogs.create(label=f'test_paginator_{random_str}',
description="my dialog")
- tab = sd.tabs.create(tab_label='tab_{}'.format(random_str),
+ tab = sd.tabs.create(tab_label=f'tab_{random_str}',
tab_desc="my tab desc")
- box = tab.boxes.create(box_label='box_{}'.format(random_str),
+ box = tab.boxes.create(box_label=f'box_{random_str}',
box_desc="my box desc")
box.elements.create(element_data=[element_data])
to_delete.append(sd)
@@ -90,7 +90,7 @@ def test_paginator_service_dialogs(some_dialogs, soft_assert, appliance):
current_rec_end = view.paginator.max_item
assert int(current_rec_offset) <= int(current_rec_end) <= int(current_total), \
- "Incorrect paginator value, expected {0} <= {1} <= {2}".format(
+ "Incorrect paginator value, expected {} <= {} <= {}".format(
current_rec_offset, current_rec_end, current_total)
assert {dlg.label for dlg in some_dialogs} <= dialogs_found, \
diff --git a/cfme/tests/automate/test_domain_priority.py b/cfme/tests/automate/test_domain_priority.py
index da288609b8..0bce8c2c44 100644
--- a/cfme/tests/automate/test_domain_priority.py
+++ b/cfme/tests/automate/test_domain_priority.py
@@ -123,7 +123,7 @@ def test_priority(
14.The contents of the file should be the same as in the first case.
"""
ssh_client = appliance.ssh_client
- ssh_client.run_command("rm -f {}".format(FILE_LOCATION))
+ ssh_client.run_command(f"rm -f {FILE_LOCATION}")
domain_collection.set_order([original_domain]) # Default first
#
# FIRST SIMULATION
@@ -136,13 +136,13 @@ def test_priority(
execute_methods=True
)
wait_for(
- lambda: ssh_client.run_command("cat {}".format(FILE_LOCATION)).success,
+ lambda: ssh_client.run_command(f"cat {FILE_LOCATION}").success,
num_sec=120, delay=0.5, message="wait for file to appear"
)
- request.addfinalizer(lambda: ssh_client.run_command("rm -f {}".format(FILE_LOCATION)))
- result = ssh_client.run_command("cat {}".format(FILE_LOCATION))
+ request.addfinalizer(lambda: ssh_client.run_command(f"rm -f {FILE_LOCATION}"))
+ result = ssh_client.run_command(f"cat {FILE_LOCATION}")
assert result.output.strip() == original_method_write_data
- ssh_client.run_command("rm -f {}".format(FILE_LOCATION))
+ ssh_client.run_command(f"rm -f {FILE_LOCATION}")
# END OF FIRST SIMULATION
# We've checked that the automate method works, so let's copy them to new domain
original_method.copy_to(copy_domain)
@@ -167,12 +167,12 @@ def test_priority(
execute_methods=True
)
wait_for(
- lambda: ssh_client.run_command("cat {}".format(FILE_LOCATION)).success,
+ lambda: ssh_client.run_command(f"cat {FILE_LOCATION}").success,
num_sec=120, delay=0.5, message="wait for file to appear"
)
- result = ssh_client.run_command("cat {}".format(FILE_LOCATION))
+ result = ssh_client.run_command(f"cat {FILE_LOCATION}")
assert result.output.strip() == copy_method_write_data
- ssh_client.run_command("rm -f {}".format(FILE_LOCATION))
+ ssh_client.run_command(f"rm -f {FILE_LOCATION}")
# END OF SECOND SIMULATION
# And last shot, now again with default domain
domain_collection.set_order([original_domain])
@@ -188,12 +188,12 @@ def test_priority(
execute_methods=True
)
wait_for(
- lambda: ssh_client.run_command("cat {}".format(FILE_LOCATION)).success,
+ lambda: ssh_client.run_command(f"cat {FILE_LOCATION}").success,
num_sec=120, delay=0.5, message="wait for file to appear"
)
- result = ssh_client.run_command("cat {}".format(FILE_LOCATION))
+ result = ssh_client.run_command(f"cat {FILE_LOCATION}")
assert result.output.strip() == original_method_write_data
- ssh_client.run_command("rm -f {}".format(FILE_LOCATION))
+ ssh_client.run_command(f"rm -f {FILE_LOCATION}")
# END OF LAST SIMULATION
diff --git a/cfme/tests/automate/test_git_import.py b/cfme/tests/automate/test_git_import.py
index e40dc56205..8f4a657c74 100644
--- a/cfme/tests/automate/test_git_import.py
+++ b/cfme/tests/automate/test_git_import.py
@@ -69,7 +69,7 @@ def test_automate_git_domain_removed_from_disk(appliance, imported_domain):
imported_domain.delete()
repo_path = urlparse(GIT_REPO_URL).path
assert appliance.ssh_client.run_command(
- '[ ! -d "/var/www/vmdb/data/git_repos{}" ]'.format(repo_path)).success
+ f'[ ! -d "/var/www/vmdb/data/git_repos{repo_path}" ]').success
@pytest.mark.tier(2)
diff --git a/cfme/tests/automate/test_instance.py b/cfme/tests/automate/test_instance.py
index 069e800206..db9b3b839b 100644
--- a/cfme/tests/automate/test_instance.py
+++ b/cfme/tests/automate/test_instance.py
@@ -93,7 +93,7 @@ def test_automate_instance_missing(domain, klass, namespace, appliance):
method = klass.methods.create(
name=fauxfactory.gen_alphanumeric(),
location='inline',
- script='$evm.log(:info, "{}")'.format(catch_string),
+ script=f'$evm.log(:info, "{catch_string}")',
)
klass.schema.add_fields({'name': 'mfield', 'type': 'Method', 'data_type': 'String'})
klass.instances.create(name='.missing', fields={'mfield': {'value': '${#_missing_instance}'}})
@@ -107,13 +107,13 @@ def test_automate_instance_missing(domain, klass, namespace, appliance):
appliance=appliance,
request='Call_Instance',
attributes_values={
- 'namespace': '{}/{}'.format(domain.name, namespace.name),
+ 'namespace': f'{domain.name}/{namespace.name}',
'class': klass2.name,
'instance': instance2.name
}
)
assert appliance.ssh_client.run_command(
- 'grep {} /var/www/miq/vmdb/log/automation.log'.format(catch_string)).success
+ f'grep {catch_string} /var/www/miq/vmdb/log/automation.log').success
@pytest.mark.tier(1)
@@ -151,7 +151,7 @@ def test_automate_relationship_trailing_spaces(request, klass, namespace, domain
method = klass.methods.create(
name=fauxfactory.gen_alphanumeric(),
location='inline',
- script='$evm.log(:info, "{}")'.format(catch_string)
+ script=f'$evm.log(:info, "{catch_string}")'
)
request.addfinalizer(method.delete_if_exists)
@@ -201,7 +201,7 @@ def test_automate_relationship_trailing_spaces(request, klass, namespace, domain
# Also checking if method1 of klass1 is executed successfully or not by searching 'catch_string'
# in automation log.
result = LogValidator(
- "/var/www/miq/vmdb/log/automation.log", matched_patterns=[".*{}.*".format(catch_string)],
+ "/var/www/miq/vmdb/log/automation.log", matched_patterns=[f".*{catch_string}.*"],
failure_patterns=[".*ERROR.*"]
)
result.start_monitoring()
@@ -211,7 +211,7 @@ def test_automate_relationship_trailing_spaces(request, klass, namespace, domain
appliance=klass.appliance,
request="Call_Instance",
attributes_values={
- "namespace": "{}/{}".format(domain.name, namespace.name),
+ "namespace": f"{domain.name}/{namespace.name}",
"class": klass2.name,
"instance": instance2.name,
},
@@ -268,7 +268,7 @@ def test_check_system_request_calls_depr_conf_mgmt(appliance, copy_instance):
"""
search = '/AutomationManagement/AnsibleTower/Operations/StateMachines/Job/default'
result = LogValidator(
- "/var/www/miq/vmdb/log/automation.log", matched_patterns=[".*{}.*".format(search)]
+ "/var/www/miq/vmdb/log/automation.log", matched_patterns=[f".*{search}.*"]
)
result.start_monitoring()
# Executing the automate instance - 'ansible_tower_job' using simulation
@@ -337,7 +337,7 @@ def test_quota_source_value(request, entity, search, copy_quota_instance, generi
request.addfinalizer(lambda: root_tenant.set_quota(**{"cpu_cb": False}))
result = LogValidator(
- "/var/www/miq/vmdb/log/automation.log", matched_patterns=[".*{}.*".format(search)]
+ "/var/www/miq/vmdb/log/automation.log", matched_patterns=[f".*{search}.*"]
)
result.start_monitoring()
service_catalogs = ServiceCatalogs(
diff --git a/cfme/tests/automate/test_method.py b/cfme/tests/automate/test_method.py
index 46b20618c9..aba0b521df 100644
--- a/cfme/tests/automate/test_method.py
+++ b/cfme/tests/automate/test_method.py
@@ -630,8 +630,8 @@ def test_method_for_log_and_notify(request, klass, notify_level, log_level):
result = LogValidator(
"/var/www/miq/vmdb/log/automation.log",
matched_patterns=[
- ".*Validating Notification type: automate_user_{}.*".format(log_level),
- ".*Calling Create Notification type: automate_user_{}.*".format(log_level),
+ f".*Validating Notification type: automate_user_{log_level}.*",
+ f".*Calling Create Notification type: automate_user_{log_level}.*",
".*Hello Testing Log & Notify.*"
],
failure_patterns=[".*ERROR.*"]
diff --git a/cfme/tests/automate/test_service_dialog.py b/cfme/tests/automate/test_service_dialog.py
index 143d03e16d..c5cf4f5eaa 100644
--- a/cfme/tests/automate/test_service_dialog.py
+++ b/cfme/tests/automate/test_service_dialog.py
@@ -56,7 +56,7 @@ def test_crud_service_dialog(appliance):
dialog, element = create_dialog(appliance, element_data)
view = appliance.browser.create_view(DialogsView, wait="10s")
- flash_message = '{} was saved'.format(dialog.label)
+ flash_message = f'{dialog.label} was saved'
view.flash.assert_message(flash_message)
with update(dialog):
dialog.description = "my edited description"
diff --git a/cfme/tests/automate/test_smoke.py b/cfme/tests/automate/test_smoke.py
index e64c01eba0..e26da824eb 100644
--- a/cfme/tests/automate/test_smoke.py
+++ b/cfme/tests/automate/test_smoke.py
@@ -29,8 +29,8 @@ def test_domain_present(domain_name, soft_assert, appliance):
3. Verify that all of the required domains are present.
"""
domain = appliance.collections.domains.instantiate(name=domain_name)
- soft_assert(domain.exists, "Domain {} does not exist!".format(domain_name))
- soft_assert(domain.locked, "Domain {} is not locked!".format(domain_name))
+ soft_assert(domain.exists, f"Domain {domain_name} does not exist!")
+ soft_assert(domain.locked, f"Domain {domain_name} is not locked!")
soft_assert(
appliance.check_domain_enabled(
- domain_name), "Domain {} is not enabled!".format(domain_name))
+ domain_name), f"Domain {domain_name} is not enabled!")
diff --git a/cfme/tests/candu/test_azone_graph.py b/cfme/tests/candu/test_azone_graph.py
index 2d1bee1fa9..134dd57f93 100644
--- a/cfme/tests/candu/test_azone_graph.py
+++ b/cfme/tests/candu/test_azone_graph.py
@@ -86,7 +86,7 @@ def refresh():
# zoom in button not available with normal graph except Instance in Azone Utilization page.
# We have to use vm average graph for zoom in operation.
- avg_graph = graph_type if graph_type == "azone_instance" else "{}_avg".format(graph_type)
+ avg_graph = graph_type if graph_type == "azone_instance" else f"{graph_type}_avg"
try:
avg_graph = getattr(view, avg_graph)
except AttributeError as e:
diff --git a/cfme/tests/candu/test_cluster_graph.py b/cfme/tests/candu/test_cluster_graph.py
index 9303f4325d..2e182f814c 100644
--- a/cfme/tests/candu/test_cluster_graph.py
+++ b/cfme/tests/candu/test_cluster_graph.py
@@ -100,7 +100,7 @@ def refresh():
# zoom in button not available with normal graph except Host and VM.
# We have to use vm or host average graph for zoom in operation.
graph_zoom = ["cluster_host", "cluster_vm"]
- avg_graph = graph_type if graph_type in graph_zoom else "{}_vm_host_avg".format(graph_type)
+ avg_graph = graph_type if graph_type in graph_zoom else f"{graph_type}_vm_host_avg"
try:
avg_graph = getattr(view, avg_graph)
except AttributeError as e:
diff --git a/cfme/tests/candu/test_graph_groupbytag.py b/cfme/tests/candu/test_graph_groupbytag.py
index d85bdadb35..85e79e263d 100644
--- a/cfme/tests/candu/test_graph_groupbytag.py
+++ b/cfme/tests/candu/test_graph_groupbytag.py
@@ -68,7 +68,7 @@ def test_tagwise(candu_db_restore, interval, graph_type, gp_by, host):
try:
graph = getattr(view.interval_type, graph_type)
except AttributeError:
- pytest.fail('{} graph was not displayed'.format(graph_type))
+ pytest.fail(f'{graph_type} graph was not displayed')
assert graph.is_displayed
graph.zoom_in()
diff --git a/cfme/tests/candu/test_host_graph.py b/cfme/tests/candu/test_host_graph.py
index bfd7280da2..f9357d533b 100644
--- a/cfme/tests/candu/test_host_graph.py
+++ b/cfme/tests/candu/test_host_graph.py
@@ -154,7 +154,7 @@ def refresh():
# zoom in button not available with normal graph in Host Utilization page.
# We have to use vm average graph for zoom in operation.
try:
- vm_avg_graph = getattr(view.interval_type, "{}_vm_avg".format(graph_type))
+ vm_avg_graph = getattr(view.interval_type, f"{graph_type}_vm_avg")
except AttributeError as e:
logger.error(e)
vm_avg_graph.zoom_in()
diff --git a/cfme/tests/cli/test_appliance_cli.py b/cfme/tests/cli/test_appliance_cli.py
index 78a5e7411e..5b46ac8f90 100644
--- a/cfme/tests/cli/test_appliance_cli.py
+++ b/cfme/tests/cli/test_appliance_cli.py
@@ -60,7 +60,7 @@ def test_appliance_console_cli_timezone(timezone, temp_appliance_preconfig_modsc
initialEstimate: 1/12h
"""
app = temp_appliance_preconfig_modscope
- app.ssh_client.run_command("appliance_console_cli --timezone {}".format(timezone))
+ app.ssh_client.run_command(f"appliance_console_cli --timezone {timezone}")
app.appliance_console.timezone_check(timezone)
@@ -147,19 +147,19 @@ def test_appliance_console_cli_external_auth(auth_type, ipa_crud, configured_app
initialEstimate: 1/4h
"""
evm_tail = LogValidator('/var/www/miq/vmdb/log/evm.log',
- matched_patterns=['.*{} to true.*'.format(auth_type)],
+ matched_patterns=[f'.*{auth_type} to true.*'],
hostname=configured_appliance.hostname)
evm_tail.start_monitoring()
- cmd_set = 'appliance_console_cli --extauth-opts="/authentication/{}=true"'.format(auth_type)
+ cmd_set = f'appliance_console_cli --extauth-opts="/authentication/{auth_type}=true"'
assert configured_appliance.ssh_client.run_command(cmd_set)
assert evm_tail.validate(wait="30s")
evm_tail = LogValidator('/var/www/miq/vmdb/log/evm.log',
- matched_patterns=['.*{} to false.*'.format(auth_type)],
+ matched_patterns=[f'.*{auth_type} to false.*'],
hostname=configured_appliance.hostname)
evm_tail.start_monitoring()
- cmd_unset = 'appliance_console_cli --extauth-opts="/authentication/{}=false"'.format(auth_type)
+ cmd_unset = f'appliance_console_cli --extauth-opts="/authentication/{auth_type}=false"'
assert configured_appliance.ssh_client.run_command(cmd_unset)
assert evm_tail.validate(wait="30s")
@@ -280,7 +280,7 @@ def test_appliance_console_cli_ha_crud(unconfigured_appliances, app_creds):
hostname=apps[2].hostname).waiting(timeout=450):
# Cause failover to occur
result = apps[0].ssh_client.run_command('systemctl stop $APPLIANCE_PG_SERVICE', timeout=15)
- assert result.success, "Failed to stop APPLIANCE_PG_SERVICE: {}".format(result.output)
+ assert result.success, f"Failed to stop APPLIANCE_PG_SERVICE: {result.output}"
apps[2].evmserverd.wait_for_running()
apps[2].wait_for_web_ui()
diff --git a/cfme/tests/cli/test_appliance_console.py b/cfme/tests/cli/test_appliance_console.py
index 99f06ef7d8..4034cdee36 100644
--- a/cfme/tests/cli/test_appliance_console.py
+++ b/cfme/tests/cli/test_appliance_console.py
@@ -347,7 +347,7 @@ def test_appliance_console_ha_crud(unconfigured_appliances, app_creds):
# Cause failover to occur
result = apps[0].ssh_client.run_command(
'systemctl stop $APPLIANCE_PG_SERVICE', timeout=15)
- assert result.success, "Failed to stop APPLIANCE_PG_SERVICE: {}".format(result.output)
+ assert result.success, f"Failed to stop APPLIANCE_PG_SERVICE: {result.output}"
apps[2].evmserverd.wait_for_running()
apps[2].wait_for_web_ui()
@@ -498,7 +498,7 @@ def test_appliance_console_external_auth(auth_type, ipa_crud, configured_applian
# TODO it assumes that first switch is to true, then false.
evm_tail = LogValidator('/var/www/miq/vmdb/log/evm.log',
- matched_patterns=['.*{} to true.*'.format(auth_type.option)],
+ matched_patterns=[f'.*{auth_type.option} to true.*'],
hostname=configured_appliance.hostname)
evm_tail.start_monitoring()
command_set = ('ap', RETURN, app_con_menu["update_ext_auth_opt"], auth_type.index, '5',
@@ -507,7 +507,7 @@ def test_appliance_console_external_auth(auth_type, ipa_crud, configured_applian
assert evm_tail.validate(wait="30s")
evm_tail = LogValidator('/var/www/miq/vmdb/log/evm.log',
- matched_patterns=['.*{} to false.*'.format(auth_type.option)],
+ matched_patterns=[f'.*{auth_type.option} to false.*'],
hostname=configured_appliance.hostname)
evm_tail.start_monitoring()
diff --git a/cfme/tests/cli/test_appliance_console_db_restore.py b/cfme/tests/cli/test_appliance_console_db_restore.py
index 7f445a7ec2..4b15125357 100644
--- a/cfme/tests/cli/test_appliance_console_db_restore.py
+++ b/cfme/tests/cli/test_appliance_console_db_restore.py
@@ -575,8 +575,8 @@ def test_appliance_console_restore_db_nfs(request, two_appliances_one_with_provi
host = utility_vm_nfs_ip
loc = data['network_share']['nfs']['path']
nfs_dump_file_name = '/tmp/backup.{}.dump'.format(fauxfactory.gen_alphanumeric())
- nfs_restore_dir_path = 'nfs://{}{}'.format(host, loc)
- nfs_restore_file_path = '{}/db_backup/{}'.format(nfs_restore_dir_path, nfs_dump_file_name)
+ nfs_restore_dir_path = f'nfs://{host}{loc}'
+ nfs_restore_file_path = f'{nfs_restore_dir_path}/db_backup/{nfs_dump_file_name}'
# Transfer v2_key and db backup from first appliance to second appliance
fetch_v2key(appl1, appl2)
@@ -651,8 +651,8 @@ def test_appliance_console_restore_db_samba(request, two_appliances_one_with_pro
host = utility_vm_samba_ip
loc = data['network_share']['smb']['path']
smb_dump_file_name = '/tmp/backup.{}.dump'.format(fauxfactory.gen_alphanumeric())
- smb_restore_dir_path = 'smb://{}{}'.format(host, loc)
- smb_restore_file_path = '{}/db_backup/{}'.format(smb_restore_dir_path, smb_dump_file_name)
+ smb_restore_dir_path = f'smb://{host}{loc}'
+ smb_restore_file_path = f'{smb_restore_dir_path}/db_backup/{smb_dump_file_name}'
creds_key = data['network_share']['smb']['credentials']
pwd = credentials[creds_key]['password']
@@ -680,7 +680,7 @@ def test_appliance_console_restore_db_samba(request, two_appliances_one_with_pro
smb_restore_dir_path)
# Enter the username with access to this file.
interaction.answer(re.escape("Example: 'mydomain.com/user': "), usr)
- interaction.answer(re.escape('Enter the password for {}: '.format(usr)), pwd)
+ interaction.answer(re.escape(f'Enter the password for {usr}: '), pwd)
# Running Database backup to nfs://10.8.198.142/srv/export...
interaction.answer('Press any key to continue.', '', timeout=120)
@@ -703,7 +703,7 @@ def test_appliance_console_restore_db_samba(request, two_appliances_one_with_pro
smb_restore_file_path)
# Enter the username with access to this file.
interaction.answer(re.escape("Example: 'mydomain.com/user': "), usr)
- interaction.answer(re.escape('Enter the password for {}: '.format(usr)), pwd)
+ interaction.answer(re.escape(f'Enter the password for {usr}: '), pwd)
interaction.answer(r'Are you sure you would like to restore the database\? \(Y\/N\): ', 'y')
interaction.answer('Press any key to continue.', '', timeout=80)
diff --git a/cfme/tests/cli/test_appliance_log_rotate.py b/cfme/tests/cli/test_appliance_log_rotate.py
index 62cd08f4dc..6756ea7d16 100644
--- a/cfme/tests/cli/test_appliance_log_rotate.py
+++ b/cfme/tests/cli/test_appliance_log_rotate.py
@@ -24,7 +24,7 @@ def advance_appliance_date_by_day(appliance):
appliance_date = dateutil.parser.parse(txt_date)
td = datetime.timedelta(days=1)
advanced_txt_date = (appliance_date + td).strftime("%Y-%m-%d %H:%M:%S%z")
- appliance.ssh_client.run_command("date -s '{}'".format(advanced_txt_date))
+ appliance.ssh_client.run_command(f"date -s '{advanced_txt_date}'")
@test_requirements.appliance
@@ -43,9 +43,9 @@ def test_appliance_log_rotate(temp_appliance_preconfig_funcscope):
initial_log_files = {}
for log_path in LOGS.pick():
initial_log_files[log_path] = appliance.ssh_client.run_command(
- "ls -1 {}*".format(log_path)).output.split('\n')
+ f"ls -1 {log_path}*").output.split('\n')
appliance.ssh_client.run_command(
- "echo 'Ensure line in logs' >> {}".format(log_path))
+ f"echo 'Ensure line in logs' >> {log_path}")
# Perform the logrotate.
advance_appliance_date_by_day(appliance)
diff --git a/cfme/tests/cli/test_appliance_update.py b/cfme/tests/cli/test_appliance_update.py
index 7d58139af8..48ccc49dda 100644
--- a/cfme/tests/cli/test_appliance_update.py
+++ b/cfme/tests/cli/test_appliance_update.py
@@ -101,7 +101,7 @@ def appliance_preupdate(old_version, appliance, request):
apps[0].db.extend_partition()
urls = cfme_data["basic_info"][update_url]
apps[0].ssh_client.run_command(
- "curl {} -o /etc/yum.repos.d/update.repo".format(urls)
+ f"curl {urls} -o /etc/yum.repos.d/update.repo"
)
logger.info('Appliance update.repo file: \n%s',
apps[0].ssh_client.run_command('cat /etc/yum.repos.d/update.repo').output)
@@ -114,7 +114,7 @@ def do_yum_update(appliance):
appliance.evmserverd.stop()
with appliance.ssh_client as ssh:
result = ssh.run_command('yum update -y', timeout=3600)
- assert result.success, "update failed {}".format(result.output)
+ assert result.success, f"update failed {result.output}"
appliance.evmserverd.start()
appliance.wait_for_web_ui()
diff --git a/cfme/tests/cloud/test_cloud_timelines.py b/cfme/tests/cloud/test_cloud_timelines.py
index 7c33e6d168..9d94193840 100644
--- a/cfme/tests/cloud/test_cloud_timelines.py
+++ b/cfme/tests/cloud/test_cloud_timelines.py
@@ -63,7 +63,7 @@ def azone(create_vm, appliance):
return inst_zone
-class InstEvent(object):
+class InstEvent:
ACTIONS = {
'create': {
'tl_event': ('AWS_EC2_Instance_CREATE', 'virtualMachines_write_EndRequest'),
@@ -150,7 +150,7 @@ def _restart(self):
def _rename_vm(self):
logger.info('%r will be renamed', self.inst.name)
- new_name = "{}-renamed".format(self.inst.name)
+ new_name = f"{self.inst.name}-renamed"
self.inst.mgmt.rename(new_name)
self.inst.name = new_name
self.inst.mgmt.restart()
@@ -263,7 +263,7 @@ def test_cloud_timeline_create_event(create_vm, soft_assert, azone):
event = 'create'
inst_event = InstEvent(create_vm, event)
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='9m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='9m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets)
@@ -286,7 +286,7 @@ def test_cloud_timeline_policy_event(create_vm, control_policy, soft_assert):
targets = (create_vm, create_vm.provider)
inst_event = InstEvent(create_vm, event)
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='9m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='9m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets, policy_events=True)
@@ -309,7 +309,7 @@ def test_cloud_timeline_stop_event(create_vm, soft_assert, azone):
event = 'stop'
inst_event = InstEvent(create_vm, event)
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='7m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='7m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets)
@@ -332,7 +332,7 @@ def test_cloud_timeline_start_event(create_vm, soft_assert, azone):
event = 'start'
inst_event = InstEvent(create_vm, 'start')
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='7m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='7m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets)
@@ -375,7 +375,7 @@ def test_cloud_timeline_rename_event(create_vm, soft_assert, azone):
targets = (create_vm, create_vm.provider, azone)
inst_event = InstEvent(create_vm, event)
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='12m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='12m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets)
@@ -406,5 +406,5 @@ def test_cloud_timeline_delete_event(create_vm, soft_assert, azone):
targets = (create_vm, create_vm.provider, azone)
inst_event = InstEvent(create_vm, event)
logger.info('Will generate event %r on machine %r', event, create_vm.name)
- wait_for(inst_event.emit, timeout='9m', message='Event {} did timeout'.format(event))
+ wait_for(inst_event.emit, timeout='9m', message=f'Event {event} did timeout')
inst_event.catch_in_timelines(soft_assert, targets)
diff --git a/cfme/tests/cloud/test_instance_power_control.py b/cfme/tests/cloud/test_instance_power_control.py
index 29a5f4a0bd..a6ace50c69 100644
--- a/cfme/tests/cloud/test_instance_power_control.py
+++ b/cfme/tests/cloud/test_instance_power_control.py
@@ -128,11 +128,11 @@ def check_power_options(soft_assert, instance, power_state):
for pwr_option in instance.ui_powerstates_available[power_state]:
soft_assert(
instance.is_pwr_option_available_in_cfme(option=pwr_option, from_details=True),
- "{} must be available in current power state - {} ".format(pwr_option, power_state))
+ f"{pwr_option} must be available in current power state - {power_state} ")
for pwr_option in instance.ui_powerstates_unavailable[power_state]:
soft_assert(
not instance.is_pwr_option_available_in_cfme(option=pwr_option, from_details=True),
- "{} must not be available in current power state - {} ".format(pwr_option, power_state))
+ f"{pwr_option} must not be available in current power state - {power_state} ")
def wait_for_instance_state(soft_assert, instance, state):
@@ -183,7 +183,7 @@ def wait_for_instance_state(soft_assert, instance, state):
# Check Vm state in CFME
soft_assert(
instance.wait_for_instance_state_change(desired_state=desired_ui_state, timeout=1200),
- "Instance {} isn't {} in CFME UI".format(instance, desired_ui_state)
+ f"Instance {instance} isn't {desired_ui_state} in CFME UI"
)
@@ -507,7 +507,7 @@ def test_instance_power_options_from_off(provider, testing_instance,
@test_requirements.rest
-class TestInstanceRESTAPI(object):
+class TestInstanceRESTAPI:
""" Tests using the /api/instances collection. """
@pytest.mark.parametrize("from_detail", [True, False], ids=["from_detail", "from_collection"])
diff --git a/cfme/tests/cloud/test_providers.py b/cfme/tests/cloud/test_providers.py
index 625b9ca56a..187aa5c37b 100644
--- a/cfme/tests/cloud/test_providers.py
+++ b/cfme/tests/cloud/test_providers.py
@@ -109,7 +109,7 @@ def connect_az_account(pwsh_ssh):
https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps
"""
path_script = os.path.join(SPACE, 'connect_account.ps1')
- connect = pwsh_ssh.run_command("pwsh {}".format(path_script), timeout=180)
+ connect = pwsh_ssh.run_command(f"pwsh {path_script}", timeout=180)
assert connect.success, "Failed to connect to Azure account"
@@ -117,7 +117,7 @@ def connect_az_account(pwsh_ssh):
def cfme_vhd(appliance, pwsh_ssh):
path_script = os.path.join(SPACE, 'get_ip.ps1')
ip_of_recourse = pwsh_ssh.run_command(
- r'pwsh {}| grep -oE "([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}"'.format(path_script),
+ fr'pwsh {path_script}| grep -oE "([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}"',
timeout=60).output.strip()
if ip_of_recourse is not None:
pytest.skip("The resource is taken by some other VM in Azure")
@@ -129,10 +129,10 @@ def cfme_vhd(appliance, pwsh_ssh):
pytest.skip("Skipping since no such key found in yaml")
image = pwsh_ssh.run_command(
- """wget -qO- {url} | grep -Po '(?<=href=")[^"]*' | grep azure""".format(url=url),
+ f"""wget -qO- {url} | grep -Po '(?<=href=")[^"]*' | grep azure""",
timeout=30).output.strip()
image_url = urljoin(url, image)
- pwsh_ssh.run_command("wget {image} -P {dest}".format(dest=SPACE, image=image_url),
+ pwsh_ssh.run_command(f"wget {image_url} -P {SPACE}",
timeout=180)
# unpack the archive
@@ -152,7 +152,7 @@ def upload_image_to_azure(cfme_vhd, pwsh_ssh):
r"""sed -i '1s/.*/$BlobNameSource = "{vhd}"/' {script}"""
.format(script=path_script, vhd=cfme_vhd), timeout=30)
- pwsh_ssh.run_command("pwsh {}".format(path_script), timeout=15 * 60)
+ pwsh_ssh.run_command(f"pwsh {path_script}", timeout=15 * 60)
@pytest.fixture(scope='function')
@@ -169,12 +169,12 @@ def vm_ip(cfme_vhd, pwsh_ssh):
name=cfme_vhd.replace('.x86_64.vhd', '-vm')),
timeout=20)
- pwsh_ssh.run_command("pwsh {}".format(path_script), timeout=600)
+ pwsh_ssh.run_command(f"pwsh {path_script}", timeout=600)
# get the ip of the resource
path_get_ip = os.path.join(SPACE, 'get_ip.ps1')
ip = pwsh_ssh.run_command(
- r'pwsh {}| grep -oE "([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}"'.format(path_get_ip),
+ fr'pwsh {path_get_ip}| grep -oE "([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}"',
timeout=60).output.strip()
yield ip
@@ -186,7 +186,7 @@ def vm_ip(cfme_vhd, pwsh_ssh):
name=cfme_vhd.replace('.x86_64.vhd', '-vm')),
timeout=20)
- pwsh_ssh.run_command("pwsh {}".format(path_script), timeout=180)
+ pwsh_ssh.run_command(f"pwsh {path_script}", timeout=180)
@pytest.fixture
@@ -821,7 +821,7 @@ def test_display_network_topology(appliance, openstack_provider):
@pytest.mark.provider([CloudProvider], scope='class')
-class TestProvidersRESTAPI(object):
+class TestProvidersRESTAPI:
@pytest.mark.tier(3)
@pytest.mark.parametrize('from_detail', [True, False], ids=['from_detail', 'from_collection'])
def test_cloud_networks_query(self, provider, appliance, from_detail, setup_provider):
@@ -990,7 +990,7 @@ def test_vpc_env_selection(setup_provider, request, provider, appliance, provisi
view.flash.assert_no_error()
# make sure the request succeeds
- request_description = 'Provision from [{}] to [{}]'.format(template, vm_name)
+ request_description = f'Provision from [{template}] to [{vm_name}]'
provision_request = appliance.collections.requests.instantiate(request_description)
provision_request.wait_for_request(method='ui', num_sec=15 * 60)
assert provision_request.is_succeeded(method='ui'), "Provisioning failed: {}".format(
@@ -1169,17 +1169,17 @@ def test_create_azure_vm_from_azure_image(connect_az_account, cfme_vhd, upload_i
# permit root login over ssh for future appliance configuration
command = 'sed -i "s/.*PermitRootLogin.*/PermitRootLogin yes/g" /etc/ssh/sshd_config'
config = app_ssh_client.run_command(
- 'echo {} | sudo -S {}'.format(password, command), ensure_user=True)
+ f'echo {password} | sudo -S {command}', ensure_user=True)
assert config.success
# restart sshd to apply configuration changes
restart = app_ssh_client.run_command(
- 'echo {} | sudo -S systemctl restart sshd'.format(password), ensure_user=True)
+ f'echo {password} | sudo -S systemctl restart sshd', ensure_user=True)
assert restart.success
# unlock root password
unlock = app_ssh_client.run_command(
- 'echo {} | sudo -S passwd -u root'.format(password), ensure_user=True)
+ f'echo {password} | sudo -S passwd -u root', ensure_user=True)
assert unlock.success
app.configure()
@@ -1394,9 +1394,9 @@ def test_regions_up_to_date(provider):
regions_not_in_cfme = set(regions_provider) - set(regions_cfme_texts)
extra_regions_in_cfme = set(regions_cfme_texts) - set(regions_provider)
if len(regions_not_in_cfme) > 0:
- pytest.fail("Regions {} are not in CFME!".format(regions_not_in_cfme))
+ pytest.fail(f"Regions {regions_not_in_cfme} are not in CFME!")
if len(extra_regions_in_cfme) > 0:
- pytest.fail("Extra regions in CFME: {}".format(extra_regions_in_cfme))
+ pytest.fail(f"Extra regions in CFME: {extra_regions_in_cfme}")
@test_requirements.ec2
@@ -1491,7 +1491,7 @@ def test_add_second_provider(setup_provider, provider, request):
3. Provider should be successfully added.
"""
second_provider = get_crud(provider.key)
- second_provider.name = "{}-2".format(provider.name)
+ second_provider.name = f"{provider.name}-2"
second_provider.create()
request.addfinalizer(second_provider.delete_if_exists)
second_provider.refresh_provider_relationships()
diff --git a/cfme/tests/cloud/test_quota.py b/cfme/tests/cloud/test_quota.py
index 59d67bc857..22046c5e3e 100644
--- a/cfme/tests/cloud/test_quota.py
+++ b/cfme/tests/cloud/test_quota.py
@@ -45,20 +45,20 @@ def prov_data(appliance, provisioning):
def set_child_tenant_quota(request, appliance, new_child):
"""This fixture assigns quota to child tenant"""
field, value = request.param
- new_child.set_quota(**{"{}_cb".format(field): True, field: value})
+ new_child.set_quota(**{f"{field}_cb": True, field: value})
yield
appliance.server.login_admin()
- new_child.set_quota(**{"{}_cb".format(field): False})
+ new_child.set_quota(**{f"{field}_cb": False})
@pytest.fixture
def set_project_quota(request, appliance, new_project):
"""This fixture assigns quota to project"""
field, value = request.param
- new_project.set_quota(**{"{}_cb".format(field): True, field: value})
+ new_project.set_quota(**{f"{field}_cb": True, field: value})
yield
appliance.server.login_admin()
- new_project.set_quota(**{"{}_cb".format(field): False})
+ new_project.set_quota(**{f"{field}_cb": False})
@pytest.fixture(scope="module")
@@ -94,7 +94,7 @@ def new_group_child(appliance, new_child, new_tenant):
group = appliance.collections.groups.create(
description=fauxfactory.gen_alphanumeric(start="group_"),
role="EvmRole-super_administrator",
- tenant="My Company/{parent}/{child}".format(parent=new_tenant.name, child=new_child.name),
+ tenant=f"My Company/{new_tenant.name}/{new_child.name}",
)
yield group
if group.exists:
@@ -138,7 +138,7 @@ def new_group_project(appliance, new_project):
group = appliance.collections.groups.create(
description=fauxfactory.gen_alphanumeric(start="group_"),
role="EvmRole-super_administrator",
- tenant="My Company/{project}".format(project=new_project.name),
+ tenant=f"My Company/{new_project.name}",
)
yield group
if group.exists:
@@ -369,9 +369,9 @@ def automate_flavor_method(appliance, klass, namespace):
def set_roottenant_quota(request, appliance):
field, value = request.param
roottenant = appliance.collections.tenants.get_root_tenant()
- roottenant.set_quota(**{'{}_cb'.format(field): True, field: value})
+ roottenant.set_quota(**{f'{field}_cb': True, field: value})
yield
- roottenant.set_quota(**{'{}_cb'.format(field): False})
+ roottenant.set_quota(**{f'{field}_cb': False})
@pytest.fixture(scope="module")
diff --git a/cfme/tests/cloud/test_stack.py b/cfme/tests/cloud/test_stack.py
index ab18861c61..0841956550 100644
--- a/cfme/tests/cloud/test_stack.py
+++ b/cfme/tests/cloud/test_stack.py
@@ -43,7 +43,7 @@ def test_security_group_link(stack):
else:
# Navigation successful, stack had security groups
assert view.is_displayed
- assert view.entities.title.text == '{} (All Security Groups)'.format(stack.name)
+ assert view.entities.title.text == f'{stack.name} (All Security Groups)'
@pytest.mark.tier(3)
@@ -63,7 +63,7 @@ def test_parameters_link(stack):
else:
# Navigation successful, stack had parameters
assert view.is_displayed
- assert view.entities.title.text == '{} (Parameters)'.format(stack.name)
+ assert view.entities.title.text == f'{stack.name} (Parameters)'
@pytest.mark.tier(3)
@@ -82,7 +82,7 @@ def test_outputs_link(stack):
assert view.sidebar.relationships.nav.is_disabled('Outputs (0)')
else:
assert view.is_displayed
- assert view.entities.title.text == '{} (Outputs)'.format(stack.name)
+ assert view.entities.title.text == f'{stack.name} (Outputs)'
@pytest.mark.tier(3)
@@ -123,7 +123,7 @@ def test_resources_link(stack):
assert view.sidebar.relationships.nav.is_disabled('Resources (0)')
else:
assert view.is_displayed is True
- assert view.entities.title.text == '{} (Resources)'.format(stack.name)
+ assert view.entities.title.text == f'{stack.name} (Resources)'
@pytest.mark.tier(3)
diff --git a/cfme/tests/cloud/test_tag_mapping.py b/cfme/tests/cloud/test_tag_mapping.py
index 08c42e0c99..f500b21a2f 100644
--- a/cfme/tests/cloud/test_tag_mapping.py
+++ b/cfme/tests/cloud/test_tag_mapping.py
@@ -48,7 +48,7 @@ def refresh_provider(provider):
@pytest.fixture(params=['instances', 'images'])
def tag_mapping_items(request, appliance, provider):
entity_type = request.param
- collection = getattr(appliance.collections, 'cloud_{}'.format(entity_type))
+ collection = getattr(appliance.collections, f'cloud_{entity_type}')
collection.filters = {'provider': provider}
view = navigate_to(collection, 'AllForProvider')
name = view.entities.get_first_entity().name
@@ -59,7 +59,7 @@ def tag_mapping_items(request, appliance, provider):
else provider.mgmt.get_vm(name)
)
except ImageNotFoundError:
- msg = 'Failed looking up template [{}] from CFME on provider: {}'.format(name, provider)
+ msg = f'Failed looking up template [{name}] from CFME on provider: {provider}'
logger.exception(msg)
pytest.skip(msg)
return collection.instantiate(name=name, provider=provider), mgmt_item, entity_type
@@ -149,7 +149,7 @@ def test_labels_update(provider, tag_mapping_items, soft_assert):
fields = view.entities.summary('Labels').fields
soft_assert(
tag_label not in fields,
- '{} label was not removed from details page'.format(tag_label)
+ f'{tag_label} label was not removed from details page'
)
@@ -214,14 +214,14 @@ def test_mapping_tags(
soft_assert(any(
tag.category.display_name == category.name and tag.display_name == tag_value
for tag in entity.get_tags()
- ), '{}: {} was not found in tags'.format(category.name, tag_value))
+ ), f'{category.name}: {tag_value} was not found in tags')
# delete it
map_tag.delete()
# check the tag goes away
provider.refresh_provider_relationships(method='ui')
- soft_assert(not '{}: {}'.format(category.name, tag_value) in entity.get_tags())
+ soft_assert(f'{category.name}: {tag_value}' not in entity.get_tags())
@pytest.mark.tier(2)
diff --git a/cfme/tests/cloud/test_tenant.py b/cfme/tests/cloud/test_tenant.py
index a0ae6f2ac1..a6d1f2a9c0 100644
--- a/cfme/tests/cloud/test_tenant.py
+++ b/cfme/tests/cloud/test_tenant.py
@@ -153,7 +153,7 @@ def test_dynamic_product_feature_for_tenant_quota(request, appliance, new_tenant
product_feature.extend(["Access Control", "Tenants", "Modify", "Manage Quotas"])
# List of two tenants with their parents to assign to two different groups
- tenant_ = ["My Company/{parent}".format(parent=new_tenant.name),
+ tenant_ = [f"My Company/{new_tenant.name}",
"My Company/{parent}/{child}".format(parent=new_tenant.name,
child=child_tenant.name)]
diff --git a/cfme/tests/cloud/test_tenant_quota.py b/cfme/tests/cloud/test_tenant_quota.py
index b3c502ccc9..e136a5db41 100644
--- a/cfme/tests/cloud/test_tenant_quota.py
+++ b/cfme/tests/cloud/test_tenant_quota.py
@@ -27,7 +27,7 @@ def set_default(provider, request):
be created with specific values for these entries.
"""
with_prov = (
- "Datastore", "ManageIQ (Locked)", "{}".format(provider.string_name), "VM", "Provisioning",
+ "Datastore", "ManageIQ (Locked)", f"{provider.string_name}", "VM", "Provisioning",
"StateMachines", "ProvisionRequestApproval", "Default"
)
default = (
diff --git a/cfme/tests/cloud_infra_common/test_cloud_init_provisioning.py b/cfme/tests/cloud_infra_common/test_cloud_init_provisioning.py
index 6b634cf656..f55d25f7b1 100644
--- a/cfme/tests/cloud_infra_common/test_cloud_init_provisioning.py
+++ b/cfme/tests/cloud_infra_common/test_cloud_init_provisioning.py
@@ -101,7 +101,7 @@ def test_provision_cloud_init(appliance, request, setup_provider, provider, prov
if provider.one_of(InfraProvider) and appliance.version > '5.9':
inst_args['customize']['customize_type'] = 'Specification'
- logger.info('Instance args: {}'.format(inst_args))
+ logger.info(f'Instance args: {inst_args}')
collection = appliance.provider_based_collection(provider)
instance = collection.create(vm_name, provider, form_values=inst_args)
@@ -164,7 +164,7 @@ def test_provision_cloud_init_payload(appliance, request, setup_provider, provid
}
inst_args['customize'].update(ci_payload)
- logger.info('Instance args: {}'.format(inst_args))
+ logger.info(f'Instance args: {inst_args}')
# Provision VM
collection = appliance.provider_based_collection(provider)
@@ -175,7 +175,7 @@ def test_provision_cloud_init_payload(appliance, request, setup_provider, provid
provision_request.wait_for_request()
connect_ip = wait_for(find_global_ipv6, func_args=[instance], num_sec=600, delay=20).out
- logger.info('Connect IP: {}'.format(connect_ip))
+ logger.info(f'Connect IP: {connect_ip}')
# Connect to the newly provisioned VM
with ssh.SSHClient(hostname=connect_ip,
diff --git a/cfme/tests/cloud_infra_common/test_custom_attributes_rest.py b/cfme/tests/cloud_infra_common/test_custom_attributes_rest.py
index 74dbda3ac0..dd8b26a12e 100644
--- a/cfme/tests/cloud_infra_common/test_custom_attributes_rest.py
+++ b/cfme/tests/cloud_infra_common/test_custom_attributes_rest.py
@@ -58,14 +58,14 @@ def _get_vm():
@pytest.fixture(scope='module')
def get_service(appliance):
uid = fauxfactory.gen_alphanumeric(5)
- name = 'test_rest_service_{}'.format(uid)
+ name = f'test_rest_service_{uid}'
def _get_service():
service = appliance.rest_api.collections.services.find_by(name=name)
if not service:
body = {
'name': name,
- 'description': 'Test REST Service {}'.format(uid),
+ 'description': f'Test REST Service {uid}',
}
service = appliance.rest_api.collections.services.action.create(body)
return service[0]
@@ -95,8 +95,8 @@ def add_custom_attributes(request, resource, num=2):
for __ in range(num):
uid = fauxfactory.gen_alphanumeric(5)
body.append({
- 'name': 'ca_name_{}'.format(uid),
- 'value': 'ca_value_{}'.format(uid)
+ 'name': f'ca_name_{uid}',
+ 'value': f'ca_value_{uid}'
})
attrs = resource.custom_attributes.action.add(*body)
@@ -123,7 +123,7 @@ def _uncollect(provider, collection_name):
GENERIC_UNCOLLECT = 'Invalid combination of collection_name and provider type'
-class TestCustomAttributesRESTAPI(object):
+class TestCustomAttributesRESTAPI:
@pytest.mark.uncollectif(lambda provider, collection_name:
_uncollect(provider, collection_name),
reason=GENERIC_UNCOLLECT)
@@ -253,8 +253,8 @@ def test_edit(self, request, from_detail, collection_name, appliance, get_resour
for __ in range(response_len):
uid = fauxfactory.gen_alphanumeric(5)
body.append({
- 'name': 'ca_name_{}'.format(uid),
- 'value': 'ca_value_{}'.format(uid),
+ 'name': f'ca_name_{uid}',
+ 'value': f'ca_value_{uid}',
'section': 'metadata'
})
if from_detail:
@@ -329,8 +329,8 @@ def test_bad_section_add(self, request, collection_name, appliance, get_resource
add_custom_attributes(request, resource)
uid = fauxfactory.gen_alphanumeric(5)
body = {
- 'name': 'ca_name_{}'.format(uid),
- 'value': 'ca_value_{}'.format(uid),
+ 'name': f'ca_name_{uid}',
+ 'value': f'ca_value_{uid}',
'section': 'bad_section'
}
with pytest.raises(Exception, match='Api::BadRequestError'):
diff --git a/cfme/tests/cloud_infra_common/test_discovery_and_support.py b/cfme/tests/cloud_infra_common/test_discovery_and_support.py
index 9e6c8d0bfe..ffc7bb6c0f 100644
--- a/cfme/tests/cloud_infra_common/test_discovery_and_support.py
+++ b/cfme/tests/cloud_infra_common/test_discovery_and_support.py
@@ -57,11 +57,11 @@ def provider_classes(appliance):
# we want to collect these provider categories
for cat in selected.keys():
selected[cat].extend(
- set( # quick and dirty uniqueness for types/versions
+ { # quick and dirty uniqueness for types/versions
prov.klass
for prov in required_providers
if prov.category == cat
- )
+ }
)
return selected
diff --git a/cfme/tests/cloud_infra_common/test_genealogy.py b/cfme/tests/cloud_infra_common/test_genealogy.py
index 2b5d63077e..1cf04045a8 100644
--- a/cfme/tests/cloud_infra_common/test_genealogy.py
+++ b/cfme/tests/cloud_infra_common/test_genealogy.py
@@ -70,7 +70,7 @@ def test_vm_genealogy_detected(
logger.exception("The parent template not detected!")
raise pytest.fail("The parent template not detected!")
assert small_template.name in vm_crud_ancestors, \
- "{} is not in {}'s ancestors".format(small_template.name, create_vm.name)
+ f"{small_template.name} is not in {create_vm.name}'s ancestors"
@pytest.mark.manual
diff --git a/cfme/tests/cloud_infra_common/test_provisioning.py b/cfme/tests/cloud_infra_common/test_provisioning.py
index 5caeca3293..6f0bab2b79 100644
--- a/cfme/tests/cloud_infra_common/test_provisioning.py
+++ b/cfme/tests/cloud_infra_common/test_provisioning.py
@@ -125,8 +125,8 @@ def test_gce_preemptible_provision(appliance, provider, instance_args, soft_asse
def post_approval(smtp_test, provision_request, vm_type, requester, provider, vm_names):
# requester includes the trailing space
- approved_subject = normalize_text("your {} request was approved".format(vm_type))
- approved_from = normalize_text("{} request from {}was approved".format(vm_type, requester))
+ approved_subject = normalize_text(f"your {vm_type} request was approved")
+ approved_from = normalize_text(f"{vm_type} request from {requester}was approved")
wait_for_messages_with_subjects(smtp_test, [approved_subject, approved_from], num_sec=90)
@@ -141,12 +141,12 @@ def post_approval(smtp_test, provision_request, vm_type, requester, provider, vm
)
provision_request.wait_for_request(method='ui')
- msg = "Provisioning failed with the message {}".format(provision_request.row.last_message.text)
+ msg = f"Provisioning failed with the message {provision_request.row.last_message.text}"
assert provision_request.is_succeeded(method='ui'), msg
# account for multiple vms, specific names
completed_subjects = [
- normalize_text("your {} request has completed vm name {}".format(vm_type, name))
+ normalize_text(f"your {vm_type} request has completed vm name {name}")
for name in vm_names
]
wait_for_messages_with_subjects(smtp_test, completed_subjects, num_sec=90)
@@ -229,25 +229,25 @@ def test_provision_approval(appliance, provider, vm_name, smtp_test, request,
}
vm = collection.create(vm_name, provider, form_values=inst_args, wait=False)
- pending_subject = normalize_text("your {} request is pending".format(vm_type))
+ pending_subject = normalize_text(f"your {vm_type} request is pending")
# requester includes the trailing space
- pending_from = normalize_text("{} request from {}pending approval".format(vm_type, requester))
+ pending_from = normalize_text(f"{vm_type} request from {requester}pending approval")
wait_for_messages_with_subjects(smtp_test, [pending_subject, pending_from], num_sec=90)
smtp_test.clear_database()
- cells = {'Description': 'Provision from [{}] to [{}###]'.format(vm.template_name, vm.name)}
+ cells = {'Description': f'Provision from [{vm.template_name}] to [{vm.name}###]'}
def action_edit():
# Automatic approval after editing the request to conform
- new_vm_name = '{}-xx'.format(vm_name)
+ new_vm_name = f'{vm_name}-xx'
modifications = {
'catalog': {
'num_vms': "1",
'vm_name': new_vm_name
},
- 'Description': 'Provision from [{}] to [{}]'.format(vm.template_name, new_vm_name)
+ 'Description': f'Provision from [{vm.template_name}] to [{new_vm_name}]'
}
provision_request = appliance.collections.requests.instantiate(cells=cells)
provision_request.edit_request(values=modifications)
@@ -272,8 +272,8 @@ def action_approve():
def action_deny():
provision_request = appliance.collections.requests.instantiate(cells=cells)
provision_request.deny_request(method='ui', reason="You stink!")
- denied_subject = normalize_text("your {} request was denied".format(vm_type))
- denied_from = normalize_text("{} request from {}was denied".format(vm_type, requester))
+ denied_subject = normalize_text(f"your {vm_type} request was denied")
+ denied_from = normalize_text(f"{vm_type} request from {requester}was denied")
wait_for_messages_with_subjects(smtp_test, [denied_subject, denied_from], num_sec=90)
# Call function doing what is necessary -- Variation of Strategy design pattern.
@@ -309,7 +309,7 @@ def test_provision_from_template_using_rest(appliance, request, provider, vm_nam
wait_for(
lambda: instance.exists,
- num_sec=1000, delay=5, message="VM {} becomes visible".format(vm_name)
+ num_sec=1000, delay=5, message=f"VM {vm_name} becomes visible"
)
@request.addfinalizer
@@ -521,7 +521,7 @@ def delete_vm_and_wait_for_gone():
instance.cleanup_on_provider() # To make it possible to delete the volume
wait_for(lambda: not instance.exists_on_provider, num_sec=180, delay=5)
- request_description = 'Provision from [{}] to [{}]'.format(image, instance.name)
+ request_description = f'Provision from [{image}] to [{instance.name}]'
provision_request = appliance.collections.requests.instantiate(request_description)
provision_request.wait_for_request(method='ui')
@@ -600,13 +600,13 @@ def cleanup_and_wait_for_instance_gone():
vm_name, provider, form_values=inst_args)
request.addfinalizer(cleanup_and_wait_for_instance_gone)
- request_description = 'Provision from [{}] to [{}]'.format(small_template.name, instance.name)
+ request_description = f'Provision from [{small_template.name}] to [{instance.name}]'
provision_request = appliance.collections.requests.instantiate(request_description)
try:
provision_request.wait_for_request(method='ui')
except Exception as e:
logger.info(
- "Provision failed {}: {}".format(e, provision_request.request_state))
+ f"Provision failed {e}: {provision_request.request_state}")
raise
assert provision_request.is_succeeded(method='ui'), (
"Provisioning failed with the message {}".format(
@@ -643,7 +643,7 @@ def test_provision_with_tag(appliance, vm_name, tag, provider, request):
"""
inst_args = {'purpose': {
'apply_tags': Check_tree.CheckNode(
- ['{} *'.format(tag.category.display_name), tag.display_name])}}
+ [f'{tag.category.display_name} *', tag.display_name])}}
collection = appliance.provider_based_collection(provider)
instance = collection.create(vm_name, provider, form_values=inst_args)
request.addfinalizer(instance.cleanup_on_provider)
diff --git a/cfme/tests/cloud_infra_common/test_relationships.py b/cfme/tests/cloud_infra_common/test_relationships.py
index 49a44c3d52..c6344368ca 100644
--- a/cfme/tests/cloud_infra_common/test_relationships.py
+++ b/cfme/tests/cloud_infra_common/test_relationships.py
@@ -111,7 +111,7 @@ def get_obj(relationship, appliance, **kwargs):
view = navigate_to(host, "Details")
cluster_name = view.entities.summary("Relationships").get_text_of("Cluster")
if cluster_name == "None":
- pytest.skip("Host {} is not a clustered host".format(host.name))
+ pytest.skip(f"Host {host.name} is not a clustered host")
obj = cluster_col.instantiate(name=cluster_name, provider=provider)
elif relationship in ["Datastores", "VMs", "Templates"]:
obj = kwargs.get("host")
@@ -147,7 +147,7 @@ def test_host_relationships(appliance, provider, setup_provider, host, relations
"""
host_view = navigate_to(host, "Details")
if host_view.entities.summary("Relationships").get_text_of(relationship) == "0":
- pytest.skip("There are no relationships for {}".format(relationship))
+ pytest.skip(f"There are no relationships for {relationship}")
obj = get_obj(relationship, appliance, provider=provider, host=host)
host_view.entities.summary("Relationships").click_at(relationship)
relationship_view = appliance.browser.create_view(view, additional_context={'object': obj})
@@ -171,7 +171,7 @@ def test_infra_provider_relationships(appliance, provider, setup_provider, relat
"""
provider_view = navigate_to(provider, "Details") # resetter selects summary view
if provider_view.entities.summary("Relationships").get_text_of(relationship) == "0":
- pytest.skip("There are no relationships for {}".format(relationship))
+ pytest.skip(f"There are no relationships for {relationship}")
provider_view.entities.summary("Relationships").click_at(relationship)
relationship_view = appliance.browser.create_view(view, additional_context={'object': provider})
assert relationship_view.is_displayed
@@ -194,7 +194,7 @@ def test_cloud_provider_relationships(appliance, provider, setup_provider, relat
# Version dependent strings
provider_view = navigate_to(provider, "Details") # resetter selects summary view
if provider_view.entities.summary("Relationships").get_text_of(relationship) == "0":
- pytest.skip("There are no relationships for {}".format(relationship))
+ pytest.skip(f"There are no relationships for {relationship}")
obj = get_obj(relationship, appliance, provider=provider)
provider_view.entities.summary("Relationships").click_at(relationship)
relationship_view = appliance.browser.create_view(view, additional_context={'object': obj})
@@ -213,7 +213,7 @@ def _finalize():
provider.remove_tag(tag=tag)
if not actual_visibility:
- pytest.skip("There are no relationships for {}".format(relationship))
+ pytest.skip(f"There are no relationships for {relationship}")
with user_restricted:
actual_visibility = _check_actual_visibility(rel_cls)
diff --git a/cfme/tests/cloud_infra_common/test_rest_providers.py b/cfme/tests/cloud_infra_common/test_rest_providers.py
index 729c1efa5a..7e362d7ee5 100644
--- a/cfme/tests/cloud_infra_common/test_rest_providers.py
+++ b/cfme/tests/cloud_infra_common/test_rest_providers.py
@@ -66,7 +66,7 @@ def test_query_provider_attributes(provider, provider_rest, soft_assert):
outcome = query_resource_attributes(provider_rest)
for failure in outcome.failed:
# once BZ1546112 is fixed other failure than internal server error is expected
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
@@ -137,7 +137,7 @@ def _refresh_success():
fail_func=task.reload,
num_sec=30,
)
- assert task.status.lower() == "ok", "Task failed with status '{}'".format(task.status)
+ assert task.status.lower() == "ok", f"Task failed with status '{task.status}'"
@pytest.mark.rhv3
diff --git a/cfme/tests/cloud_infra_common/test_snapshots_rest.py b/cfme/tests/cloud_infra_common/test_snapshots_rest.py
index 787244a7ea..7b2f7787cb 100644
--- a/cfme/tests/cloud_infra_common/test_snapshots_rest.py
+++ b/cfme/tests/cloud_infra_common/test_snapshots_rest.py
@@ -101,7 +101,7 @@ def vm_snapshot(appliance, vm):
snap.wait_not_exists(num_sec=300, delay=5)
-class TestRESTSnapshots(object):
+class TestRESTSnapshots:
"""Tests actions with VM/instance snapshots using REST API."""
@pytest.mark.rhv2
diff --git a/cfme/tests/cloud_infra_common/test_tag_objects.py b/cfme/tests/cloud_infra_common/test_tag_objects.py
index b1f85c3a47..6100198325 100644
--- a/cfme/tests/cloud_infra_common/test_tag_objects.py
+++ b/cfme/tests/cloud_infra_common/test_tag_objects.py
@@ -92,12 +92,12 @@ def _tagging_check(test_item, tag_place):
test_item.add_tag(tag=tag, details=tag_place)
tags = test_item.get_tags()
assert tag in tags, (
- "{}: {} not in ({})".format(tag.category.display_name, tag.display_name, tags))
+ f"{tag.category.display_name}: {tag.display_name} not in ({tags})")
test_item.remove_tag(tag=tag, details=tag_place)
tags = test_item.get_tags()
assert tag not in tags, (
- "{}: {} in ({})".format(tag.category.display_name, tag.display_name, tags))
+ f"{tag.category.display_name}: {tag.display_name} in ({tags})")
request.addfinalizer(lambda: tag_cleanup(test_item, tag))
return _tagging_check
diff --git a/cfme/tests/cloud_infra_common/test_tag_visibility.py b/cfme/tests/cloud_infra_common/test_tag_visibility.py
index 78315bfb3f..1137a0bcfb 100644
--- a/cfme/tests/cloud_infra_common/test_tag_visibility.py
+++ b/cfme/tests/cloud_infra_common/test_tag_visibility.py
@@ -134,7 +134,7 @@ def _check_vm_visibility(group, vm, vis_expect):
except ItemNotFound:
actual_visibility = False
assert actual_visibility == vis_expect, (
- 'VM visibility is not as expected, expected {}'.format(vis_expect)
+ f'VM visibility is not as expected, expected {vis_expect}'
)
return _check_vm_visibility
diff --git a/cfme/tests/cloud_infra_common/test_vm_instance_analysis.py b/cfme/tests/cloud_infra_common/test_vm_instance_analysis.py
index 3ab381e430..daeb699a3b 100644
--- a/cfme/tests/cloud_infra_common/test_vm_instance_analysis.py
+++ b/cfme/tests/cloud_infra_common/test_vm_instance_analysis.py
@@ -189,7 +189,7 @@ def _hosts_remove_creds():
def set_agent_creds(appliance, request, provider):
version = appliance.version.vstring
- docker_image_name = "simaishi/amazon-ssa:{}".format(version)
+ docker_image_name = f"simaishi/amazon-ssa:{version}"
unique_agent = fauxfactory.gen_alpha(length=20, start="test_ssa_agent-")
agent_data = {
"ems": {
@@ -476,7 +476,7 @@ def schedule_ssa(appliance, ssa_vm, wait_for_task_result=True):
ss.enable()
if wait_for_task_result:
task = appliance.collections.tasks.instantiate(
- name='Scan from Vm {}'.format(ssa_vm.name), tab='AllTasks')
+ name=f'Scan from Vm {ssa_vm.name}', tab='AllTasks')
task.wait_for_finished()
return ss
@@ -499,13 +499,13 @@ def _compare_linux_vm_data(ssa_vm):
current_services = view.entities.summary('Configuration').get_text_of('Init Processes')
soft_assert(current_users == expected_users,
- "users: '{}' != '{}'".format(current_users, expected_users))
+ f"users: '{current_users}' != '{expected_users}'")
soft_assert(current_groups == expected_groups,
- "groups: '{}' != '{}'".format(current_groups, expected_groups))
+ f"groups: '{current_groups}' != '{expected_groups}'")
soft_assert(current_packages == expected_packages,
- "packages: '{}' != '{}'".format(current_packages, expected_packages))
+ f"packages: '{current_packages}' != '{expected_packages}'")
soft_assert(current_services == expected_services,
- "services: '{}' != '{}'".format(current_services, expected_services))
+ f"services: '{current_services}' != '{expected_services}'")
return _compare_linux_vm_data
@@ -526,14 +526,14 @@ def _compare_windows_vm_data(ssa_vm):
current_fs_drivers = view.entities.summary('Configuration')\
.get_text_of('File System Drivers')
- soft_assert(current_patches != '0', "patches: '{}' != '0'".format(current_patches))
+ soft_assert(current_patches != '0', f"patches: '{current_patches}' != '0'")
soft_assert(current_applications != '0', "applications: '{}' != '0'".format(
current_applications))
soft_assert(current_win32_services != '0',
- "win32 services: '{}' != '0'".format(current_win32_services))
+ f"win32 services: '{current_win32_services}' != '0'")
soft_assert(current_kernel_drivers != '0',
- "kernel drivers: '{}' != '0'".format(current_kernel_drivers))
- soft_assert(current_fs_drivers != '0', "fs drivers: '{}' != '0'".format(current_fs_drivers))
+ f"kernel drivers: '{current_kernel_drivers}' != '0'")
+ soft_assert(current_fs_drivers != '0', f"fs drivers: '{current_fs_drivers}' != '0'")
return _compare_windows_vm_data
@@ -565,7 +565,7 @@ def test_ssa_template(local_setup_provider, provider, soft_assert, vm_analysis_p
quadicon_os_icon = template.find_quadicon().data['os']
view = navigate_to(template, 'Details')
details_os_icon = view.entities.summary('Properties').get_text_of('Operating System')
- logger.info("Icons: {}, {}".format(details_os_icon, quadicon_os_icon))
+ logger.info(f"Icons: {details_os_icon}, {quadicon_os_icon}")
c_users = view.entities.summary('Security').get_text_of('Users')
c_groups = view.entities.summary('Security').get_text_of('Groups')
@@ -577,9 +577,9 @@ def test_ssa_template(local_setup_provider, provider, soft_assert, vm_analysis_p
c_users, c_groups, c_packages))
if vm_analysis_provisioning_data['fs-type'] not in ['ntfs', 'fat32']:
- soft_assert(c_users != '0', "users: '{}' != '0'".format(c_users))
- soft_assert(c_groups != '0', "groups: '{}' != '0'".format(c_groups))
- soft_assert(c_packages != '0', "packages: '{}' != '0'".format(c_packages))
+ soft_assert(c_users != '0', f"users: '{c_users}' != '0'")
+ soft_assert(c_groups != '0', f"groups: '{c_groups}' != '0'")
+ soft_assert(c_packages != '0', f"packages: '{c_packages}' != '0'")
else:
# Make sure windows-specific data is not empty
compare_windows_vm_data(ssa_vm)
@@ -603,7 +603,7 @@ def test_ssa_compliance(local_setup_provider, ssa_compliance_profile, ssa_vm,
"""
ssa_vm.smartstate_scan(wait_for_task_result=True)
task = appliance.collections.tasks.instantiate(
- name='Scan from Vm {}'.format(ssa_vm.name), tab='AllTasks')
+ name=f'Scan from Vm {ssa_vm.name}', tab='AllTasks')
task.wait_for_finished()
# Check release and quadicon
quadicon_os_icon = ssa_vm.find_quadicon().data['os']
@@ -614,9 +614,9 @@ def test_ssa_compliance(local_setup_provider, ssa_compliance_profile, ssa_vm,
soft_assert(c_lastanalyzed != 'Never', "Last Analyzed is set to Never")
soft_assert(vm_system_type in details_os_icon.lower(),
- "details icon: '{}' not in '{}'".format(vm_system_type, details_os_icon))
+ f"details icon: '{vm_system_type}' not in '{details_os_icon}'")
soft_assert(vm_system_type in quadicon_os_icon.lower(),
- "quad icon: '{}' not in '{}'".format(vm_system_type, quadicon_os_icon))
+ f"quad icon: '{vm_system_type}' not in '{quadicon_os_icon}'")
if ssa_vm.system_type != WINDOWS:
compare_linux_vm_data(ssa_vm)
@@ -652,9 +652,9 @@ def test_ssa_schedule(ssa_vm, schedule_ssa, soft_assert, vm_system_type,
# RHEL has 'Red Hat' in details_os_icon, but 'redhat' in quadicon_os_icon
os_type = vm_system_type if vm_system_type != 'redhat' else 'red hat'
soft_assert(os_type in details_os_icon.lower(),
- "details icon: '{}' not in '{}'".format(vm_system_type, details_os_icon))
+ f"details icon: '{vm_system_type}' not in '{details_os_icon}'")
soft_assert(vm_system_type in quadicon_os_icon.lower(),
- "quad icon: '{}' not in '{}'".format(vm_system_type, quadicon_os_icon))
+ f"quad icon: '{vm_system_type}' not in '{quadicon_os_icon}'")
if ssa_vm.system_type != WINDOWS:
compare_linux_vm_data(ssa_vm)
@@ -690,9 +690,9 @@ def test_ssa_vm(ssa_vm, scanned_vm, soft_assert, vm_system_type,
# RHEL has 'Red Hat' in details_os_icon, but 'redhat' in quadicon_os_icon
os_type = vm_system_type if vm_system_type != 'redhat' else 'red hat'
soft_assert(os_type in details_os_icon.lower(),
- "details icon: '{}' not in '{}'".format(os_type, details_os_icon))
+ f"details icon: '{os_type}' not in '{details_os_icon}'")
soft_assert(vm_system_type in quadicon_os_icon.lower(),
- "quad icon: '{}' not in '{}'".format(vm_system_type, quadicon_os_icon))
+ f"quad icon: '{vm_system_type}' not in '{quadicon_os_icon}'")
if ssa_vm.system_type != WINDOWS:
compare_linux_vm_data(ssa_vm)
@@ -743,7 +743,7 @@ def test_ssa_users(ssa_vm):
details_property_view.paginator.find_row_on_pages(
details_property_view.table, name=username)
except NoSuchElementException:
- pytest.fail('User {} was not found in details table after SSA run'.format(username))
+ pytest.fail(f'User {username} was not found in details table after SSA run')
@pytest.mark.rhv3
@@ -786,7 +786,7 @@ def test_ssa_groups(ssa_vm):
details_property_view.paginator.find_row_on_pages(
details_property_view.table, name=group)
except NoSuchElementException:
- pytest.fail('Group {} was not found in details table after SSA run'.format(group))
+ pytest.fail(f'Group {group} was not found in details table after SSA run')
@pytest.mark.long_running
@@ -811,7 +811,7 @@ def test_ssa_packages(ssa_vm):
pytest.skip("Windows has no packages")
if 'package' not in list(ssa_vm.system_type.keys()):
- pytest.skip("Don't know how to update packages for {}".format(ssa_vm.system_type))
+ pytest.skip(f"Don't know how to update packages for {ssa_vm.system_type}")
package_name = ssa_vm.system_type['package']
package_command = ssa_vm.system_type['install-command']
@@ -836,7 +836,7 @@ def test_ssa_packages(ssa_vm):
details_property_view.paginator.find_row_on_pages(
details_property_view.table, name=package_name)
except NoSuchElementException:
- pytest.fail('Package {} was not found in details table after SSA run'.format(package_name))
+ pytest.fail(f'Package {package_name} was not found in details table after SSA run')
@pytest.mark.long_running
@@ -921,7 +921,7 @@ def test_drift_analysis(request, ssa_vm, soft_assert, appliance):
# check drift difference
soft_assert(
ssa_vm.equal_drift_results(
- '{} (1)'.format(added_tag.category.display_name),
+ f'{added_tag.category.display_name} (1)',
'My Company Tags',
0,
1
@@ -936,15 +936,15 @@ def test_drift_analysis(request, ssa_vm, soft_assert, appliance):
drift_analysis_view.toolbar.same_values_attributes.click()
soft_assert(
not drift_analysis_view.drift_analysis.check_section_attribute_availability(
- '{}'.format(added_tag.category.display_name)),
- "{} row should be hidden, but not".format(added_tag.display_name))
+ f'{added_tag.category.display_name}'),
+ f"{added_tag.display_name} row should be hidden, but not")
# Accounting tag should be displayed now
drift_analysis_view.toolbar.different_values_attributes.click()
soft_assert(
drift_analysis_view.drift_analysis.check_section_attribute_availability(
- '{} (1)'.format(added_tag.category.display_name)),
- "{} row should be visible, but not".format(added_tag.display_name))
+ f'{added_tag.category.display_name} (1)'),
+ f"{added_tag.display_name} row should be visible, but not")
@pytest.mark.tier(2)
@@ -979,7 +979,7 @@ def test_ssa_multiple_vms(ssa_multiple_vms, soft_assert, appliance, compare_linu
for ssa_vm in ssa_multiple_vms:
# check SSA results for all created vms
task = appliance.collections.tasks.instantiate(
- name='Scan from Vm {}'.format(ssa_vm.name), tab='AllTasks')
+ name=f'Scan from Vm {ssa_vm.name}', tab='AllTasks')
task.wait_for_finished()
current_lastanalyzed = ssa_vm.last_analysed
diff --git a/cfme/tests/cloud_infra_common/test_vm_ownership.py b/cfme/tests/cloud_infra_common/test_vm_ownership.py
index e1a3039cd1..b6cc83bfb9 100644
--- a/cfme/tests/cloud_infra_common/test_vm_ownership.py
+++ b/cfme/tests/cloud_infra_common/test_vm_ownership.py
@@ -30,7 +30,7 @@ def vm_crud(provider):
try:
vm.create_on_provider(find_in_cfme=True, allow_skip="default")
except KeyError:
- msg = 'Missing template for provider {}'.format(provider.key)
+ msg = f'Missing template for provider {provider.key}'
logger.exception(msg)
pytest.skip(msg)
yield vm
diff --git a/cfme/tests/configure/test_access_control.py b/cfme/tests/configure/test_access_control.py
index 182a8fc9ba..c8af1478fc 100644
--- a/cfme/tests/configure/test_access_control.py
+++ b/cfme/tests/configure/test_access_control.py
@@ -90,7 +90,7 @@ def setup_openldap_user_group(appliance, two_child_tenants, openldap_auth_provid
for group in ldap_user.groups:
if 'evmgroup' not in group.lower():
# create group in CFME via retrieve_group which looks it up on auth_provider
- logger.info('Retrieving a user group that is non evm built-in: {}'.format(group))
+ logger.info(f'Retrieving a user group that is non evm built-in: {group}')
tenant = 'My Company/marketing' if group == 'marketing' else 'My Company/finance'
retrieved_groups.append(retrieve_group(appliance,
'ldap',
@@ -170,7 +170,7 @@ def test_user_crud(appliance):
user = new_user(appliance, [group])
with update(user):
- user.name = "{}edited".format(user.name)
+ user.name = f"{user.name}edited"
copied_user = user.copy()
copied_user.delete()
user.delete()
@@ -571,7 +571,7 @@ def test_group_crud(appliance):
group = group_collection.create(
description=fauxfactory.gen_alphanumeric(start="grp_"), role=role)
with update(group):
- group.description = "{}edited".format(group.description)
+ group.description = f"{group.description}edited"
group.delete()
@@ -843,7 +843,7 @@ def test_role_crud(appliance):
],
)
with update(role):
- role.name = "{}edited".format(role.name)
+ role.name = f"{role.name}edited"
copied_role = role.copy()
copied_role.delete()
role.delete()
@@ -989,7 +989,7 @@ def _test_vm_provision(appliance):
def _test_vm_removal(appliance, provider):
logger.info("Testing for VM removal permission")
vm = appliance.collections.infra_vms.all()[0] # pick first vm from collection
- logger.debug("VM {} selected".format(vm.name))
+ logger.debug(f"VM {vm.name} selected")
vm.delete(cancel=True)
@@ -1153,7 +1153,7 @@ def test_permissions(appliance, product_features, allowed_actions, disallowed_ac
if fails:
message = ''
for failure in fails.values():
- message = "{}\n\n{}".format(message, failure)
+ message = f"{message}\n\n{failure}"
raise Exception(message)
finally:
appliance.server.login_admin()
@@ -1330,7 +1330,7 @@ def test_delete_default_tenant(appliance):
"""
view = navigate_to(appliance.collections.tenants, "All")
roottenant = appliance.collections.tenants.get_root_tenant()
- msg = 'Default Tenant "{}" can not be deleted'.format(roottenant.name)
+ msg = f'Default Tenant "{roottenant.name}" can not be deleted'
tenant = appliance.collections.tenants.instantiate(name=roottenant.name)
appliance.collections.tenants.delete(tenant)
assert view.flash.assert_message(msg)
@@ -1370,9 +1370,9 @@ def _delete_tenant():
tenant.delete()
with update(tenant):
- tenant.description = "{}edited".format(tenant.description)
+ tenant.description = f"{tenant.description}edited"
with update(tenant):
- tenant.name = "{}edited".format(tenant.name)
+ tenant.name = f"{tenant.name}edited"
tenant.delete()
@@ -1417,9 +1417,9 @@ def _delete_tenant_and_project():
item.delete()
with update(project):
- project.description = "{}edited".format(project.description)
+ project.description = f"{project.description}edited"
with update(project):
- project.name = "{}_edited".format(project.name)
+ project.name = f"{project.name}_edited"
project.delete()
tenant.delete()
@@ -1466,9 +1466,9 @@ def _delete_tenants():
tenant_update = tenant.parent_tenant
with update(tenant_update):
- tenant_update.description = "{}edited".format(tenant_update.description)
+ tenant_update.description = f"{tenant_update.description}edited"
with update(tenant_update):
- tenant_update.name = "{}edited".format(tenant_update.name)
+ tenant_update.name = f"{tenant_update.name}edited"
@pytest.mark.tier(3)
@@ -1541,7 +1541,7 @@ def test_superadmin_tenant_admin_crud(appliance):
user = new_user(appliance, [group])
assert user.exists
with update(user):
- user.name = "{}_edited".format(user.name)
+ user.name = f"{user.name}_edited"
user.delete()
assert not user.exists
@@ -1576,7 +1576,7 @@ def test_tenantadmin_group_crud(child_tenant_admin_user, tenant_role, child_tena
assert group.exists
with update(group):
- group.description = "{}edited".format(group.description)
+ group.description = f"{group.description}edited"
group.delete()
assert not group.exists
@@ -1941,7 +1941,7 @@ def test_superadmin_child_tenant_delete_parent_catalog(appliance, request):
group_collection = appliance.collections.groups
group = group_collection.create(description=fauxfactory.gen_alphanumeric(start="grp_"),
role="EvmRole-super_administrator",
- tenant="{}/{}".format(root_tenant.name, new_tenant.name))
+ tenant=f"{root_tenant.name}/{new_tenant.name}")
user = new_user(appliance, [group])
@request.addfinalizer
@@ -2072,14 +2072,14 @@ def test_tenant_ldap_group_switch_between_tenants(appliance, setup_openldap_auth
soft_assert(other_group in user.groups,
f"Group {other_group} in UI not expected for user {user.name}")
view.change_group(other_group)
- assert view.is_displayed, (u'Not logged in after switching to group {} for {}'
+ assert view.is_displayed, ('Not logged in after switching to group {} for {}'
.format(other_group, user.name))
# assert selected group has changed
soft_assert(other_group == view.current_groupname,
f"After switching to group {other_group}, its not displayed as active")
appliance.server.login_admin()
- assert user.exists, 'User record for "{}" should exist after login'.format(user.name)
+ assert user.exists, f'User record for "{user.name}" should exist after login'
@pytest.mark.manual
diff --git a/cfme/tests/configure/test_analysis_profiles.py b/cfme/tests/configure/test_analysis_profiles.py
index 1fefe60326..641553af51 100644
--- a/cfme/tests/configure/test_analysis_profiles.py
+++ b/cfme/tests/configure/test_analysis_profiles.py
@@ -33,7 +33,7 @@
# RBAC for roles
PRODUCT_FEATURES_DIALOG = [
["Everything", "Automation", "Automate", "Customization", "Dialogs", "Modify"]
- + [op, "{operation} ({tenant})".format(operation=op, tenant=TENANT_NAME)]
+ + [op, f"{op} ({TENANT_NAME})"]
for op in OPERATIONS
]
@@ -49,7 +49,7 @@
"Modify",
"Manage Quotas",
]
- + ["Manage Quotas ({tenant})".format(tenant=tenant)]
+ + [f"Manage Quotas ({tenant})"]
for tenant in ["My Company", TENANT_NAME]
]
@@ -93,36 +93,36 @@ def test_vm_analysis_profile_crud(appliance, soft_assert, analysis_profile_colle
view = appliance.browser.create_view(
navigator.get_class(analysis_profile_collection, 'All').VIEW)
vm_flash = vm_profile.name if appliance.version < '5.10' else vm_profile.description
- view.flash.assert_message('Analysis Profile "{}" was saved'.format(vm_flash))
+ view.flash.assert_message(f'Analysis Profile "{vm_flash}" was saved')
assert vm_profile.exists
with update(vm_profile):
vm_profile.files = updated_files
view = appliance.browser.create_view(navigator.get_class(vm_profile, 'Details').VIEW)
- view.flash.assert_success_message('Analysis Profile "{}" was saved'.format(vm_flash))
+ view.flash.assert_success_message(f'Analysis Profile "{vm_flash}" was saved')
soft_assert(vm_profile.files == updated_files,
- 'Files update failed on profile: {}, {}'.format(vm_profile.name, vm_profile.files))
+ f'Files update failed on profile: {vm_profile.name}, {vm_profile.files}')
with update(vm_profile):
vm_profile.categories = ['System']
soft_assert(vm_profile.categories == ['System'],
- 'Categories update failed on profile: {}'.format(vm_profile.name))
- copied_profile = vm_profile.copy(new_name='copied-{}'.format(vm_profile.name))
+ f'Categories update failed on profile: {vm_profile.name}')
+ copied_profile = vm_profile.copy(new_name=f'copied-{vm_profile.name}')
view = appliance.browser.create_view(
navigator.get_class(analysis_profile_collection, 'All').VIEW)
# yep, not copy specific
vm_copied_flash = (
copied_profile.name if appliance.version < '5.10' else copied_profile.description
)
- view.flash.assert_message('Analysis Profile "{}" was saved'.format(vm_copied_flash))
+ view.flash.assert_message(f'Analysis Profile "{vm_copied_flash}" was saved')
assert copied_profile.exists
copied_profile.delete()
assert not copied_profile.exists
vm_profile.delete()
- view.flash.assert_success_message('Analysis Profile "{}": Delete successful'.format(vm_flash))
+ view.flash.assert_success_message(f'Analysis Profile "{vm_flash}": Delete successful')
assert not vm_profile.exists
@@ -147,7 +147,7 @@ def test_host_analysis_profile_crud(appliance, soft_assert, analysis_profile_col
view = appliance.browser.create_view(
navigator.get_class(analysis_profile_collection, 'All').VIEW)
host_flash = host_profile.name if appliance.version < '5.10' else host_profile.description
- view.flash.assert_message('Analysis Profile "{}" was saved'.format(host_flash))
+ view.flash.assert_message(f'Analysis Profile "{host_flash}" was saved')
assert host_profile.exists
with update(host_profile):
@@ -155,20 +155,20 @@ def test_host_analysis_profile_crud(appliance, soft_assert, analysis_profile_col
soft_assert(host_profile.files == updated_files,
'Files update failed on profile: {}, {}'
.format(host_profile.name, host_profile.files))
- copied_profile = host_profile.copy(new_name='copied-{}'.format(host_profile.name))
+ copied_profile = host_profile.copy(new_name=f'copied-{host_profile.name}')
view = appliance.browser.create_view(
navigator.get_class(analysis_profile_collection, 'All').VIEW)
host_copied_flash = (
copied_profile.name if appliance.version < '5.10' else copied_profile.description
)
- view.flash.assert_message('Analysis Profile "{}" was saved'.format(host_copied_flash))
+ view.flash.assert_message(f'Analysis Profile "{host_copied_flash}" was saved')
assert copied_profile.exists
copied_profile.delete()
assert not copied_profile.exists
host_profile.delete()
- view.flash.assert_success_message('Analysis Profile "{}": Delete successful'.format(host_flash))
+ view.flash.assert_success_message(f'Analysis Profile "{host_flash}": Delete successful')
assert not host_profile.exists
diff --git a/cfme/tests/configure/test_db_backup_schedule.py b/cfme/tests/configure/test_db_backup_schedule.py
index 12b2c55d9c..1a05d6c7fa 100644
--- a/cfme/tests/configure/test_db_backup_schedule.py
+++ b/cfme/tests/configure/test_db_backup_schedule.py
@@ -61,7 +61,7 @@ def _get_credentials(self):
"No 'credentials' key found for machine {machine_id}".format(**self.__dict__)
assert creds_key in conf.credentials and conf.credentials[creds_key],\
- "No credentials for key '{}' found in credentials yaml".format(creds_key)
+ f"No credentials for key '{creds_key}' found in credentials yaml"
credentials = conf.credentials[creds_key]
return credentials
@@ -72,7 +72,7 @@ def _get_data(self, protocol_data, protocol_type):
data = {}
for key in self.required_keys[protocol_type]:
assert key in protocol_data and protocol_data[key],\
- "'{}' key must be set for scheduled {} backup to work".format(key, protocol_type)
+ f"'{key}' key must be set for scheduled {protocol_type} backup to work"
data[key] = protocol_data[key]
return data
@@ -118,7 +118,7 @@ def get_schedulable_datetime():
def get_ssh_client(hostname, credentials):
""" Returns fresh ssh client connected to given server using given credentials
"""
- hostname = urlparse('scheme://{}'.format(hostname)).netloc
+ hostname = urlparse(f'scheme://{hostname}').netloc
connect_kwargs = {
'username': credentials['username'],
'password': credentials['password'],
@@ -132,7 +132,7 @@ def get_full_path_to_file(path_on_host, schedule_name):
"""
if not path_on_host.endswith('/'):
path_on_host += '/'
- full_path = '{}db_backup/region_*/{}'.format(path_on_host, schedule_name)
+ full_path = f'{path_on_host}db_backup/region_*/{schedule_name}'
return full_path
@@ -153,7 +153,7 @@ def test_db_backup_schedule(request, db_backup_data, depot_machine_ip, appliance
# the dash is there to make strftime not use a leading zero
hour = dt.strftime('%-H')
minute = dt.strftime('%-M')
- db_depot_uri = '{}{}'.format(depot_machine_ip, db_backup_data.sub_folder)
+ db_depot_uri = f'{depot_machine_ip}{db_backup_data.sub_folder}'
sched_args = {
'name': db_backup_data.schedule_name,
'description': db_backup_data.schedule_description,
@@ -181,7 +181,7 @@ def test_db_backup_schedule(request, db_backup_data, depot_machine_ip, appliance
})
if db_backup_data.protocol_type == 'nfs':
- path_on_host = urlparse('nfs://{}'.format(db_depot_uri)).path
+ path_on_host = urlparse(f'nfs://{db_depot_uri}').path
else:
path_on_host = db_backup_data.path_on_host
full_path = get_full_path_to_file(path_on_host, db_backup_data.schedule_name)
@@ -192,7 +192,7 @@ def test_db_backup_schedule(request, db_backup_data, depot_machine_ip, appliance
# ---- Add cleanup finalizer
def delete_sched_and_files():
with get_ssh_client(db_depot_uri, db_backup_data.credentials) as ssh_client:
- ssh_client.run_command('rm -rf {}'.format(full_path), ensure_user=True)
+ ssh_client.run_command(f'rm -rf {full_path}', ensure_user=True)
sched.delete()
request.addfinalizer(delete_sched_and_files)
@@ -214,10 +214,10 @@ def delete_sched_and_files():
# ---- Check if the db backup file exists
with get_ssh_client(db_depot_uri, db_backup_data.credentials) as ssh_client:
- assert ssh_client.run_command('cd "{}"'.format(path_on_host), ensure_user=True).success, (
- "Could not cd into '{}' over ssh".format(path_on_host))
+ assert ssh_client.run_command(f'cd "{path_on_host}"', ensure_user=True).success, (
+ f"Could not cd into '{path_on_host}' over ssh")
# Find files no more than 5 minutes old, count them and remove newline
- file_check_cmd = "find {}/* -cmin -5 | wc -l | tr -d '\n' ".format(full_path)
+ file_check_cmd = f"find {full_path}/* -cmin -5 | wc -l | tr -d '\n' "
# Note that this check is not sufficient. It seems the file may be
# present, but there is no check whether it is sane backup. For example
@@ -227,7 +227,7 @@ def delete_sched_and_files():
lambda: ssh_client.run_command(file_check_cmd, ensure_user=True).output == '1',
delay=5,
num_sec=60,
- message="File '{}' not found on share".format(full_path)
+ message=f"File '{full_path}' not found on share"
)
# ----
diff --git a/cfme/tests/configure/test_default_views_cloud.py b/cfme/tests/configure/test_default_views_cloud.py
index 189b8a4d80..26d296bdea 100644
--- a/cfme/tests/configure/test_default_views_cloud.py
+++ b/cfme/tests/configure/test_default_views_cloud.py
@@ -66,7 +66,7 @@ def test_cloud_default_view(appliance, group_name, expected_view):
# gtl_params.values(), source of page, are mix of class and collection name
nav_cls = getattr(appliance.collections, page) if isinstance(page, str) else page
selected_view = navigate_to(nav_cls, 'All', use_resetter=False).toolbar.view_selector.selected
- assert expected_view == selected_view, '{} view setting failed'.format(expected_view)
+ assert expected_view == selected_view, f'{expected_view} view setting failed'
default_views.set_default_view(group_name, old_default, fieldset='Clouds')
@@ -97,5 +97,5 @@ def test_cloud_compare_view(appliance, expected_view):
[e.ensure_checked() for e in inst_view.entities.get_all(slice=e_slice)]
inst_view.toolbar.configuration.item_select('Compare Selected items')
selected_view = getattr(inst_view.actions, selector_type).selected
- assert expected_view == selected_view, '{} setting failed'.format(expected_view)
+ assert expected_view == selected_view, f'{expected_view} setting failed'
default_views.set_default_view(group_name, old_default)
diff --git a/cfme/tests/configure/test_default_views_infra.py b/cfme/tests/configure/test_default_views_infra.py
index 6c6ca90cc5..3429616475 100644
--- a/cfme/tests/configure/test_default_views_infra.py
+++ b/cfme/tests/configure/test_default_views_infra.py
@@ -115,7 +115,7 @@ def test_infra_default_view(appliance, group_name, view):
if group_name == 'VMs':
dest = 'VMsOnly'
selected_view = navigate_to(page, dest, use_resetter=False).toolbar.view_selector.selected
- assert view == selected_view, '{} view setting failed'.format(view)
+ assert view == selected_view, f'{view} view setting failed'
default_views.set_default_view(group_name, old_default)
@@ -144,7 +144,7 @@ def test_infra_compare_view(appliance, expected_view):
[e.ensure_checked() for e in vm_view.entities.get_all(slice=e_slice)]
vm_view.toolbar.configuration.item_select('Compare Selected items')
selected_view = getattr(vm_view.actions, selector_type).selected
- assert expected_view == selected_view, '{} setting failed'.format(expected_view)
+ assert expected_view == selected_view, f'{expected_view} setting failed'
default_views.set_default_view(group_name, old_default)
diff --git a/cfme/tests/configure/test_log_depot_operation.py b/cfme/tests/configure/test_log_depot_operation.py
index b00369f51b..0bc04971c5 100644
--- a/cfme/tests/configure/test_log_depot_operation.py
+++ b/cfme/tests/configure/test_log_depot_operation.py
@@ -21,7 +21,7 @@
pytestmark = [pytest.mark.long_running, test_requirements.log_depot]
-class LogDepotType(object):
+class LogDepotType:
def __init__(self, protocol, credentials, access_dir=None, path=None):
self.protocol = protocol
self._param_name = self.protocol
@@ -121,7 +121,7 @@ def configured_depot(log_depot, depot_machine_ip, appliance):
It also provides a finalizer to disable the depot after test run.
"""
log_depot.machine_ip = depot_machine_ip
- uri = '{}{}'.format(log_depot.machine_ip, log_depot.access_dir)
+ uri = f'{log_depot.machine_ip}{log_depot.access_dir}'
server_log_depot = appliance.server.collect_logs
with update(server_log_depot):
server_log_depot.depot_type = log_depot.protocol
@@ -134,21 +134,21 @@ def configured_depot(log_depot, depot_machine_ip, appliance):
def check_ftp(appliance, ftp, server_name, server_zone_id, check_contents=False):
- server_string = '{}_{}'.format(server_name, server_zone_id)
+ server_string = f'{server_name}_{server_zone_id}'
with ftp:
# Files must have been created after start with server string in it (for ex. EVM_1)
date_group = '(_.*?){4}'
zip_files = ftp.filesystem.search(re.compile(
- r"^.*{}{}[.]zip$".format(server_string, date_group)), directories=False)
+ fr"^.*{server_string}{date_group}[.]zip$"), directories=False)
assert zip_files, "No logs found!"
# Collection of Models and Dialogs introduced in 5.10 but it work only in 5.11 (BZ 1656318)
if appliance.version >= "5.11" and not BZ(1706989).blocks:
models_files = ftp.filesystem.search(re.compile(
- r"^Models_.*{}[.]zip$".format(server_string)), directories=False
+ fr"^Models_.*{server_string}[.]zip$"), directories=False
)
assert models_files, 'No models files found'
dialogs_files = ftp.filesystem.search(re.compile(
- r"^Dialogs_.*{}[.]zip$".format(server_string)), directories=False
+ fr"^Dialogs_.*{server_string}[.]zip$"), directories=False
)
assert dialogs_files, 'No dialogs files found'
@@ -173,7 +173,7 @@ def check_ftp(appliance, ftp, server_name, server_zone_id, check_contents=False)
if "ansible" in log and BZ(1751961).blocks:
continue
result = log_ssh.run_command(
- "unzip -l ~{} | grep {}".format(zip_file.path, log), ensure_user=True
+ f"unzip -l ~{zip_file.path} | grep {log}", ensure_user=True
)
assert log in result.output
log_file_size = result.output.split()[0]
@@ -303,7 +303,7 @@ def _clear_ftp():
ftp.recursively_delete()
with appliance:
- uri = '{}{}'.format(log_depot.machine_ip, log_depot.access_dir)
+ uri = f'{log_depot.machine_ip}{log_depot.access_dir}'
with update(collect_logs):
collect_logs.second_server_collect = from_secondary
collect_logs.depot_type = log_depot.protocol
@@ -355,7 +355,7 @@ def _clear_ftp():
# delete all files
ftp.recursively_delete()
- uri = '{}{}'.format(log_depot.machine_ip, log_depot.access_dir)
+ uri = f'{log_depot.machine_ip}{log_depot.access_dir}'
collect_logs = (
appliance.server.zone.collect_logs if zone_collect else appliance.server.collect_logs)
with update(collect_logs):
diff --git a/cfme/tests/configure/test_logs.py b/cfme/tests/configure/test_logs.py
index 19d7ceae96..fafddd3d2d 100644
--- a/cfme/tests/configure/test_logs.py
+++ b/cfme/tests/configure/test_logs.py
@@ -62,7 +62,7 @@ def test_provider_log_rotate(appliance, provider, log_exists):
initialEstimate: 1/4h
casecomponent: Configuration
"""
- assert log_exists, "Log file {}.log doesn't exist".format(provider.log_name)
+ assert log_exists, f"Log file {provider.log_name}.log doesn't exist"
appliance.ssh_client.run_command("logrotate -f /etc/logrotate.d/miq_logs.conf")
logs_count = int(appliance.ssh_client.run_command(
"ls -l /var/www/miq/vmdb/log/{}.log*|wc -l".format(
@@ -92,7 +92,7 @@ def test_provider_log_updated(appliance, provider, log_exists):
initialEstimate: 1/4h
casecomponent: Configuration
"""
- assert log_exists, "Log file {}.log doesn't exist".format(provider.log_name)
+ assert log_exists, f"Log file {provider.log_name}.log doesn't exist"
log_before = appliance.ssh_client.run_command(
"md5sum /var/www/miq/vmdb/log/{}.log | awk '{{ print $1 }}'".format(
provider.log_name
@@ -132,12 +132,12 @@ def test_provider_log_level(appliance, provider, log_exists):
6. Check there are no info messages in the log
7. Reset log level back
"""
- assert log_exists, "Log file {}.log doesn't exist".format(provider.log_name)
- log_level = appliance.server.advanced_settings['log']['level_{}'.format(provider.log_name)]
+ assert log_exists, f"Log file {provider.log_name}.log doesn't exist"
+ log_level = appliance.server.advanced_settings['log'][f'level_{provider.log_name}']
log = f'/var/www/miq/vmdb/log/{provider.log_name}.log'
# set log level to info
wait_for(lambda: appliance.server.update_advanced_settings(
- {'log': {'level_{}'.format(provider.log_name): 'info'}}), timeout=300)
+ {'log': {f'level_{provider.log_name}': 'info'}}), timeout=300)
lv_info = LogValidator(log, matched_patterns=['.*INFO.*'], failure_patterns=['.*DEBUG.*'])
lv_info.start_monitoring()
provider.refresh_provider_relationships(wait=600)
@@ -145,7 +145,7 @@ def test_provider_log_level(appliance, provider, log_exists):
# set log level to warn
wait_for(lambda: appliance.server.update_advanced_settings(
- {'log': {'level_{}'.format(provider.log_name): 'warn'}}), timeout=300)
+ {'log': {f'level_{provider.log_name}': 'warn'}}), timeout=300)
lv = LogValidator(log, failure_patterns=['.*INFO.*'])
def _no_info():
@@ -161,4 +161,4 @@ def _no_info():
wait_for(_no_info, num_sec=900, delay=40, message="no INFOs in the log")
# set log level back
appliance.server.update_advanced_settings(
- {'log': {'level_{}'.format(provider.log_name): log_level}})
+ {'log': {f'level_{provider.log_name}': log_level}})
diff --git a/cfme/tests/configure/test_ntp_server.py b/cfme/tests/configure/test_ntp_server.py
index 73723ffb7b..9dc51b08bc 100644
--- a/cfme/tests/configure/test_ntp_server.py
+++ b/cfme/tests/configure/test_ntp_server.py
@@ -32,7 +32,7 @@ def appliance_date(appliance):
def check_ntp_grep(appliance, clock):
result = appliance.ssh_client.run_command(
- "cat /etc/chrony.conf| grep {}".format(clock))
+ f"cat /etc/chrony.conf| grep {clock}")
return not bool(result.rc)
@@ -104,7 +104,7 @@ def test_ntp_conf_file_update_check(request, appliance, empty_ntp_dict, ntp_serv
for clock in cfme_data['clock_servers']:
status, wait_time = wait_for(lambda: check_ntp_grep(appliance, clock),
fail_condition=False, num_sec=60, delay=5)
- assert status is True, "Clock value {} not update in /etc/chrony.conf file".format(clock)
+ assert status is True, f"Clock value {clock} not update in /etc/chrony.conf file"
# Unsetting the ntp server values
ntp_file_date_stamp = appliance.ssh_client.run_command(
@@ -115,7 +115,7 @@ def test_ntp_conf_file_update_check(request, appliance, empty_ntp_dict, ntp_serv
for clock in cfme_data['clock_servers']:
status, wait_time = wait_for(lambda: check_ntp_grep(appliance, clock),
fail_condition=True, num_sec=60, delay=5)
- assert status is False, "Found clock record '{}' in /etc/chrony.conf file".format(clock)
+ assert status is False, f"Found clock record '{clock}' in /etc/chrony.conf file"
@pytest.mark.tier(3)
diff --git a/cfme/tests/configure/test_paginator.py b/cfme/tests/configure/test_paginator.py
index 0078494320..fa0cc21ddc 100644
--- a/cfme/tests/configure/test_paginator.py
+++ b/cfme/tests/configure/test_paginator.py
@@ -161,7 +161,7 @@ def test_paginator_details_page(appliance, place_info, schedule):
if check_paginator_for_page(view):
paginator = view.paginator
- items_selector = Dropdown(view, '{} Items'.format(paginator.items_per_page))
+ items_selector = Dropdown(view, f'{paginator.items_per_page} Items')
msg = 'Not all options are present in items per page'
if view.extra.appliance.version < '5.11':
assert set(items_selection_5_10) == set(items_selector.items), msg
diff --git a/cfme/tests/configure/test_proxy.py b/cfme/tests/configure/test_proxy.py
index a302cf67d6..0b933937ae 100644
--- a/cfme/tests/configure/test_proxy.py
+++ b/cfme/tests/configure/test_proxy.py
@@ -20,7 +20,7 @@ def validate_proxy_logs(provider, utility_vm_ssh, appliance_ip):
def _is_ip_in_log():
provider.refresh_provider_relationships()
return utility_vm_ssh.run_command(
- "grep {} /var/log/squid/access.log".format(appliance_ip)).success
+ f"grep {appliance_ip} /var/log/squid/access.log").success
# need to wait until requests will occur in access.log or check if its empty after some time
wait_for(func=_is_ip_in_log, num_sec=300, delay=10,
diff --git a/cfme/tests/configure/test_region.py b/cfme/tests/configure/test_region.py
index 4d9c9e8f19..65efde4d16 100644
--- a/cfme/tests/configure/test_region.py
+++ b/cfme/tests/configure/test_region.py
@@ -47,7 +47,7 @@ def _reset_region_description(description, view):
request.addfinalizer(lambda: _reset_region_description(old_description, view))
view.region_description.fill(region_description)
view.save.click()
- view.flash.assert_message('Region "{}" was saved'.format(region_description))
+ view.flash.assert_message(f'Region "{region_description}" was saved')
view.redhat_updates.click()
reg = "Settings Region" if appliance.version < "5.10" else "CFME Region"
expected_title = '{reg} "{des} [{num}]"'.format(
diff --git a/cfme/tests/configure/test_register_appliance.py b/cfme/tests/configure/test_register_appliance.py
index 8101f2eced..e85b538157 100644
--- a/cfme/tests/configure/test_register_appliance.py
+++ b/cfme/tests/configure/test_register_appliance.py
@@ -101,7 +101,7 @@ def appliance_preupdate(temp_appliance_preconfig_funcscope):
def run(c):
assert appliance.ssh_client.run_command(c).success
- run('curl -o /etc/yum.repos.d/rpmrebuild.repo {}'.format(url))
+ run(f'curl -o /etc/yum.repos.d/rpmrebuild.repo {url}')
run('yum install rpmrebuild createrepo -y')
run('mkdir /myrepo')
run('rpmrebuild --release=99 cfme-appliance')
diff --git a/cfme/tests/configure/test_rest_access_control.py b/cfme/tests/configure/test_rest_access_control.py
index c09668805f..32340ea2d4 100644
--- a/cfme/tests/configure/test_rest_access_control.py
+++ b/cfme/tests/configure/test_rest_access_control.py
@@ -15,7 +15,7 @@
pytestmark = [test_requirements.rest]
-class TestTenantsViaREST(object):
+class TestTenantsViaREST:
@pytest.fixture(scope="function")
def tenants(self, request, appliance):
num_tenants = 3
@@ -137,7 +137,7 @@ def test_delete_tenants_from_collection(self, tenants):
delete_resources_from_collection(tenants)
-class TestRolesViaREST(object):
+class TestRolesViaREST:
@pytest.fixture(scope="function")
def roles(self, request, appliance):
num_roles = 3
@@ -310,7 +310,7 @@ def test_role_assign_and_unassign_feature(self, appliance, roles):
assert feature.id not in [f.id for f in role.features.all]
-class TestGroupsViaREST(object):
+class TestGroupsViaREST:
@pytest.fixture(scope="function")
def tenants(self, request, appliance):
return _tenants(request, appliance, num=1)
@@ -443,7 +443,7 @@ def test_delete_groups_from_collection(self, groups):
delete_resources_from_collection(groups, not_found=True)
-class TestUsersViaREST(object):
+class TestUsersViaREST:
@pytest.fixture(scope="function")
def users_data(self, request, appliance):
def _users_data(num=3):
@@ -518,8 +518,8 @@ def test_create_uppercase_user(self, request, appliance):
"""
uniq = fauxfactory.gen_alphanumeric(4).upper()
data = {
- "userid": "rest_{}".format(uniq),
- "name": "REST User {}".format(uniq),
+ "userid": f"rest_{uniq}",
+ "name": f"REST User {uniq}",
"password": fauxfactory.gen_alphanumeric(),
"email": "user@example.com",
"group": "EvmGroup-user_self_service",
diff --git a/cfme/tests/configure/test_schedule_operations.py b/cfme/tests/configure/test_schedule_operations.py
index 2326b422a0..748e275a99 100644
--- a/cfme/tests/configure/test_schedule_operations.py
+++ b/cfme/tests/configure/test_schedule_operations.py
@@ -71,7 +71,7 @@ def test_schedule_crud(appliance, current_server_time):
)
view = appliance.browser.create_view(BaseLoggedInPage)
- view.flash.assert_message('Schedule "{}" was saved'.format(schedule.name))
+ view.flash.assert_message(f'Schedule "{schedule.name}" was saved')
# test for bz 1569127
start_date_updated = start_date - relativedelta.relativedelta(days=1)
updates = {
@@ -80,16 +80,16 @@ def test_schedule_crud(appliance, current_server_time):
}
schedule.update(updates, cancel=True)
view.flash.assert_message(
- 'Edit of Schedule "{}" was cancelled by the user'.format(schedule.name))
+ f'Edit of Schedule "{schedule.name}" was cancelled by the user')
schedule.update(updates, reset=True)
view.flash.assert_message('All changes have been reset')
with update(schedule):
schedule.name = fauxfactory.gen_alphanumeric()
schedule.start_date = start_date_updated
- view.flash.assert_message('Schedule "{}" was saved'.format(schedule.name))
+ view.flash.assert_message(f'Schedule "{schedule.name}" was saved')
schedule.delete(cancel=True)
schedule.delete()
- view.flash.assert_message('Schedule "{}": Delete successful'.format(schedule.description))
+ view.flash.assert_message(f'Schedule "{schedule.description}": Delete successful')
def test_schedule_analysis_in_the_past(appliance, current_server_time, request):
@@ -138,7 +138,7 @@ def test_create_multiple_schedules_in_one_timezone(appliance, request):
time_zone='(GMT-04:00) Atlantic Time (Canada)'
)
view = appliance.browser.create_view(BaseLoggedInPage)
- view.flash.assert_message('Schedule "{}" was saved'.format(schedule.name))
+ view.flash.assert_message(f'Schedule "{schedule.name}" was saved')
schedule_list.append(schedule)
diff --git a/cfme/tests/configure/test_tag.py b/cfme/tests/configure/test_tag.py
index 8bb61aea1e..7d2fadd005 100644
--- a/cfme/tests/configure/test_tag.py
+++ b/cfme/tests/configure/test_tag.py
@@ -173,15 +173,15 @@ def test_updated_tag_name_on_vm(provider, tag, request):
@test_requirements.rest
-class TestTagsViaREST(object):
+class TestTagsViaREST:
COLLECTIONS_BULK_TAGS = ("services", "vms", "users")
def _service_body(self, **kwargs):
uid = fauxfactory.gen_alphanumeric(5)
body = {
- 'name': 'test_rest_service_{}'.format(uid),
- 'description': 'Test REST Service {}'.format(uid),
+ 'name': f'test_rest_service_{uid}',
+ 'description': f'Test REST Service {uid}',
}
body.update(kwargs)
return body
@@ -297,7 +297,7 @@ def test_edit_tag_from_detail(self, appliance, tags):
assert_response(appliance)
for index, name in enumerate(new_names):
record, _ = wait_for(lambda:
- appliance.rest_api.collections.tags.find_by(name="%/{}".format(name)) or False,
+ appliance.rest_api.collections.tags.find_by(name=f"%/{name}") or False,
num_sec=180,
delay=10)
assert record[0].id == edited[index].id
@@ -383,7 +383,7 @@ def test_assign_and_unassign_tag(self, appliance, tags_mod, provider, services_m
collection = getattr(appliance.rest_api.collections, collection_name)
collection.reload()
if not collection.all:
- pytest.skip("No available entity in {} to assign tag".format(collection_name))
+ pytest.skip(f"No available entity in {collection_name} to assign tag")
entity = collection[-1]
tag = tags_mod[0]
try:
diff --git a/cfme/tests/configure/test_tag_category.py b/cfme/tests/configure/test_tag_category.py
index 075a9af72e..7f0b32a68a 100644
--- a/cfme/tests/configure/test_tag_category.py
+++ b/cfme/tests/configure/test_tag_category.py
@@ -39,12 +39,12 @@ def test_category_crud(appliance, soft_assert):
display_name=fauxfactory.gen_alphanumeric(32)
)
view = appliance.browser.create_view(navigator.get_class(cg.parent, 'All').VIEW)
- soft_assert(view.flash.assert_message('Category "{}" was added'.format(cg.display_name)))
+ soft_assert(view.flash.assert_message(f'Category "{cg.display_name}" was added'))
with update(cg):
cg.description = fauxfactory.gen_alphanumeric(32)
- soft_assert(view.flash.assert_message('Category "{}" was saved'.format(cg.name)))
+ soft_assert(view.flash.assert_message(f'Category "{cg.name}" was saved'))
cg.delete()
- soft_assert(view.flash.assert_message('Category "{}": Delete successful'.format(cg.name)))
+ soft_assert(view.flash.assert_message(f'Category "{cg.name}": Delete successful'))
@test_requirements.rest
@@ -76,7 +76,7 @@ def test_query_custom_category_via_api(appliance, custom_category):
@test_requirements.rest
-class TestCategoriesViaREST(object):
+class TestCategoriesViaREST:
@pytest.fixture(scope="function")
def categories(self, request, appliance):
response = _categories(request, appliance, num=5)
diff --git a/cfme/tests/configure/test_timeprofile.py b/cfme/tests/configure/test_timeprofile.py
index 4ab410eff4..b051deafbf 100644
--- a/cfme/tests/configure/test_timeprofile.py
+++ b/cfme/tests/configure/test_timeprofile.py
@@ -141,5 +141,5 @@ def test_time_profile_copy(appliance):
hours=True,
timezone='(GMT-10:00) Hawaii')
copied_time_profile = time_profile.copy(
- description='check_copy{}'.format(time_profile.description))
+ description=f'check_copy{time_profile.description}')
collection.delete(False, time_profile, copied_time_profile)
diff --git a/cfme/tests/configure/test_version.py b/cfme/tests/configure/test_version.py
index a98341826f..225a404274 100644
--- a/cfme/tests/configure/test_version.py
+++ b/cfme/tests/configure/test_version.py
@@ -23,4 +23,4 @@ def test_appliance_version(appliance):
"""
ssh_version = str(appliance.version)
ui_version = about.get_detail(about.VERSION, server=appliance.server)
- assert ui_version.startswith(ssh_version), "UI: {}, SSH: {}".format(ui_version, ssh_version)
+ assert ui_version.startswith(ssh_version), f"UI: {ui_version}, SSH: {ssh_version}"
diff --git a/cfme/tests/configure/test_visual_cloud.py b/cfme/tests/configure/test_visual_cloud.py
index 5a2fe60862..0f4ff9e28e 100644
--- a/cfme/tests/configure/test_visual_cloud.py
+++ b/cfme/tests/configure/test_visual_cloud.py
@@ -92,7 +92,7 @@ def test_cloud_grid_page_per_item(appliance, request, page, value, set_grid):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Gridview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Gridview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
@@ -126,7 +126,7 @@ def test_cloud_tile_page_per_item(appliance, request, page, value, set_tile):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Tileview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Tileview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
@@ -160,7 +160,7 @@ def test_cloud_list_page_per_item(appliance, request, page, value, set_list):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Listview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Listview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
diff --git a/cfme/tests/configure/test_visual_infra.py b/cfme/tests/configure/test_visual_infra.py
index 1258406ba5..cb2e71a3df 100644
--- a/cfme/tests/configure/test_visual_infra.py
+++ b/cfme/tests/configure/test_visual_infra.py
@@ -136,7 +136,7 @@ def test_infra_grid_page_per_item(appliance, request, page, value, set_grid):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Gridview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Gridview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
@@ -170,7 +170,7 @@ def test_infra_tile_page_per_item(appliance, request, page, value, set_tile):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Tileview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Tileview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
@@ -204,7 +204,7 @@ def test_infra_list_page_per_item(appliance, request, page, value, set_list):
assert int(items_per_page) == int(limit)
if int(item_amt) >= int(limit):
- assert int(max_item) == int(limit), 'Listview Failed for page {}!'.format(page)
+ assert int(max_item) == int(limit), f'Listview Failed for page {page}!'
assert int(max_item) <= int(item_amt)
diff --git a/cfme/tests/containers/test_ad_hoc_metrics.py b/cfme/tests/containers/test_ad_hoc_metrics.py
index c6bc4c635d..303810596f 100644
--- a/cfme/tests/containers/test_ad_hoc_metrics.py
+++ b/cfme/tests/containers/test_ad_hoc_metrics.py
@@ -28,13 +28,13 @@ def metrics_up_and_running(provider):
router.metadata.name == 'prometheus'].pop()
metrics_url = router.status.ingress[0].host
except AttributeError:
- pytest.skip('Could not determine metric route for {}'.format(provider.key))
+ pytest.skip(f'Could not determine metric route for {provider.key}')
creds = provider.get_credentials_from_config(provider.key, cred_type='token')
- header = {"Authorization": "Bearer {token}".format(token=creds.token)}
- response = requests.get("https://{url}:443".format(url=metrics_url), headers=header,
+ header = {"Authorization": f"Bearer {creds.token}"}
+ response = requests.get(f"https://{metrics_url}:443", headers=header,
verify=False)
- assert response.ok, "{metrics} failed to start!".format(metrics=router.metadata.name)
- logger.info("{metrics} started successfully".format(metrics=router.metadata.name))
+ assert response.ok, f"{router.metadata.name} failed to start!"
+ logger.info(f"{router.metadata.name} started successfully")
def is_ad_hoc_greyed(provider_object):
@@ -71,4 +71,4 @@ def test_ad_hoc_metrics_select_filter(provider, metrics_up_and_running):
view.wait_for_results_to_load()
assert view.get_total_results_count() != 0, (
- "No results found for {filter}".format(filter=view.selected_filter))
+ f"No results found for {view.selected_filter}")
diff --git a/cfme/tests/containers/test_basic_metrics.py b/cfme/tests/containers/test_basic_metrics.py
index 0977d9c336..1aac36d59e 100644
--- a/cfme/tests/containers/test_basic_metrics.py
+++ b/cfme/tests/containers/test_basic_metrics.py
@@ -45,7 +45,7 @@ def enable_capacity_and_utilization(appliance):
if appliance.wait_for_server_roles(args, delay=10, timeout=300):
yield
else:
- pytest.skip("Failed to set server roles on appliance {}".format(appliance))
+ pytest.skip(f"Failed to set server roles on appliance {appliance}")
logger.info("Disabling metrics collection roles")
appliance.server.settings.disable_server_roles(*args)
@@ -78,10 +78,10 @@ def test_basic_metrics(provider):
router.metadata.name == 'prometheus'].pop()
metrics_url = router.status.ingress[0].host
except AttributeError:
- pytest.skip('Could not determine metric route for {}'.format(provider.key))
+ pytest.skip(f'Could not determine metric route for {provider.key}')
creds = provider.get_credentials_from_config(provider.key, cred_type='token')
- header = {"Authorization": "Bearer {token}".format(token=creds.token)}
- response = requests.get("https://{url}:443".format(url=metrics_url), headers=header,
+ header = {"Authorization": f"Bearer {creds.token}"}
+ response = requests.get(f"https://{metrics_url}:443", headers=header,
verify=False)
assert response.ok, "{metrics} failed to start!".format(metrics=router["metadata"]["name"])
diff --git a/cfme/tests/containers/test_chargeback.py b/cfme/tests/containers/test_chargeback.py
index 40e9052611..eed3598bcb 100644
--- a/cfme/tests/containers/test_chargeback.py
+++ b/cfme/tests/containers/test_chargeback.py
@@ -53,7 +53,7 @@ def dump_args(**kwargs):
'"""
out = ''
for key, val in kwargs.items():
- out += '{}={}, '.format(key, val)
+ out += f'{key}={val}, '
if out:
return out[:-2] + ';'
return kwargs
@@ -100,7 +100,7 @@ def gen_report_base(appliance, obj_type, provider, rate_desc, rate_interval):
}
}
else:
- raise Exception("Unknown object type: {}".format(obj_type))
+ raise Exception(f"Unknown object type: {obj_type}")
data['menu_name'] = title
data['title'] = title
@@ -150,7 +150,7 @@ def assign_custom_compute_rate(obj_type, chargeback_rate, provider):
})
logger.info('ASSIGNING CUSTOM COMPUTE RATE FOR PROJECT CHARGEBACK')
else:
- raise Exception("Unknown object type: {}".format(obj_type))
+ raise Exception(f"Unknown object type: {obj_type}")
compute_assign.assign()
logger.info('Rate - {}: {}'.format(chargeback_rate.description,
@@ -251,7 +251,7 @@ def abstract_test_chargeback_cost(
)
assert found_something_to_test, \
- 'Could not find {} with the assigned rate: {}'.format(obj_type, compute_rate.description)
+ f'Could not find {obj_type} with the assigned rate: {compute_rate.description}'
# Ideally, we would have a single test parametrized by two marks, one in module and the other in
diff --git a/cfme/tests/containers/test_cockpit.py b/cfme/tests/containers/test_cockpit.py
index 160930c0af..43462e9b0c 100644
--- a/cfme/tests/containers/test_cockpit.py
+++ b/cfme/tests/containers/test_cockpit.py
@@ -48,7 +48,7 @@ def test_cockpit_button_access(appliance, provider, cockpit, request):
for node in nodes:
view = (navigate_to(node, 'Details', force=True) if node else
- pytest.skip("Could not determine node of {}".format(provider.name)))
+ pytest.skip(f"Could not determine node of {provider.name}"))
if cockpit:
assert not view.toolbar.web_console.disabled
diff --git a/cfme/tests/containers/test_container_provider_crud.py b/cfme/tests/containers/test_container_provider_crud.py
index 7bfdf827c2..a9a15a303e 100644
--- a/cfme/tests/containers/test_container_provider_crud.py
+++ b/cfme/tests/containers/test_container_provider_crud.py
@@ -49,7 +49,7 @@ def test_container_provider_crud(request, appliance, has_no_providers, provider)
assert view.is_displayed
view.flash.assert_success_message(
- 'Containers Provider "{}" was saved'.format(provider.name))
+ f'Containers Provider "{provider.name}" was saved')
assert provider.name == str(view.entities.get_first_entity().data.get('name', {}))
diff --git a/cfme/tests/containers/test_container_provider_refresh.py b/cfme/tests/containers/test_container_provider_refresh.py
index ac0fcf3cbd..8872f6dac9 100644
--- a/cfme/tests/containers/test_container_provider_refresh.py
+++ b/cfme/tests/containers/test_container_provider_refresh.py
@@ -77,7 +77,7 @@ def test_dup_db_entry_refresh(setup_temp_appliance_provider, temp_appliance_prec
appliance.db.client.session.add(copied_db_entry)
except IntegrityError as ex:
pytest.fail(
- 'Exception while adding DB entry. {}'.format(ex)
+ f'Exception while adding DB entry. {ex}'
)
new_db_entry = image_query.filter(image_table.id == copied_db_entry.id).all()
diff --git a/cfme/tests/containers/test_containers_smartstate_analysis.py b/cfme/tests/containers/test_containers_smartstate_analysis.py
index 4637048a73..50e1933f12 100644
--- a/cfme/tests/containers/test_containers_smartstate_analysis.py
+++ b/cfme/tests/containers/test_containers_smartstate_analysis.py
@@ -115,7 +115,7 @@ def test_containers_smartstate_analysis(provider, test_item, soft_assert,
table_data = {k.lower(): v for k, v in table.read().items()}
if not soft_assert(attr.lower() in table_data,
- '{} table has missing attribute \'{}\''.format(tbl, attr)):
+ f'{tbl} table has missing attribute \'{attr}\''):
continue
provider.refresh_provider_relationships()
wait_for_retval = wait_for(lambda: get_table_attr(random_image_instance, tbl, attr),
@@ -128,7 +128,7 @@ def test_containers_smartstate_analysis(provider, test_item, soft_assert,
continue
value = wait_for_retval.out
soft_assert(verifier(value),
- '{}.{} attribute has unexpected value ({})'.format(tbl, attr, value))
+ f'{tbl}.{attr} attribute has unexpected value ({value})')
@pytest.mark.parametrize(('test_item'), TEST_ITEMS)
@@ -157,7 +157,7 @@ def test_containers_smartstate_analysis_api(provider, test_item, soft_assert,
random_image_instance.scan()
task = provider.appliance.collections.tasks.instantiate(
- name="Container Image Analysis: '{}'".format(random_image_instance.name), tab='AllTasks')
+ name=f"Container Image Analysis: '{random_image_instance.name}'", tab='AllTasks')
task.wait_for_finished()
diff --git a/cfme/tests/containers/test_containers_smartstate_analysis_multiple_images.py b/cfme/tests/containers/test_containers_smartstate_analysis_multiple_images.py
index f3ef3d6721..335d9a2159 100644
--- a/cfme/tests/containers/test_containers_smartstate_analysis_multiple_images.py
+++ b/cfme/tests/containers/test_containers_smartstate_analysis_multiple_images.py
@@ -134,7 +134,7 @@ def test_containers_smartstate_analysis_multiple_images(provider, test_item,
table_data = {k.lower(): v for k, v in table.read().items()}
if not soft_assert(attr.lower() in table_data,
- '{} table has missing attribute \'{}\''.format(tbl, attr)):
+ f'{tbl} table has missing attribute \'{attr}\''):
continue
provider.refresh_provider_relationships()
wait_for_retval = wait_for(lambda: get_table_attr(image_instance, tbl, attr),
@@ -147,4 +147,4 @@ def test_containers_smartstate_analysis_multiple_images(provider, test_item,
continue
value = wait_for_retval.out
soft_assert(verifier(value),
- '{}.{} attribute has unexpected value ({})'.format(tbl, attr, value))
+ f'{tbl}.{attr} attribute has unexpected value ({value})')
diff --git a/cfme/tests/containers/test_logging.py b/cfme/tests/containers/test_logging.py
index 04bc7bf215..83da3b3352 100644
--- a/cfme/tests/containers/test_logging.py
+++ b/cfme/tests/containers/test_logging.py
@@ -52,7 +52,7 @@ def kibana_logging_url(provider):
if len(all_logging_routes) >= NUM_OF_DEFAULT_LOG_ROUTES:
pass
else:
- pytest.skip("Missing logging routes for {}".format(provider.name))
+ pytest.skip(f"Missing logging routes for {provider.name}")
kibana_router = []
for route in all_logging_routes:
@@ -61,7 +61,7 @@ def kibana_logging_url(provider):
if 'kibana' in route.spec.host:
kibana_router.append(route.spec.host)
if not kibana_router:
- pytest.skip("Could not determine Kibana Router for provider {}".format(provider.name))
+ pytest.skip(f"Could not determine Kibana Router for provider {provider.name}")
return kibana_router
diff --git a/cfme/tests/containers/test_node.py b/cfme/tests/containers/test_node.py
index cee782f8e5..fc05b9057a 100644
--- a/cfme/tests/containers/test_node.py
+++ b/cfme/tests/containers/test_node.py
@@ -39,7 +39,7 @@ def test_nodes_navigate(soft_assert, appliance):
try:
view = navigate_to(test_item, dest)
except NodeNotFound:
- soft_assert(False, 'Could not navigate to Node "{}" .'.format(dest))
+ soft_assert(False, f'Could not navigate to Node "{dest}" .')
else:
# Navigation successful, page is displayed
assert view.is_displayed
diff --git a/cfme/tests/containers/test_pause_resume_workers.py b/cfme/tests/containers/test_pause_resume_workers.py
index 432dc5439d..dd97860024 100644
--- a/cfme/tests/containers/test_pause_resume_workers.py
+++ b/cfme/tests/containers/test_pause_resume_workers.py
@@ -23,7 +23,7 @@ def check_ems_state_in_diagnostics(appliance, provider):
workers_view.browser.refresh()
try:
if workers_view.workers_table.rows(
- name='Event Monitor for Provider: {}'.format(provider.name)).next():
+ name=f'Event Monitor for Provider: {provider.name}').next():
return True
except Exception:
return False
diff --git a/cfme/tests/containers/test_projects_dashboard.py b/cfme/tests/containers/test_projects_dashboard.py
index 4d788a07b3..b9eab257fb 100644
--- a/cfme/tests/containers/test_projects_dashboard.py
+++ b/cfme/tests/containers/test_projects_dashboard.py
@@ -153,4 +153,4 @@ def test_project_has_provider(appliance, soft_assert, provider):
curr_project_provider = row.data["provider"]
soft_assert(curr_project_provider,
- "No Provider found for project {name}".format(name=curr_project_name))
+ f"No Provider found for project {curr_project_name}")
diff --git a/cfme/tests/containers/test_provider_configuration_menu.py b/cfme/tests/containers/test_provider_configuration_menu.py
index 42f964cea4..3dafca6f87 100644
--- a/cfme/tests/containers/test_provider_configuration_menu.py
+++ b/cfme/tests/containers/test_provider_configuration_menu.py
@@ -72,7 +72,7 @@ def test_ocp_operator_out_of_the_box(appliance):
if role_name_prefix in row.name.text.lower()])
# validate the role exist out-of-the-box
- assert is_role_found, "No {role} found".format(role=role_name_prefix)
+ assert is_role_found, f"No {role_name_prefix} found"
@pytest.mark.meta(automates=[1516292])
diff --git a/cfme/tests/containers/test_provider_openscap_policy_attached.py b/cfme/tests/containers/test_provider_openscap_policy_attached.py
index b6fac5a268..3a30e39629 100644
--- a/cfme/tests/containers/test_provider_openscap_policy_attached.py
+++ b/cfme/tests/containers/test_provider_openscap_policy_attached.py
@@ -88,7 +88,7 @@ def test_check_compliance_provider_policy(provider, soft_assert, delete_all_cont
wait_for_retval = wait_for(
get_table_attr,
func_args=[openscap_assigned_rand_image, tbl, attr],
- message='Trying to get attribute "{}" of table "{}"'.format(attr, tbl),
+ message=f'Trying to get attribute "{attr}" of table "{tbl}"',
delay=5,
num_sec=120,
silent_failure=True
diff --git a/cfme/tests/containers/test_reports.py b/cfme/tests/containers/test_reports.py
index 502ea688d8..8971a4a920 100644
--- a/cfme/tests/containers/test_reports.py
+++ b/cfme/tests/containers/test_reports.py
@@ -83,7 +83,7 @@ def test_container_reports_base_on_options(soft_assert, appliance):
compare = (base_on.match if hasattr(base_on, 'match') else base_on.__eq__)
option = [opt for opt in view.base_report_on.all_options
if compare(str(opt.text))]
- soft_assert(option, 'Could not find option "{}" for base report on.'.format(base_on))
+ soft_assert(option, f'Could not find option "{base_on}" for base report on.')
def test_report_pods_per_ready_status(appliance, soft_assert, provider):
@@ -323,7 +323,7 @@ def test_report_recently_discovered_pods(appliance, provider, soft_assert):
for pod in pods_per_ready_status.keys():
soft_assert(pod in pods_in_report,
- 'Could not find pod "{}" in report.'.format(pod))
+ f'Could not find pod "{pod}" in report.')
def test_report_number_of_images_per_node(appliance, provider, soft_assert):
@@ -348,7 +348,7 @@ def test_report_number_of_images_per_node(appliance, provider, soft_assert):
# Use 'in' since the image name in the API may include also registry and tag
is_image = [img_nm for img_nm in pod_images if img_nm in expected_image]
soft_assert(is_image,
- 'Expected image for pod "{0}" in node {1} is "{2}". found images: {3}'
+ 'Expected image for pod "{}" in node {} is "{}". found images: {}'
.format(pod_name, node, expected_image, pod_images))
diff --git a/cfme/tests/containers/test_ssa_set_cve_image_inspector_per_provider.py b/cfme/tests/containers/test_ssa_set_cve_image_inspector_per_provider.py
index e4a3efa6ea..7130cc01d3 100644
--- a/cfme/tests/containers/test_ssa_set_cve_image_inspector_per_provider.py
+++ b/cfme/tests/containers/test_ssa_set_cve_image_inspector_per_provider.py
@@ -68,9 +68,9 @@ def set_cve_location(appliance, provider, soft_assert):
provider_edit_view.save.click()
view = appliance.browser.create_view(ContainerProvidersView)
view.flash.assert_success_message(
- 'Containers Provider "{}" was saved'.format(provider.name))
+ f'Containers Provider "{provider.name}" was saved')
except AssertionError:
- soft_assert(False, "{} wasn't added successfully".format(provider.name))
+ soft_assert(False, f"{provider.name} wasn't added successfully")
else:
provider_edit_view.cancel.click()
yield
@@ -94,9 +94,9 @@ def set_image_inspector_registry(appliance, provider, soft_assert):
provider_edit_view.save.click()
view = appliance.browser.create_view(ContainerProvidersView)
view.flash.assert_success_message(
- 'Containers Provider "{}" was saved'.format(provider.name))
+ f'Containers Provider "{provider.name}" was saved')
except AssertionError:
- soft_assert(False, "{} wasn't added successfully".format(provider.name))
+ soft_assert(False, f"{provider.name} wasn't added successfully")
else:
provider_edit_view.cancel.click()
yield
@@ -133,7 +133,7 @@ def verify_ssa_image_attributes(provider, soft_assert, rand_image):
wait_for_retval = wait_for(
get_table_attr,
func_args=[rand_image, tbl, attr],
- message='Trying to get attribute "{}" of table "{}"'.format(attr, tbl),
+ message=f'Trying to get attribute "{attr}" of table "{tbl}"',
delay=5,
num_sec=120,
silent_failure=True
diff --git a/cfme/tests/containers/test_tables_sort.py b/cfme/tests/containers/test_tables_sort.py
index 39eeacceae..b68725c258 100644
--- a/cfme/tests/containers/test_tables_sort.py
+++ b/cfme/tests/containers/test_tables_sort.py
@@ -53,13 +53,13 @@ def test_tables_sort(test_item, soft_assert, appliance):
# in CFME 5.8, the sort on IP Address column for container providers fails to sort?
soft_assert((view.entities.elements.sorted_by == attributize_string(header_text) and
view.entities.elements.sort_order == 'asc'),
- 'Failed checking sorted_by {} and sort_order asc'.format(header_text))
+ f'Failed checking sorted_by {header_text} and sort_order asc')
rows_ascending = [r[col].text for r in view.entities.elements.rows()]
# opposite sort order
view.entities.elements.sort_by(column=header_text, order='desc')
soft_assert((view.entities.elements.sorted_by == attributize_string(header_text) and
view.entities.elements.sort_order == 'desc'),
- 'Failed checking sorted_by {} and sort_order desc'.format(header_text))
+ f'Failed checking sorted_by {header_text} and sort_order desc')
rows_descending = [r[col].text for r in view.entities.elements.rows()]
soft_assert(
diff --git a/cfme/tests/control/test_actions.py b/cfme/tests/control/test_actions.py
index 027aeaeac3..d7c301fca8 100644
--- a/cfme/tests/control/test_actions.py
+++ b/cfme/tests/control/test_actions.py
@@ -100,8 +100,8 @@ def compliance_condition(appliance):
def compliance_policy(vm, policy_name, appliance):
compliance_policy = appliance.collections.policies.create(
policies.VMCompliancePolicy,
- "compliance_{}".format(policy_name),
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name),
+ f"compliance_{policy_name}",
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {vm.name})",
)
return compliance_policy
@@ -126,7 +126,7 @@ def policy_for_testing(
control_policy = appliance.collections.policies.create(
policies.VMControlPolicy,
policy_name,
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name),
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {vm.name})",
)
policy_profile_collection = appliance.collections.policy_profiles
policy_profile = policy_profile_collection.create(
@@ -213,7 +213,7 @@ def _cleanup():
try:
vm.mgmt.wait_for_state(VmState.RUNNING, timeout=600, delay=5)
except TimedOutError:
- pytest.fail("CFME did not power on the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not power on the VM {vm.name}")
@pytest.mark.provider(
@@ -246,7 +246,7 @@ def _cleanup():
try:
vm.mgmt.wait_for_state(VmState.STOPPED, timeout=600, delay=5)
except TimedOutError:
- pytest.fail("CFME did not power off the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not power off the VM {vm.name}")
@pytest.mark.provider(
@@ -280,7 +280,7 @@ def _cleanup():
try:
vm.mgmt.wait_for_state(VmState.SUSPENDED, timeout=600, delay=5)
except TimedOutError:
- pytest.fail("CFME did not suspend the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not suspend the VM {vm.name}")
@pytest.mark.provider(
@@ -315,7 +315,7 @@ def _cleanup():
except TimedOutError:
pass # VM did not start, so that's what we want
else:
- pytest.fail("CFME did not prevent starting of the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not prevent starting of the VM {vm.name}")
@pytest.mark.provider(
@@ -357,7 +357,7 @@ def _fail_func():
except TimedOutError:
pass
else:
- pytest.fail("CFME did not prevent retire of the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not prevent retire of the VM {vm.name}")
@pytest.mark.provider([VMwareProvider], scope="module")
@@ -388,7 +388,7 @@ def _cleanup():
policy_result = LogValidator(
"/var/www/miq/vmdb/log/policy.log",
matched_patterns=[
- '.*Prevent current event from proceeding.*VM Analysis Request.*{}'.format(vm.name)
+ f'.*Prevent current event from proceeding.*VM Analysis Request.*{vm.name}'
]
)
policy_result.start_monitoring()
@@ -400,7 +400,7 @@ def _cleanup():
except TimedOutError:
assert policy_result.validate(wait="120s")
else:
- pytest.fail("CFME did not prevent analysing the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not prevent analysing the VM {vm.name}")
@pytest.mark.provider([VMwareProvider, RHEVMProvider], scope="module")
@@ -431,7 +431,7 @@ def _cleanup():
policy_result = LogValidator(
"/var/www/miq/vmdb/log/policy.log",
matched_patterns=[
- '.*Prevent current event from proceeding.*Host Analysis Request.*{}'.format(host.name)
+ f'.*Prevent current event from proceeding.*Host Analysis Request.*{host.name}'
]
)
policy_result.start_monitoring()
@@ -443,7 +443,7 @@ def _scan():
original = _scan()
view.toolbar.configuration.item_select("Perform SmartState Analysis", handle_alert=True)
- view.flash.assert_success_message('"{}": Analysis successfully initiated'.format(host.name))
+ view.flash.assert_success_message(f'"{host.name}": Analysis successfully initiated')
try:
wait_for(
lambda: _scan() != original,
@@ -455,7 +455,7 @@ def _scan():
except TimedOutError:
assert policy_result.validate(wait="120s")
else:
- pytest.fail("CFME did not prevent analysing the Host {}".format(host.name))
+ pytest.fail(f"CFME did not prevent analysing the Host {host.name}")
@pytest.mark.provider(
@@ -694,7 +694,7 @@ def _cleanup():
try:
do_scan(vm)
except TimedOutError:
- pytest.fail("CFME did not finish analysing the VM {}".format(vm.name))
+ pytest.fail(f"CFME did not finish analysing the VM {vm.name}")
# TODO: Rework to use REST
@@ -869,7 +869,7 @@ def test_action_cancel_clone(
)
policy_for_testing.assign_events("VM Clone Start")
policy_for_testing.assign_actions_to_event("VM Clone Start", ["Cancel vCenter Task"])
- clone_vm_name = "{}-clone".format(vm_big.name)
+ clone_vm_name = f"{vm_big.name}-clone"
@request.addfinalizer
def finalize():
diff --git a/cfme/tests/control/test_alerts.py b/cfme/tests/control/test_alerts.py
index b765bbfcf2..6aa2d991a8 100644
--- a/cfme/tests/control/test_alerts.py
+++ b/cfme/tests/control/test_alerts.py
@@ -55,7 +55,7 @@ def wait_for_alert(smtp, alert, delay=None, additional_checks=None):
def _mail_arrived():
for mail in smtp.get_emails():
- if "Alert Triggered: {}".format(alert.description) in mail["subject"]:
+ if f"Alert Triggered: {alert.description}" in mail["subject"]:
if not additional_checks:
return True
else:
@@ -91,7 +91,7 @@ def _setup_for_alerts(request, alerts_list, event=None, vm_name=None, provider=N
"""
alert_profile = appliance.collections.alert_profiles.create(
alert_profiles.VMInstanceAlertProfile,
- "Alert profile for {}".format(vm_name),
+ f"Alert profile for {vm_name}",
alerts=alerts_list
)
request.addfinalizer(alert_profile.delete)
@@ -107,19 +107,19 @@ def _setup_for_alerts(request, alerts_list, event=None, vm_name=None, provider=N
view.flash.assert_message('Edit Alert Profile assignments cancelled by user')
if event is not None:
action = appliance.collections.actions.create(
- "Evaluate Alerts for {}".format(vm_name),
+ f"Evaluate Alerts for {vm_name}",
"Evaluate Alerts",
action_values={"alerts_to_evaluate": [str(alert) for alert in alerts_list]}
)
request.addfinalizer(action.delete)
policy = appliance.collections.policies.create(
policies.VMControlPolicy,
- "Evaluate Alerts policy for {}".format(vm_name),
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm_name)
+ f"Evaluate Alerts policy for {vm_name}",
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {vm_name})"
)
request.addfinalizer(policy.delete)
policy_profile = appliance.collections.policy_profiles.create(
- "Policy profile for {}".format(vm_name), policies=[policy]
+ f"Policy profile for {vm_name}", policies=[policy]
)
request.addfinalizer(policy_profile.delete)
policy.assign_actions_to_event(event, [action])
@@ -299,7 +299,7 @@ def test_alert_timeline_cpu(request, appliance, create_vm,
if alert.description in event.message:
break
else:
- pytest.fail("The event has not been found on the timeline. Event list: {}".format(events))
+ pytest.fail(f"The event has not been found on the timeline. Event list: {events}")
@pytest.mark.parametrize('create_vm', ['full_template'], indirect=True)
@@ -337,7 +337,7 @@ def test_alert_snmp(request, appliance, provider, setup_snmp, setup_candu, creat
"version": "v2",
"id": "info",
"traps": [
- ("1.2.3", "OctetString", "{}".format(match_string))]},
+ ("1.2.3", "OctetString", f"{match_string}")]},
)
request.addfinalizer(alert.delete)
@@ -345,7 +345,7 @@ def test_alert_snmp(request, appliance, provider, setup_snmp, setup_candu, creat
def _snmp_arrived():
result = appliance.ssh_client.run_command(
- "journalctl --no-pager /usr/sbin/snmptrapd | grep {}".format(match_string))
+ f"journalctl --no-pager /usr/sbin/snmptrapd | grep {match_string}")
if result.failed:
return False
elif result.output:
diff --git a/cfme/tests/control/test_basic.py b/cfme/tests/control/test_basic.py
index e0d8a936ec..9572cbbcc6 100644
--- a/cfme/tests/control/test_basic.py
+++ b/cfme/tests/control/test_basic.py
@@ -562,7 +562,7 @@ def _cleanup():
prefix = policy.TREE_NODE if not policy.TREE_NODE == "Vm" else policy.TREE_NODE.upper()
if policy.TREE_NODE == "Physical Infrastructure" and BZ(1700070).blocks:
prefix = policy.PRETTY
- event = "{} Compliance Check".format(prefix)
+ event = f"{prefix} Compliance Check"
request.addfinalizer(lambda: policy.assign_actions_to_event(
event, {"Mark as Non-Compliant": False}))
policy.assign_actions_to_event(event, action)
diff --git a/cfme/tests/control/test_bugs.py b/cfme/tests/control/test_bugs.py
index 61e1eb5247..05a0a2c06e 100644
--- a/cfme/tests/control/test_bugs.py
+++ b/cfme/tests/control/test_bugs.py
@@ -174,7 +174,7 @@ def setup_disk_usage_alert(appliance):
)
alert_profile = appliance.collections.alert_profiles.create(
ServerAlertProfile,
- "Alert profile for {}".format(alert.description),
+ f"Alert profile for {alert.description}",
alerts=[alert]
)
alert_profile.assign_to("Selected Servers", selections=["Servers", "EVM"])
@@ -344,7 +344,7 @@ def test_check_compliance_history(request, virtualcenter_provider, vmware_vm, ap
VMCompliancePolicy,
fauxfactory.gen_alpha(36, start="Check compliance history policy "),
active=True,
- scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vmware_vm.name)
+ scope=f"fill_field(VM and Instance : Name, INCLUDES, {vmware_vm.name})"
)
request.addfinalizer(lambda: policy.delete() if policy.exists else None)
policy_profile = appliance.collections.policy_profiles.create(
@@ -522,7 +522,7 @@ def _check_query():
_check_query,
delay=5,
num_sec=600,
- message="Waiting for alert {} to appear in DB".format(alert.description)
+ message=f"Waiting for alert {alert.description} to appear in DB"
)
@@ -554,7 +554,7 @@ def test_accordion_after_condition_creation(appliance, condition_class):
)
view = condition.create_view(conditions.ConditionDetailsView, wait="10s")
assert view.conditions.tree.currently_selected == [
- "All Conditions", "{} Conditions".format(condition_class.TREE_NODE), condition.description
+ "All Conditions", f"{condition_class.TREE_NODE} Conditions", condition.description
]
@@ -608,7 +608,7 @@ def test_policy_condition_multiple_ors(
vm_name = virtualcenter_provider.data["cap_and_util"]["capandu_vm"]
# check that it exists on provider
if not virtualcenter_provider.mgmt.does_vm_exist(vm_name):
- pytest.skip("No capandu_vm available on virtualcenter_provider of name {}".format(vm_name))
+ pytest.skip(f"No capandu_vm available on virtualcenter_provider of name {vm_name}")
vms = [all_vms.pop(all_vm_names.index(vm_name))]
@@ -622,7 +622,7 @@ def test_policy_condition_multiple_ors(
# Now perform the policy simulation
view = navigate_to(filtered_collection, "PolicySimulation")
# Select the correct policy profile
- view.fill({"form": {"policy_profile": "{}".format(vm_compliance_policy_profile.description)}})
+ view.fill({"form": {"policy_profile": f"{vm_compliance_policy_profile.description}"}})
# Now check each quadicon and ensure that only cu-24x7 is compliant
for entity in view.form.entities.get_all():
diff --git a/cfme/tests/control/test_default_alerts.py b/cfme/tests/control/test_default_alerts.py
index c35b00952a..ac013eb5c3 100644
--- a/cfme/tests/control/test_default_alerts.py
+++ b/cfme/tests/control/test_default_alerts.py
@@ -15,7 +15,7 @@ def default_alerts(appliance):
all_alerts = yaml.safe_load(f)
alerts = (all_alerts.get('v5.10'))
else:
- pytest.skip('Could not find {}, skipping test.'.format(file_name))
+ pytest.skip(f'Could not find {file_name}, skipping test.')
# instantiate a list of alerts based on default_alerts.yaml
alert_collection = appliance.collections.alerts
diff --git a/cfme/tests/control/test_rest_control.py b/cfme/tests/control/test_rest_control.py
index 9c3173b293..d0ffb59a11 100644
--- a/cfme/tests/control/test_rest_control.py
+++ b/cfme/tests/control/test_rest_control.py
@@ -17,7 +17,7 @@
]
-class TestConditionsRESTAPI(object):
+class TestConditionsRESTAPI:
@pytest.fixture(scope='function')
def conditions(self, request, appliance):
num_conditions = 2
@@ -102,7 +102,7 @@ def test_edit_conditions(self, conditions, appliance, from_detail):
"""
num_conditions = len(conditions)
uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_conditions)]
- new = [{'description': 'Edited Test Condition {}'.format(u)} for u in uniq]
+ new = [{'description': f'Edited Test Condition {u}'} for u in uniq]
if from_detail:
edited = []
for index in range(num_conditions):
@@ -126,7 +126,7 @@ def test_edit_conditions(self, conditions, appliance, from_detail):
assert condition.description == edited[index].description == record[0].description
-class TestPoliciesRESTAPI(object):
+class TestPoliciesRESTAPI:
@pytest.fixture(scope='function')
def policies(self, request, appliance):
num_policies = 2
@@ -229,7 +229,7 @@ def test_edit_policies(self, policies, appliance, from_detail):
"""
num_policies = len(policies)
uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_policies)]
- new = [{'description': 'Edited Test Policy {}'.format(u)} for u in uniq]
+ new = [{'description': f'Edited Test Policy {u}'} for u in uniq]
if from_detail:
edited = []
for index in range(num_policies):
@@ -270,8 +270,8 @@ def test_create_invalid_policies(self, appliance):
"""
policy_name = fauxfactory.gen_alphanumeric(5)
data = {
- "name": "test_policy_{}".format(policy_name),
- "description": "Test Policy {}".format(policy_name),
+ "name": f"test_policy_{policy_name}",
+ "description": f"Test Policy {policy_name}",
"mode": "bar",
"towhat": "baz",
"conditions_ids": [2000, 3000],
diff --git a/cfme/tests/control/test_smoke_control.py b/cfme/tests/control/test_smoke_control.py
index 31e628d0ef..583b9f9657 100644
--- a/cfme/tests/control/test_smoke_control.py
+++ b/cfme/tests/control/test_smoke_control.py
@@ -66,4 +66,4 @@ def test_control_explorer_tree(control_explorer_view, destination, appliance):
navigate_to(appliance.server, 'ControlExplorer', wait_for_view=30)
accordion_name = destination.lower().replace(" ", "_")
accordion = getattr(control_explorer_view, accordion_name)
- accordion.tree.click_path("All {}".format(destination))
+ accordion.tree.click_path(f"All {destination}")
diff --git a/cfme/tests/infrastructure/test_advanced_search_host.py b/cfme/tests/infrastructure/test_advanced_search_host.py
index 99f7da5404..5e55aee136 100644
--- a/cfme/tests/infrastructure/test_advanced_search_host.py
+++ b/cfme/tests/infrastructure/test_advanced_search_host.py
@@ -37,7 +37,7 @@ def hosts_with_vm_count(hosts, host_collection):
def get_expression(user_input=False, op=">"):
- expression = "fill_count(Host / Node.VMs, {}".format(op)
+ expression = f"fill_count(Host / Node.VMs, {op}"
if user_input:
return expression + ")"
else:
diff --git a/cfme/tests/infrastructure/test_advanced_search_providers.py b/cfme/tests/infrastructure/test_advanced_search_providers.py
index 42d4481bfa..b6709981fe 100644
--- a/cfme/tests/infrastructure/test_advanced_search_providers.py
+++ b/cfme/tests/infrastructure/test_advanced_search_providers.py
@@ -22,13 +22,13 @@ def rails_delete_filter(request):
yield
filter_name = getattr(request.function, "filter_name", None)
- logger.debug('rails_delete_filter: calling rails to delete filter: {}'.format(filter_name))
+ logger.debug(f'rails_delete_filter: calling rails to delete filter: {filter_name}')
if filter_name:
try:
store.current_appliance.ssh_client.run_rails_command(
'"MiqSearch.where(:description => {}).first.delete"'.format(repr(filter_name)))
except Exception as ex:
- logger.warning('rails_delete_filter: exception during delete. {}'.format(ex))
+ logger.warning(f'rails_delete_filter: exception during delete. {ex}')
pass
else:
logger.warning('rails_delete_filter: failed to get filter_name')
@@ -108,7 +108,7 @@ def test_provider_filter_save_cancel(rails_delete_filter, advanced_search_view):
"""
# bind filter_name to the function for fixture cleanup
test_provider_filter_save_cancel.filter_name = fauxfactory.gen_alphanumeric()
- logger.debug('Set filter_name to: {}'.format(test_provider_filter_save_cancel.filter_name))
+ logger.debug(f'Set filter_name to: {test_provider_filter_save_cancel.filter_name}')
# Try save filter
assert advanced_search_view.entities.search.save_filter(
@@ -133,7 +133,7 @@ def test_provider_filter_save_and_load(rails_delete_filter, advanced_search_view
"""
# bind filter_name to the function for fixture cleanup
test_provider_filter_save_and_load.filter_name = fauxfactory.gen_alphanumeric()
- logger.debug('Set filter_name to: {}'.format(test_provider_filter_save_and_load.filter_name))
+ logger.debug(f'Set filter_name to: {test_provider_filter_save_and_load.filter_name}')
# Save filter
assert advanced_search_view.entities.search.save_filter(
@@ -254,7 +254,7 @@ def test_can_delete_provider_filter(advanced_search_view):
initialEstimate: 1/10h
"""
filter_name = fauxfactory.gen_alphanumeric()
- logger.debug('Set filter_name to: {}'.format(filter_name))
+ logger.debug(f'Set filter_name to: {filter_name}')
assert advanced_search_view.entities.search.save_filter(
"fill_count(Infrastructure Provider.VMs, >, 0)", filter_name)
advanced_search_view.flash.assert_no_error()
diff --git a/cfme/tests/infrastructure/test_advanced_search_vms.py b/cfme/tests/infrastructure/test_advanced_search_vms.py
index 46d0f888e0..383d66b571 100644
--- a/cfme/tests/infrastructure/test_advanced_search_vms.py
+++ b/cfme/tests/infrastructure/test_advanced_search_vms.py
@@ -46,7 +46,7 @@ def subset_of_vms(vms):
@pytest.fixture
def expression_for_vms_subset(subset_of_vms):
return ";select_first_expression;click_or;".join(
- ["fill_field(Virtual Machine : Name, =, {})".format(vm) for vm in subset_of_vms]
+ [f"fill_field(Virtual Machine : Name, =, {vm})" for vm in subset_of_vms]
)
@@ -84,7 +84,7 @@ def test_vm_filter_without_user_input(appliance, vm_view, vms, subset_of_vms,
vm_view.flash.assert_no_error()
vms_present = vm_view.entities.entity_names
for vm in subset_of_vms:
- assert vm in vms_present, "Could not find VM {} after filtering!".format(vm)
+ assert vm in vms_present, f"Could not find VM {vm} after filtering!"
@pytest.mark.meta(blockers=[BZ(1715550, forced_streams=["5.10", "5.11"])])
@@ -108,7 +108,7 @@ def test_vm_filter_with_user_input(
# Check the number of VMs after filtering and that it's less than without filtering
vms_after = len(vm_view.entities.get_all())
assert vms_after < vms_before
- assert vm in vm_view.entities.entity_names, "Could not find VM {} after filtering!".format(vm)
+ assert vm in vm_view.entities.entity_names, f"Could not find VM {vm} after filtering!"
def test_vm_filter_with_user_input_and_cancellation(vm_view, vms, subset_of_vms,
@@ -409,6 +409,6 @@ def cleanup():
vms_after = len(vm_view.entities.get_all())
assert 2 <= vms_after < vms_before
- msg = "Could not find VMs {}, {} after filtering!".format(vm1_name, vm2_name)
+ msg = f"Could not find VMs {vm1_name}, {vm2_name} after filtering!"
vms = vm_view.entities.entity_names
assert vm1_name in vms and vm2_name in vms, msg
diff --git a/cfme/tests/infrastructure/test_child_tenant.py b/cfme/tests/infrastructure/test_child_tenant.py
index e18c999870..975f45a872 100644
--- a/cfme/tests/infrastructure/test_child_tenant.py
+++ b/cfme/tests/infrastructure/test_child_tenant.py
@@ -42,12 +42,12 @@ def prov_data(vm_name, provisioning):
@pytest.fixture
def set_child_tenant_quota(request, appliance, new_child):
field, value = request.param
- new_child.set_quota(**{'{}_cb'.format(field): True, field: value})
+ new_child.set_quota(**{f'{field}_cb': True, field: value})
yield
# will refresh page as navigation to configuration is blocked if alerts are on the page
appliance.server.login_admin()
appliance.server.browser.refresh()
- new_child.set_quota(**{'{}_cb'.format(field): False})
+ new_child.set_quota(**{f'{field}_cb': False})
@pytest.fixture(scope='module')
@@ -79,7 +79,7 @@ def new_group(appliance, new_child, new_tenant):
collection = appliance.collections.groups
group = collection.create(description=fauxfactory.gen_alphanumeric(start="group_"),
role='EvmRole-administrator',
- tenant='My Company/{}/{}'.format(new_tenant.name, new_child.name))
+ tenant=f'My Company/{new_tenant.name}/{new_child.name}')
yield group
if group.exists:
group.delete()
diff --git a/cfme/tests/infrastructure/test_config_management_rest.py b/cfme/tests/infrastructure/test_config_management_rest.py
index 5cca6ea3b5..cf4d06e18c 100644
--- a/cfme/tests/infrastructure/test_config_management_rest.py
+++ b/cfme/tests/infrastructure/test_config_management_rest.py
@@ -21,15 +21,15 @@ def authentications(appliance, provider):
"""Creates and returns authentication resources under /api/authentications."""
auth_num = 2
collection = appliance.rest_api.collections.authentications
- prov = appliance.rest_api.collections.providers.get(name='{} %'.format(provider.name))
+ prov = appliance.rest_api.collections.providers.get(name=f'{provider.name} %')
data = []
cred_names = []
for __ in range(auth_num):
uniq = fauxfactory.gen_alphanumeric(5)
- cred_name = 'test_credentials_{}'.format(uniq)
+ cred_name = f'test_credentials_{uniq}'
cred_names.append(cred_name)
data.append({
- 'description': 'Test Description {}'.format(uniq),
+ 'description': f'Test Description {uniq}',
'name': cred_name,
'related': {},
'user': 1,
@@ -69,7 +69,7 @@ def _check_edited_authentications(appliance, authentications, new_names):
assert auth.name == record[0].name
-class TestAuthenticationsRESTAPI(object):
+class TestAuthenticationsRESTAPI:
def test_query_authentications_attributes(self, authentications, soft_assert):
"""Tests access to authentication attributes.
diff --git a/cfme/tests/infrastructure/test_datastore_analysis.py b/cfme/tests/infrastructure/test_datastore_analysis.py
index 313e80b49a..0667c23b73 100644
--- a/cfme/tests/infrastructure/test_datastore_analysis.py
+++ b/cfme/tests/infrastructure/test_datastore_analysis.py
@@ -106,7 +106,7 @@ def test_run_datastore_analysis(setup_provider, datastore, soft_assert, datastor
datastore.run_smartstate_analysis(wait_for_task_result=True)
except (MenuItemNotFound, DropdownDisabled):
# TODO need to update to cover all detastores
- pytest.skip('Smart State analysis is disabled for {} datastore'.format(datastore.name))
+ pytest.skip(f'Smart State analysis is disabled for {datastore.name} datastore')
details_view = navigate_to(datastore, 'DetailsFromProvider')
# c_datastore = details_view.entities.properties.get_text_of("Datastore Type")
@@ -125,6 +125,6 @@ def test_run_datastore_analysis(setup_provider, datastore, soft_assert, datastor
for row_name in CONTENT_ROWS_TO_CHECK:
value = details_view.entities.content.get_text_of(row_name)
soft_assert(value != '0',
- 'Expected value for {} to be non-empty'.format(row_name))
+ f'Expected value for {row_name} to be non-empty')
else:
assert details_view.entities.content.get_text_of(CONTENT_ROWS_TO_CHECK[-1]) != '0'
diff --git a/cfme/tests/infrastructure/test_host.py b/cfme/tests/infrastructure/test_host.py
index 6e78b0a8a2..68477b15ca 100644
--- a/cfme/tests/infrastructure/test_host.py
+++ b/cfme/tests/infrastructure/test_host.py
@@ -60,7 +60,7 @@ def host_ips(provider):
if ipaddr:
ipaddresses.append(ipaddr)
if not ipaddresses:
- pytest.skip('No hosts IP addresses found for provider "{}"'.format(provider.name))
+ pytest.skip(f'No hosts IP addresses found for provider "{provider.name}"')
ipaddresses.sort()
return tuple(ipaddresses)
diff --git a/cfme/tests/infrastructure/test_host_drift_analysis.py b/cfme/tests/infrastructure/test_host_drift_analysis.py
index 6135266c67..d44aa52d7b 100644
--- a/cfme/tests/infrastructure/test_host_drift_analysis.py
+++ b/cfme/tests/infrastructure/test_host_drift_analysis.py
@@ -115,7 +115,7 @@ def test_host_drift_analysis(appliance, request, a_host, soft_assert, set_host_c
# check drift difference
soft_assert(
a_host.equal_drift_results(
- '{} (1)'.format(added_tag.category.display_name),
+ f'{added_tag.category.display_name} (1)',
'My Company Tags',
0,
1
@@ -130,12 +130,12 @@ def test_host_drift_analysis(appliance, request, a_host, soft_assert, set_host_c
drift_analysis_view.toolbar.same_values_attributes.click()
soft_assert(
not drift_analysis_view.drift_analysis.check_section_attribute_availability(
- '{}'.format(added_tag.category.display_name)),
- "{} row should be hidden, but not".format(added_tag.display_name))
+ f'{added_tag.category.display_name}'),
+ f"{added_tag.display_name} row should be hidden, but not")
# Accounting tag should be displayed now
drift_analysis_view.toolbar.different_values_attributes.click()
soft_assert(
drift_analysis_view.drift_analysis.check_section_attribute_availability(
- '{} (1)'.format(added_tag.category.display_name)),
- "{} row should be visible, but not".format(added_tag.display_name))
+ f'{added_tag.category.display_name} (1)'),
+ f"{added_tag.display_name} row should be visible, but not")
diff --git a/cfme/tests/infrastructure/test_host_provisioning.py b/cfme/tests/infrastructure/test_host_provisioning.py
index c947e84c90..c8d2ed70bf 100644
--- a/cfme/tests/infrastructure/test_host_provisioning.py
+++ b/cfme/tests/infrastructure/test_host_provisioning.py
@@ -183,7 +183,7 @@ def cleanup_host():
view = navigate_to(test_host, 'Provision')
- note = ('Provisioning host {} on provider {}'.format(prov_host_name, provider.key))
+ note = (f'Provisioning host {prov_host_name} on provider {provider.key}')
provisioning_data = {
'request': {
'email': 'template_provisioner@example.com',
@@ -196,7 +196,7 @@ def cleanup_host():
},
'environment': {'provider_name': provider.name,
'datastore_name': {'name': datastores},
- 'cluster': "{} / {}".format(datacenter, cluster),
+ 'cluster': f"{datacenter} / {cluster}",
'host_name': prov_host_name
},
'customize': {'root_password': root_password,
@@ -213,7 +213,7 @@ def cleanup_host():
"Host Request was Submitted, you will be notified when your Hosts are ready"
)
- request_description = 'PXE install on [{}] from image [{}]'.format(prov_host_name, pxe_image)
+ request_description = f'PXE install on [{prov_host_name}] from image [{pxe_image}]'
host_request = appliance.collections.requests.instantiate(request_description)
host_request.wait_for_request(method='ui')
assert host_request.row.last_message.text == 'Host Provisioned Successfully'
diff --git a/cfme/tests/infrastructure/test_infra_tag_filters_combination.py b/cfme/tests/infrastructure/test_infra_tag_filters_combination.py
index 1e3b003c86..3576ecb4e8 100644
--- a/cfme/tests/infrastructure/test_infra_tag_filters_combination.py
+++ b/cfme/tests/infrastructure/test_infra_tag_filters_combination.py
@@ -38,7 +38,7 @@ def testing_vis_object(request, provider, appliance):
view = navigate_to(provider, destination) if destination else navigate_to(collection, 'All')
names = view.entities.entity_names
if not names:
- pytest.skip("No content found for test of {}".format(collection))
+ pytest.skip(f"No content found for test of {collection}")
return collection.instantiate(name=names[0], provider=provider)
diff --git a/cfme/tests/infrastructure/test_kubevirt.py b/cfme/tests/infrastructure/test_kubevirt.py
index be751f2420..a72d2f2b45 100644
--- a/cfme/tests/infrastructure/test_kubevirt.py
+++ b/cfme/tests/infrastructure/test_kubevirt.py
@@ -23,7 +23,7 @@ def temp_vm(appliance, provider, provisioning):
vm = appliance.collections.infra_vms.instantiate(name=vm_name,
provider=provider,
template_name=template_name)
- note = ('template {} to vm {} on provider {}'.format(template_name, vm_name, provider.key))
+ note = (f'template {template_name} to vm {vm_name} on provider {provider.key}')
prov_data.update({
'request': {
'email': 'template_provisioner@example.com',
@@ -70,11 +70,11 @@ def test_k6t_vm_crud(request, appliance, provider, provisioning, custom_prov_dat
template = provisioning['template']
do_vm_provisioning(appliance, template, provider, vm_name, prov_data, request, wait=False)
logger.info('Waiting for cfme provision request for vm %s', vm_name)
- request_description = 'Provision from [{}] to [{}]'.format(template, vm_name)
+ request_description = f'Provision from [{template}] to [{vm_name}]'
provision_request = appliance.collections.requests.instantiate(request_description)
provision_request.wait_for_request(method='ui', num_sec=300)
assert provision_request.is_succeeded(method='ui'), \
- ("Provisioning failed with the message {}".format(provision_request.row.last_message.text))
+ (f"Provisioning failed with the message {provision_request.row.last_message.text}")
@pytest.mark.parametrize('from_details', ['True', 'False'], ids=['from_details', 'from_all_view'])
diff --git a/cfme/tests/infrastructure/test_project_quota.py b/cfme/tests/infrastructure/test_project_quota.py
index b52d738c39..a15991e3b9 100644
--- a/cfme/tests/infrastructure/test_project_quota.py
+++ b/cfme/tests/infrastructure/test_project_quota.py
@@ -42,12 +42,12 @@ def prov_data(vm_name, provisioning):
@pytest.fixture
def set_project_quota(request, appliance, new_project):
field, value = request.param
- new_project.set_quota(**{'{}_cb'.format(field): True, field: value})
+ new_project.set_quota(**{f'{field}_cb': True, field: value})
yield
# will refresh page as navigation to configuration is blocked if alerts are on the page
appliance.server.login_admin()
appliance.server.browser.refresh()
- new_project.set_quota(**{'{}_cb'.format(field): False})
+ new_project.set_quota(**{f'{field}_cb': False})
@pytest.fixture(scope='module')
@@ -75,7 +75,7 @@ def new_group(appliance, new_project, new_role):
collection = appliance.collections.groups
group = collection.create(description=fauxfactory.gen_alphanumeric(start="group_"),
role=new_role.name,
- tenant='My Company/{}'.format(new_project.name))
+ tenant=f'My Company/{new_project.name}')
yield group
group.delete()
diff --git a/cfme/tests/infrastructure/test_providers.py b/cfme/tests/infrastructure/test_providers.py
index 99fab6a6cf..db50c8b2fc 100644
--- a/cfme/tests/infrastructure/test_providers.py
+++ b/cfme/tests/infrastructure/test_providers.py
@@ -330,7 +330,7 @@ def test_provider_rhv_create_delete_tls(request, provider, verify_tls):
endpoints['default'].ca_certs = None
prov.endpoints = endpoints
- prov.name = "{}-no-tls".format(provider.name)
+ prov.name = f"{provider.name}-no-tls"
prov.create()
prov.validate_stats(ui=True)
diff --git a/cfme/tests/infrastructure/test_provisioning_dialog.py b/cfme/tests/infrastructure/test_provisioning_dialog.py
index 98e6d08fa1..db220567f5 100644
--- a/cfme/tests/infrastructure/test_provisioning_dialog.py
+++ b/cfme/tests/infrastructure/test_provisioning_dialog.py
@@ -86,7 +86,7 @@ def _provisioner(template, provisioning_data, delayed=None):
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(vm_name, provider)
.cleanup_on_provider())
- request_description = 'Provision from [{}] to [{}]'.format(template, vm_name)
+ request_description = f'Provision from [{template}] to [{vm_name}]'
provision_request = appliance.collections.requests.instantiate(
description=request_description)
if delayed is not None:
@@ -108,7 +108,7 @@ def _provisioner(template, provisioning_data, delayed=None):
# nav to requests page happens on successful provision
logger.info('Waiting for cfme provision request for vm %s', vm_name)
provision_request.wait_for_request()
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
return vm
@@ -299,7 +299,7 @@ def test_tag(provisioner, prov_data, provider, vm_name):
assert any(
tag.category.display_name == "Service Level" and tag.display_name == "Gold"
for tag in tags
- ), "Service Level: Gold not in tags ({})".format(tags)
+ ), f"Service Level: Gold not in tags ({tags})"
@pytest.mark.rhv3
@@ -467,7 +467,7 @@ def test_vmware_default_placement(provisioner, prov_data, provider, setup_provid
wait_for(
lambda: vm.exists_on_provider,
num_sec=240, delay=5,
- message="VM {} exists on provider.".format(vm_name)
+ message=f"VM {vm_name} exists on provider."
)
assert 'Datacenter' == provider.mgmt.get_vm(vm_name).raw.parent.parent.name, (
'The new vm is not placed in the Datacenter root directory!')
diff --git a/cfme/tests/infrastructure/test_provisioning_rest.py b/cfme/tests/infrastructure/test_provisioning_rest.py
index 3acf868c12..4ac3556296 100644
--- a/cfme/tests/infrastructure/test_provisioning_rest.py
+++ b/cfme/tests/infrastructure/test_provisioning_rest.py
@@ -30,7 +30,7 @@ def get_provision_data(rest_api, provider, template_name, auto_approve=True):
guid = template.guid
break
else:
- raise Exception('No such template {} on provider!'.format(template_name))
+ raise Exception(f'No such template {template_name} on provider!')
result = {
"version": "1.1",
@@ -114,7 +114,7 @@ def test_provision(request, appliance, provider, provision_data):
provision_request.rest.message)
assert provision_request.is_succeeded(), msg
found_vms = appliance.rest_api.collections.vms.find_by(name=vm_name)
- assert found_vms, 'VM `{}` not found'.format(vm_name)
+ assert found_vms, f'VM `{vm_name}` not found'
@pytest.mark.rhv2
@@ -159,7 +159,7 @@ def test_provision_vlan(request, appliance, provision_data, vnic_profile, provid
provision_request.rest.message)
assert provision_request.is_succeeded(), msg
found_vms = appliance.rest_api.collections.vms.find_by(name=vm_name)
- assert found_vms, 'VM `{}` not found'.format(vm_name)
+ assert found_vms, f'VM `{vm_name}` not found'
# Check the VM vNIC
vm = appliance.collections.infra_vms.instantiate(vm_name, provider)
nics = vm.mgmt.get_nics()
@@ -220,7 +220,7 @@ def check_one_completed_mail_received():
request = appliance.collections.requests.instantiate(description=vm_name, partial_check=True)
request.wait_for_request()
- assert provider.mgmt.does_vm_exist(vm_name), "The VM {} does not exist!".format(vm_name)
+ assert provider.mgmt.does_vm_exist(vm_name), f"The VM {vm_name} does not exist!"
wait_for(check_one_approval_mail_received, num_sec=90, delay=5)
wait_for(check_one_completed_mail_received, num_sec=90, delay=5)
diff --git a/cfme/tests/infrastructure/test_pxe.py b/cfme/tests/infrastructure/test_pxe.py
index 2cf5678d70..e7d94b3b81 100644
--- a/cfme/tests/infrastructure/test_pxe.py
+++ b/cfme/tests/infrastructure/test_pxe.py
@@ -31,5 +31,5 @@ def test_pxe_server_crud(pxe_name, pxe_server_crud):
"""
pxe_server_crud.create(refresh_timeout=300)
with update(pxe_server_crud):
- pxe_server_crud.name = "{}_update".format(pxe_server_crud.name)
+ pxe_server_crud.name = f"{pxe_server_crud.name}_update"
pxe_server_crud.delete(cancel=False)
diff --git a/cfme/tests/infrastructure/test_quota.py b/cfme/tests/infrastructure/test_quota.py
index eae0095c77..58154a7fed 100644
--- a/cfme/tests/infrastructure/test_quota.py
+++ b/cfme/tests/infrastructure/test_quota.py
@@ -132,13 +132,13 @@ def set_parent_tenant_quota(request, appliance, new_tenant):
"""
for i in range(0, NUM_TENANTS):
field, value = request.param
- new_tenant[i].set_quota(**{'{}_cb'.format(field): True, field: value})
+ new_tenant[i].set_quota(**{f'{field}_cb': True, field: value})
yield
# will refresh page as navigation to configuration is blocked if alerts are on the page
appliance.server.login_admin()
appliance.server.browser.refresh()
for i in range(0, NUM_TENANTS):
- new_tenant[i].set_quota(**{'{}_cb'.format(field): False})
+ new_tenant[i].set_quota(**{f'{field}_cb': False})
@pytest.fixture(scope='module')
diff --git a/cfme/tests/infrastructure/test_rest_automation_request.py b/cfme/tests/infrastructure/test_rest_automation_request.py
index ae3a9d5712..a257d54786 100644
--- a/cfme/tests/infrastructure/test_rest_automation_request.py
+++ b/cfme/tests/infrastructure/test_rest_automation_request.py
@@ -126,7 +126,7 @@ def edit_requests(collection, rest_api, requests_pending, from_detail):
else:
identifiers = []
for i, resource in enumerate(requests_pending):
- loc = ({'id': resource.id}, {'href': '{}/{}'.format(collection._href, resource.id)})
+ loc = ({'id': resource.id}, {'href': f'{collection._href}/{resource.id}'})
identifiers.append(loc[i % 2])
collection.action.edit(*identifiers, **body)
assert_response(rest_api)
@@ -136,7 +136,7 @@ def edit_requests(collection, rest_api, requests_pending, from_detail):
assert request.options['arbitrary_key_allowed'] == 'test_rest'
-class TestAutomationRequestsRESTAPI(object):
+class TestAutomationRequestsRESTAPI:
"""Tests using /api/automation_requests."""
@pytest.fixture(scope='function')
@@ -276,7 +276,7 @@ def test_multiple_automation_requests(self, collection, appliance, vm):
deny_requests(collection, appliance.rest_api, response, from_detail=False)
-class TestAutomationRequestsCommonRESTAPI(object):
+class TestAutomationRequestsCommonRESTAPI:
"""Tests using /api/requests (common collection for all requests types)."""
@pytest.fixture(scope='function')
diff --git a/cfme/tests/infrastructure/test_rest_templates.py b/cfme/tests/infrastructure/test_rest_templates.py
index de44b5e84f..cbd38a594f 100644
--- a/cfme/tests/infrastructure/test_rest_templates.py
+++ b/cfme/tests/infrastructure/test_rest_templates.py
@@ -47,7 +47,7 @@ def _finished():
)
)
except Exception as e:
- logger.error("Failed to delete template. {}".format(e))
+ logger.error(f"Failed to delete template. {e}")
return template
@@ -78,7 +78,7 @@ def test_query_template_attributes(request, appliance, provider, soft_assert):
outcome = query_resource_attributes(template_rest)
for failure in outcome.failed:
# BZ1546995
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
diff --git a/cfme/tests/infrastructure/test_scvmm_specific.py b/cfme/tests/infrastructure/test_scvmm_specific.py
index 933ab83c77..ffcb63ee49 100644
--- a/cfme/tests/infrastructure/test_scvmm_specific.py
+++ b/cfme/tests/infrastructure/test_scvmm_specific.py
@@ -55,11 +55,11 @@ def cfme_vhd(provider, appliance):
try:
url = '{}/'.format(conf.cfme_data["basic_info"]["cfme_images_url"][stream])
except KeyError:
- pytest.skip("No such stream: {} found in cfme_data.yaml".format(stream))
+ pytest.skip(f"No such stream: {stream} found in cfme_data.yaml")
# get image name
image_name = get_vhd_name(url)
if not image_name:
- pytest.skip("No hyperv vhd image at {}".format(url))
+ pytest.skip(f"No hyperv vhd image at {url}")
# download the image to SCVMM library
if appliance.version > "5.10":
unzip = True
@@ -83,7 +83,7 @@ def scvmm_appliance(provider, cfme_vhd):
""" Create an appliance from the VHD provided on SCVMM """
# script to create template
version = ".".join(re.findall(r"\d+", cfme_vhd)[0:4]) # [0:4] gets the 4 version num for CFME
- template_name = "cfme-{}-template".format(version)
+ template_name = f"cfme-{version}-template"
vhd_path = provider.data.get("vhd_path")
small_disk = provider.data.get("small_disk")
@@ -269,7 +269,7 @@ def test_check_disk_allocation_size_scvmm(vm):
"Total Datastore Used Space"
)
- msg = "Usage before snapshot: {}, Usage after snapshot: {}".format(usage_before, usage_after)
+ msg = f"Usage before snapshot: {usage_before}, Usage after snapshot: {usage_after}"
# convert usage after and before to bytes
vb, kb = usage_before.split()
va, ka = usage_after.split()
diff --git a/cfme/tests/infrastructure/test_snapshot.py b/cfme/tests/infrastructure/test_snapshot.py
index ea014a4305..248a08060e 100644
--- a/cfme/tests/infrastructure/test_snapshot.py
+++ b/cfme/tests/infrastructure/test_snapshot.py
@@ -30,8 +30,8 @@
def new_snapshot(test_vm, has_name=True, memory=False, create_description=True):
name = fauxfactory.gen_alphanumeric(8)
return InfraVm.Snapshot(
- name="test_snapshot_{}".format(name) if has_name else None,
- description="snapshot_{}".format(name) if create_description else None,
+ name=f"test_snapshot_{name}" if has_name else None,
+ description=f"snapshot_{name}" if create_description else None,
memory=memory,
parent_vm=test_vm
)
@@ -474,7 +474,7 @@ def test_snapshot_history_btn(create_vm, provider):
snapshot = new_snapshot(create_vm, has_name=(not provider.one_of(RHEVMProvider)))
snapshot.create()
vm_details_view = navigate_to(create_vm, 'Details')
- item = '"Snapshots" for Virtual Machine "{}"'.format(create_vm.name)
+ item = f'"Snapshots" for Virtual Machine "{create_vm.name}"'
vm_details_view.toolbar.history.item_select(item)
snapshot_view = create_vm.create_view(InfraVmSnapshotView)
assert snapshot_view.is_displayed
diff --git a/cfme/tests/infrastructure/test_tenant_quota.py b/cfme/tests/infrastructure/test_tenant_quota.py
index e17fb3d596..c56341d4c8 100644
--- a/cfme/tests/infrastructure/test_tenant_quota.py
+++ b/cfme/tests/infrastructure/test_tenant_quota.py
@@ -41,7 +41,7 @@ def set_default(provider, request):
be created with specific values for these entries.
"""
with_prov = (
- "Datastore", "ManageIQ (Locked)", "{}".format(provider.string_name), "VM", "Provisioning",
+ "Datastore", "ManageIQ (Locked)", f"{provider.string_name}", "VM", "Provisioning",
"StateMachines", "ProvisionRequestApproval", "Default (Default)"
)
default = (
@@ -101,11 +101,11 @@ def custom_prov_data(request, prov_data, vm_name, template_name):
@pytest.fixture
def set_roottenant_quota(request, roottenant, appliance):
field, value = request.param
- roottenant.set_quota(**{'{}_cb'.format(field): True, field: value})
+ roottenant.set_quota(**{f'{field}_cb': True, field: value})
yield
# will refresh page as navigation to configuration is blocked if alerts are on the page
appliance.server.browser.refresh()
- roottenant.set_quota(**{'{}_cb'.format(field): False})
+ roottenant.set_quota(**{f'{field}_cb': False})
@pytest.fixture(scope='function')
@@ -376,7 +376,7 @@ def test_vm_migration_after_assigning_tenant_quota(appliance, small_vm, set_root
migrate_request = appliance.collections.requests.instantiate(request_description, cells=cells,
partial_check=True)
migrate_request.wait_for_request(method='ui')
- msg = "Request failed with the message {}".format(migrate_request.row.last_message.text)
+ msg = f"Request failed with the message {migrate_request.row.last_message.text}"
assert migrate_request.is_succeeded(method='ui'), msg
diff --git a/cfme/tests/infrastructure/test_timelines.py b/cfme/tests/infrastructure/test_timelines.py
index eec6e084e5..b45400c935 100644
--- a/cfme/tests/infrastructure/test_timelines.py
+++ b/cfme/tests/infrastructure/test_timelines.py
@@ -45,7 +45,7 @@ def new_vm(provider):
def mark_vm_as_appliance(new_vm, appliance):
# set diagnostics vm
relations_view = navigate_to(new_vm, 'EditManagementEngineRelationship', wait_for_view=0)
- server_name = "{name} ({sid})".format(name=appliance.server.name, sid=appliance.server.sid)
+ server_name = f"{appliance.server.name} ({appliance.server.sid})"
relations_view.form.server.select_by_visible_text(server_name)
relations_view.form.save_button.click()
@@ -69,7 +69,7 @@ def control_policy(appliance, new_vm):
action.delete()
-class VMEvent(object):
+class VMEvent:
"""Class for generating events on a VM in order to check it on Timelines.
Args:
vm: A VM object (Object)
@@ -329,7 +329,7 @@ def test_infra_timeline_create_event(new_vm, soft_assert):
else:
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {evt}failed'.format(evt=event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event}failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -354,7 +354,7 @@ def test_infra_timeline_policy_event(new_vm, control_policy, soft_assert):
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
vm_event = VMEvent(new_vm, event)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {} did timeout'.format(event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} did timeout')
vm_event.catch_in_timelines(soft_assert, targets, policy_events=True)
@@ -377,7 +377,7 @@ def test_infra_timeline_stop_event(new_vm, soft_assert):
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
vm_event = VMEvent(new_vm, event)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {} failed'.format(event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -400,7 +400,7 @@ def test_infra_timeline_start_event(new_vm, soft_assert):
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
vm_event = VMEvent(new_vm, event)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {} failed'.format(event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -423,7 +423,7 @@ def test_infra_timeline_suspend_event(new_vm, soft_assert):
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
vm_event = VMEvent(new_vm, event)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {} failed'.format(event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -468,7 +468,7 @@ def test_infra_timeline_clone_event(new_vm, soft_assert):
vm_event = VMEvent(new_vm, event)
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {evt} failed'.format(evt=event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -491,7 +491,7 @@ def test_infra_timeline_migrate_event(new_vm, soft_assert):
vm_event = VMEvent(new_vm, event)
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {evt} failed'.format(evt=event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -516,7 +516,7 @@ def test_infra_timeline_rename_event(new_vm, soft_assert):
vm_event = VMEvent(new_vm, event)
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {evt} failed'.format(evt=event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
vm_event.catch_in_timelines(soft_assert, targets)
@@ -546,6 +546,6 @@ def test_infra_timeline_delete_event(new_vm, soft_assert):
else:
targets = (new_vm, new_vm.cluster, new_vm.host, new_vm.provider)
logger.info('Will generate event %r on machine %r', event, new_vm.name)
- wait_for(vm_event.emit, timeout='7m', message='Event {evt} failed'.format(evt=event))
+ wait_for(vm_event.emit, timeout='7m', message=f'Event {event} failed')
navigate_to(new_vm, 'ArchiveDetails')
vm_event.catch_in_timelines(soft_assert, targets)
diff --git a/cfme/tests/infrastructure/test_vm_clone.py b/cfme/tests/infrastructure/test_vm_clone.py
index 51db247198..57bf08e258 100644
--- a/cfme/tests/infrastructure/test_vm_clone.py
+++ b/cfme/tests/infrastructure/test_vm_clone.py
@@ -63,7 +63,7 @@ def test_vm_clone(appliance, provider, clone_vm_name, create_vm):
request_row = appliance.collections.requests.instantiate(request_description,
partial_check=True)
request_row.wait_for_request(method='ui')
- msg = "Request failed with the message {}".format(request_row.row.last_message.text)
+ msg = f"Request failed with the message {request_row.row.last_message.text}"
assert request_row.is_succeeded(method='ui'), msg
diff --git a/cfme/tests/infrastructure/test_vm_migrate.py b/cfme/tests/infrastructure/test_vm_migrate.py
index c78f1c19ca..e4115a892e 100644
--- a/cfme/tests/infrastructure/test_vm_migrate.py
+++ b/cfme/tests/infrastructure/test_vm_migrate.py
@@ -61,7 +61,7 @@ def test_vm_migrate(appliance, new_vm, provider):
migrate_request = appliance.collections.requests.instantiate(request_description, cells=cells,
partial_check=True)
migrate_request.wait_for_request(method='ui')
- msg = "Request failed with the message {}".format(migrate_request.row.last_message.text)
+ msg = f"Request failed with the message {migrate_request.row.last_message.text}"
assert migrate_request.is_succeeded(method='ui'), msg
diff --git a/cfme/tests/infrastructure/test_vm_ownership.py b/cfme/tests/infrastructure/test_vm_ownership.py
index be2945caf4..a37ef35117 100644
--- a/cfme/tests/infrastructure/test_vm_ownership.py
+++ b/cfme/tests/infrastructure/test_vm_ownership.py
@@ -21,7 +21,7 @@
@test_requirements.rest
-class TestVmOwnershipRESTAPI(object):
+class TestVmOwnershipRESTAPI:
@pytest.fixture(scope="function")
def vm(self, request, provider, appliance):
return _vm(request, provider, appliance)
diff --git a/cfme/tests/infrastructure/test_vm_power_control.py b/cfme/tests/infrastructure/test_vm_power_control.py
index 630c163919..da2804ce1e 100644
--- a/cfme/tests/infrastructure/test_vm_power_control.py
+++ b/cfme/tests/infrastructure/test_vm_power_control.py
@@ -150,7 +150,7 @@ def _wait_for_tools_ok():
return False
-class TestControlOnQuadicons(object):
+class TestControlOnQuadicons:
@pytest.mark.rhv3
def test_power_off_cancel(self, testing_vm, ensure_vm_running, soft_assert):
@@ -244,7 +244,7 @@ def test_power_on(self, appliance, testing_vm, ensure_vm_stopped, soft_assert):
soft_assert(testing_vm.mgmt.is_running, "vm not running")
-class TestVmDetailsPowerControlPerProvider(object):
+class TestVmDetailsPowerControlPerProvider:
@pytest.mark.rhv3
def test_power_off(self, appliance, testing_vm, ensure_vm_running, soft_assert):
@@ -278,7 +278,7 @@ def test_power_off(self, appliance, testing_vm, ensure_vm_running, soft_assert):
new_last_boot_time = view.entities.summary("Power Management").get_text_of(
"Last Boot Time")
soft_assert(new_last_boot_time == last_boot_time,
- "ui: {} should == orig: {}".format(new_last_boot_time, last_boot_time))
+ f"ui: {new_last_boot_time} should == orig: {last_boot_time}")
@pytest.mark.rhv3
def test_power_on(self, appliance, testing_vm, ensure_vm_stopped, soft_assert):
@@ -341,7 +341,7 @@ def test_suspend(self, appliance, testing_vm, ensure_vm_running, soft_assert):
new_last_boot_time = view.entities.summary("Power Management").get_text_of(
"Last Boot Time")
soft_assert(new_last_boot_time == last_boot_time,
- "ui: {} should == orig: {}".format(new_last_boot_time, last_boot_time))
+ f"ui: {new_last_boot_time} should == orig: {last_boot_time}")
@pytest.mark.rhv1
def test_start_from_suspend(self, appliance, testing_vm, ensure_vm_suspended, soft_assert):
@@ -421,7 +421,7 @@ def test_no_template_power_control(provider, soft_assert):
action = 'Start'
elif action == 'Power Off':
action = 'Stop'
- view.flash.assert_message('{} action does not apply to selected items'.format(action))
+ view.flash.assert_message(f'{action} action does not apply to selected items')
view.flash.dismiss()
# Ensure there isn't a power button on the details page
@@ -610,7 +610,7 @@ def test_guest_os_shutdown(appliance, provider, testing_vm_tools, ensure_vm_runn
if not (BZ(1571895, forced_streams=["5.10", "5.11"]).blocks and provider.one_of(RHEVMProvider)):
new_last_boot_time = view.entities.summary("Power Management").get_text_of("Last Boot Time")
soft_assert(new_last_boot_time == last_boot_time,
- "ui: {} should == orig: {}".format(new_last_boot_time, last_boot_time))
+ f"ui: {new_last_boot_time} should == orig: {last_boot_time}")
@pytest.fixture(scope="function")
diff --git a/cfme/tests/infrastructure/test_vm_rest.py b/cfme/tests/infrastructure/test_vm_rest.py
index bde6fe17a9..67e48e4ffb 100644
--- a/cfme/tests/infrastructure/test_vm_rest.py
+++ b/cfme/tests/infrastructure/test_vm_rest.py
@@ -44,7 +44,7 @@ def test_query_vm_attributes(vm, soft_assert):
outcome = query_resource_attributes(vm)
for failure in outcome.failed:
# BZ 1546995
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
@@ -72,7 +72,7 @@ def test_vm_scan(appliance, vm, from_detail):
def _finished():
response.task.reload()
if 'error' in response.task.status.lower():
- pytest.fail('Error when running scan vm method: `{}`'.format(response.task.message))
+ pytest.fail(f'Error when running scan vm method: `{response.task.message}`')
return response.task.state.lower() == 'finished'
diff --git a/cfme/tests/infrastructure/test_vmware_provider.py b/cfme/tests/infrastructure/test_vmware_provider.py
index edfe5d3aa4..bb4c4a41c0 100644
--- a/cfme/tests/infrastructure/test_vmware_provider.py
+++ b/cfme/tests/infrastructure/test_vmware_provider.py
@@ -55,7 +55,7 @@ def test_vmware_provider_filters(appliance, provider, soft_assert):
esx_platforms = ['Platform / ESX 6.0', 'Platform / ESX 6.5', 'Platform / ESX 6.7']
view = navigate_to(appliance.collections.hosts, 'All')
all_options = view.filters.navigation.all_options
- logger.info("All options for Filters are: {} ".format(all_options))
+ logger.info(f"All options for Filters are: {all_options} ")
for esx_platform in esx_platforms:
soft_assert(esx_platform in all_options, "ESX Platform does not exists in options")
@@ -284,7 +284,7 @@ def test_vmware_cdrom_dropdown_not_blank(appliance, provider):
try:
iso_ds = datastore_collection.instantiate(name=ds[0], provider=provider)
except IndexError:
- pytest.skip('No datastores found of type iso on provider {}'.format(provider.name))
+ pytest.skip(f'No datastores found of type iso on provider {provider.name}')
iso_ds.run_smartstate_analysis()
vms_collections = appliance.collections.infra_vms
vm = vms_collections.instantiate(name='cu-24x7', provider=provider)
@@ -342,9 +342,9 @@ def test_vmware_inaccessible_datastore_vm_provisioning(request, appliance, provi
datastore for datastore in provider.mgmt.list_datastore()
if not provider.mgmt.get_datastore(datastore).summary.accessible]
if inaccessible_datastores:
- logger.info("Found {} inaccessible_datastores".format(inaccessible_datastores))
+ logger.info(f"Found {inaccessible_datastores} inaccessible_datastores")
else:
- pytest.skip("This provider {} has no inaccessible_datastores.".format(provider.name))
+ pytest.skip(f"This provider {provider.name} has no inaccessible_datastores.")
vm = appliance.collections.infra_vms.create(
fauxfactory.gen_alphanumeric(18, start="test-vmware-"),
provider, find_in_cfme=True, wait=True,
@@ -426,9 +426,9 @@ def test_esxi_reboot_not_orphan_vms(appliance, provider):
puts \"VM_ID=#{vm.id} name=[#{vm.name}] uid=#{vm.uid_ems}\"'"
result = appliance.ssh_client.run_rails_command(command)
provider.refresh_provider_relationships()
- assert result.success, "SSH Command result was unsuccessful: {}".format(result)
+ assert result.success, f"SSH Command result was unsuccessful: {result}"
if not result.output:
- logger.info("Output of Rails command was {}".format(result.output))
+ logger.info(f"Output of Rails command was {result.output}")
vm_name = re.findall(r"\[.+\]", result.output)[0].split('[')[1].split(']')[0]
vm = appliance.collections.infra_vms.instantiate(name=vm_name, provider=provider)
view = vm.load_details(from_any_provider=True)
@@ -473,7 +473,7 @@ def test_switches_class_present_ems(appliance, provider):
puts "class name [#{p.switches.first.class.name}]"'
"""
result = appliance.ssh_client.run_rails_command(command)
- assert result.success, "SSH Command result was unsuccessful: {}".format(result)
+ assert result.success, f"SSH Command result was unsuccessful: {result}"
logger.info('output of rails command: %s', result.output)
# https://bugzilla.redhat.com/show_bug.cgi?id=1688900#c19
# due to above comment, and since list of Switch classes that can be returned would differ based
@@ -517,7 +517,7 @@ def test_rebuilt_vcenter_duplicate_hosts(appliance, provider):
hosts_before = len(appliance.rest_api.collections.hosts.all)
command = "'Host.all.each { |h| h.ems_id = nil; h.ems_ref = h.id.to_s; h.save! }'"
result = appliance.ssh_client.run_rails_command(command)
- assert result.success, "SSH Command result was unsuccessful: {}".format(result)
+ assert result.success, f"SSH Command result was unsuccessful: {result}"
logger.info('output of rails command: %s', result.output)
provider.refresh_provider_relationships(wait=300, delay=30, refresh_delta=120)
# Using appliance.rest_api as hosts.all() do not return archived hosts, I need those too
diff --git a/cfme/tests/integration/test_aws_iam_auth_and_roles.py b/cfme/tests/integration/test_aws_iam_auth_and_roles.py
index 5c71e94908..9914dcdc7c 100644
--- a/cfme/tests/integration/test_aws_iam_auth_and_roles.py
+++ b/cfme/tests/integration/test_aws_iam_auth_and_roles.py
@@ -33,7 +33,7 @@ def pytest_generate_tests(metafunc):
for role_access, context in roles_and_context:
for group in role_access.keys():
parameter_list.append((group, role_access, context))
- id_list.append('{}-{}'.format(group, context))
+ id_list.append(f'{group}-{context}')
metafunc.parametrize('group_name, role_access, context', parameter_list)
@@ -67,7 +67,7 @@ def test_group_roles(temp_appliance_preconfig_long, setup_aws_auth_provider, gro
password = credentials[iam_group_name]['password']
fullname = credentials[iam_group_name]['fullname']
except KeyError:
- pytest.fail('No match in credentials file for group "{}"'.format(iam_group_name))
+ pytest.fail(f'No match in credentials file for group "{iam_group_name}"')
with temp_appliance_preconfig_long.context.use(context):
# fullname overrides user.name attribute, but doesn't impact login with username credential
diff --git a/cfme/tests/integration/test_cfme_auth.py b/cfme/tests/integration/test_cfme_auth.py
index e5340c9755..bee36905e3 100644
--- a/cfme/tests/integration/test_cfme_auth.py
+++ b/cfme/tests/integration/test_cfme_auth.py
@@ -160,16 +160,16 @@ def test_login_evm_group(
with user_obj:
logger.info('Logging in as user %s, member of groups %s', user_obj, evm_group_names)
view = navigate_to(temp_appliance_preconfig_long.server, 'LoggedIn')
- assert view.is_displayed, 'user {} failed login'.format(user_obj)
+ assert view.is_displayed, f'user {user_obj} failed login'
soft_assert(user_obj.name == view.current_fullname,
- 'user {} is not in view fullname'.format(user_obj))
+ f'user {user_obj} is not in view fullname')
for name in evm_group_names:
soft_assert(name in view.group_names,
- 'user {} evm group {} not in view group_names'.format(user_obj, name))
+ f'user {user_obj} evm group {name} not in view group_names')
# split loop to reduce number of logins
temp_appliance_preconfig_long.server.login_admin()
- assert user_obj.exists, 'user record should have been created for "{}"'.format(user_obj)
+ assert user_obj.exists, f'user record should have been created for "{user_obj}"'
# assert no pwd in logs
assert log_monitor.validate()
@@ -244,11 +244,11 @@ def test_login_retrieve_group(
'user full name "{}" did not match UI display name "{}"'
.format(user_obj.name, view.current_fullname))
soft_assert(group.description in view.group_names,
- u'user group "{}" not displayed in UI groups list "{}"'
+ 'user group "{}" not displayed in UI groups list "{}"'
.format(group.description, view.group_names))
temp_appliance_preconfig_long.server.login_admin() # context should get us back to admin
- assert user_obj.exists, 'User record for "{}" should exist after login'.format(user_obj)
+ assert user_obj.exists, f'User record for "{user_obj}" should exist after login'
# assert no pwd in logs
assert log_monitor.validate()
@@ -271,7 +271,7 @@ def format_user_principal(username, user_type, auth_provider):
username,
auth_provider.user_types[user_type].user_suffix)
else:
- pytest.skip('No user formatting for {} and user type {}'.format(auth_provider, user_type))
+ pytest.skip(f'No user formatting for {auth_provider} and user type {user_type}')
@pytest.fixture(scope='function')
@@ -368,7 +368,7 @@ def test_user_group_switching(
# pick non-evm group when there are multiple groups for the user
if 'evmgroup' not in group.lower():
# create group in CFME via retrieve_group which looks it up on auth_provider
- logger.info(u'Retrieving a user group that is non evm built-in: {}'.format(group))
+ logger.info(f'Retrieving a user group that is non evm built-in: {group}')
retrieved_groups.append(retrieve_group(temp_appliance_preconfig_long,
auth_mode,
auth_user.username,
@@ -391,23 +391,23 @@ def test_user_group_switching(
# check retrieved groups are there
for group in retrieved_groups:
soft_assert(group.description in view.group_names,
- u'user group "{}" not displayed in UI groups list "{}"'
+ 'user group "{}" not displayed in UI groups list "{}"'
.format(group, view.group_names))
# change to the other groups
for other_group in display_other_groups:
- soft_assert(other_group in auth_user.groups, u'Group {} in UI not expected for user {}'
+ soft_assert(other_group in auth_user.groups, 'Group {} in UI not expected for user {}'
.format(other_group, auth_user))
view.change_group(other_group)
- assert view.is_displayed, (u'Not logged in after switching to group {} for {}'
+ assert view.is_displayed, ('Not logged in after switching to group {} for {}'
.format(other_group, auth_user))
# assert selected group has changed
soft_assert(other_group == view.current_groupname,
- u'After switching to group {}, its not displayed as active'
+ 'After switching to group {}, its not displayed as active'
.format(other_group))
temp_appliance_preconfig_long.server.login_admin()
- assert user_obj.exists, 'User record for "{}" should exist after login'.format(auth_user)
+ assert user_obj.exists, f'User record for "{auth_user}" should exist after login'
# assert no pwd in log
assert log_monitor.validate()
diff --git a/cfme/tests/integration/test_ldap_auth_and_roles.py b/cfme/tests/integration/test_ldap_auth_and_roles.py
index bf15661606..50569af278 100644
--- a/cfme/tests/integration/test_ldap_auth_and_roles.py
+++ b/cfme/tests/integration/test_ldap_auth_and_roles.py
@@ -43,7 +43,7 @@ def test_group_roles(request, temp_appliance_preconfig_long, group_name, group_d
username = credentials[group_name]['username']
password = credentials[group_name]['password']
except KeyError:
- pytest.fail('No match in credentials file for group "{}"'.format(group_name))
+ pytest.fail(f'No match in credentials file for group "{group_name}"')
user = appliance.collections.users.simple_user(username, password)
with user:
diff --git a/cfme/tests/intelligence/chargeback/test_chargeback_long_term_rates.py b/cfme/tests/intelligence/chargeback/test_chargeback_long_term_rates.py
index 6b38745792..71789a2cf9 100644
--- a/cfme/tests/intelligence/chargeback/test_chargeback_long_term_rates.py
+++ b/cfme/tests/intelligence/chargeback/test_chargeback_long_term_rates.py
@@ -67,7 +67,7 @@ def vm_ownership(enable_candu, provider, appliance):
cost_center='Workload',
value_assign='Database')
vm.set_ownership(user=user)
- logger.info('Assigned VM OWNERSHIP for {} running on {}'.format(vm_name, provider.name))
+ logger.info(f'Assigned VM OWNERSHIP for {vm_name} running on {provider.name}')
yield user.name
vm.unset_ownership()
@@ -155,7 +155,7 @@ def verify_records_metrics_table(appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_capture('realtime', 1.hour.ago.utc, Time.now.utc)\""
.format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to capture VM C&U data:".format(ret.output)
+ assert ret.success, f"Failed to capture VM C&U data:"
with appliance.db.client.transaction:
result = (
@@ -215,7 +215,7 @@ def resource_usage(vm_ownership, appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_rollup_range(1.hour.ago.utc, Time.now.utc,'realtime')\"".
format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to rollup VM C&U data:".format(ret.out)
+ assert ret.success, f"Failed to rollup VM C&U data:"
wait_for(verify_records_rollups_table, [appliance, provider], timeout=600,
message='Waiting for hourly rollups')
@@ -343,7 +343,7 @@ def chargeback_report_custom(appliance, vm_ownership, assign_custom_rate, interv
}
report = appliance.collections.reports.create(is_candu=True, **data)
- logger.info('Queuing chargeback report for {} rate'.format(interval))
+ logger.info(f'Queuing chargeback report for {interval} rate')
report.queue(wait_for_finish=True)
if not list(report.saved_reports.all()[0].data.rows):
diff --git a/cfme/tests/intelligence/chargeback/test_resource_allocation.py b/cfme/tests/intelligence/chargeback/test_resource_allocation.py
index 6e39e8d816..44a5e90166 100644
--- a/cfme/tests/intelligence/chargeback/test_resource_allocation.py
+++ b/cfme/tests/intelligence/chargeback/test_resource_allocation.py
@@ -67,7 +67,7 @@ def vm_ownership(enable_candu, provider, appliance):
vm = appliance.provider_based_collection(provider, coll_type='vms').instantiate(vm_name,
provider)
if not vm.exists_on_provider:
- pytest.skip('Skipping test, {} VM does not exist'.format(vm_name))
+ pytest.skip(f'Skipping test, {vm_name} VM does not exist')
vm.mgmt.ensure_state(VmState.RUNNING)
group_collection = appliance.collections.groups
@@ -81,7 +81,7 @@ def vm_ownership(enable_candu, provider, appliance):
cost_center='Workload',
value_assign='Database')
vm.set_ownership(user=user)
- logger.info('Assigned VM OWNERSHIP for {} running on {}'.format(vm_name, provider.name))
+ logger.info(f'Assigned VM OWNERSHIP for {vm_name} running on {provider.name}')
yield user.name
vm.unset_ownership()
@@ -178,7 +178,7 @@ def verify_records_metrics_table(appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_capture('realtime', 1.hour.ago.utc, Time.now.utc)\""
.format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to capture VM C&U data:".format(ret.output)
+ assert ret.success, f"Failed to capture VM C&U data:"
with appliance.db.client.transaction:
result = (
@@ -247,7 +247,7 @@ def resource_alloc(vm_ownership, appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_rollup_range(1.hour.ago.utc, Time.now.utc,'realtime')\"".
format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to rollup VM C&U data:".format(ret.out)
+ assert ret.success, f"Failed to rollup VM C&U data:"
wait_for(verify_records_rollups_table, [appliance, provider], timeout=600,
message='Waiting for hourly rollups')
@@ -346,7 +346,7 @@ def chargeback_report_custom(appliance, vm_ownership, assign_custom_rate, provid
}
report = appliance.collections.reports.create(is_candu=True, **data)
- logger.info('Queuing chargeback report with custom rate for {} provider'.format(provider.name))
+ logger.info(f'Queuing chargeback report with custom rate for {provider.name} provider')
report.queue(wait_for_finish=True)
if not list(report.saved_reports.all()[0].data.rows):
diff --git a/cfme/tests/intelligence/reports/test_canned_corresponds.py b/cfme/tests/intelligence/reports/test_canned_corresponds.py
index c5d8d02c9a..3d9bb953b2 100644
--- a/cfme/tests/intelligence/reports/test_canned_corresponds.py
+++ b/cfme/tests/intelligence/reports/test_canned_corresponds.py
@@ -100,7 +100,7 @@ def test_cluster_relationships(appliance, request, soft_assert, setup_provider):
cluster_list = provider.mgmt.list_clusters() if isinstance(
provider, SCVMMProvider) else provider.mgmt.list_cluster()
verified_cluster = [item for item in cluster_list if name in item]
- soft_assert(verified_cluster, "Cluster {} not found in {}".format(name, provider_name))
+ soft_assert(verified_cluster, f"Cluster {name} not found in {provider_name}")
if not host_name:
continue # No host name
host_ip = resolve_hostname(host_name, force=True)
@@ -128,7 +128,7 @@ def test_cluster_relationships(appliance, request, soft_assert, setup_provider):
if host_ip == ip_from_provider:
break
else:
- soft_assert(False, "Hostname {} not found in {}".format(host_name, provider_name))
+ soft_assert(False, f"Hostname {host_name} not found in {provider_name}")
@pytest.mark.rhv2
@@ -177,10 +177,10 @@ def test_operations_vm_on(
for vm in vms_in_db:
# Following check is based on BZ 1504010
assert vm_names.count(vm.vm_name) == 1, (
- 'There is a duplicate entry in DB for VM {}'.format(vm.vm_name))
+ f'There is a duplicate entry in DB for VM {vm.vm_name}')
store_path = vm.vm_location
if vm.storages_name:
- store_path = '{}/{}'.format(vm.storages_name, store_path)
+ store_path = f'{vm.storages_name}/{store_path}'
for item in report.data.rows:
if vm.vm_name == item['VM Name']:
assert compare(vm.hosts_name, item['Host'])
diff --git a/cfme/tests/intelligence/reports/test_crud.py b/cfme/tests/intelligence/reports/test_crud.py
index d0824b7e8e..8d4079d608 100644
--- a/cfme/tests/intelligence/reports/test_crud.py
+++ b/cfme/tests/intelligence/reports/test_crud.py
@@ -104,7 +104,7 @@ def test_reports_schedule_crud(schedule_data, appliance, request):
request.addfinalizer(schedule.delete_if_exists)
view = schedule.create_view(ScheduleDetailsView)
- view.flash.assert_success_message('Schedule "{}" was added'.format(schedule.name))
+ view.flash.assert_success_message(f'Schedule "{schedule.name}" was added')
# update
date = datetime.datetime.today() + datetime.timedelta(5)
@@ -114,7 +114,7 @@ def test_reports_schedule_crud(schedule_data, appliance, request):
with update(schedule):
schedule.description = updated_description
schedule.timer = updated_timer
- view.flash.assert_message('Schedule "{}" was saved'.format(schedule.name))
+ view.flash.assert_message(f'Schedule "{schedule.name}" was saved')
assert view.schedule_info.get_text_of("Description") == updated_description
@@ -128,7 +128,7 @@ def test_reports_schedule_crud(schedule_data, appliance, request):
# delete
schedule.delete()
- view.flash.assert_message("Schedule {} was deleted".format(schedule.name))
+ view.flash.assert_message(f"Schedule {schedule.name} was deleted")
@pytest.mark.sauce
@@ -145,7 +145,7 @@ def test_menuwidget_crud(appliance, request):
caseimportance: critical
initialEstimate: 1/12h
"""
- dashboard = "{} / Dashboard".format(appliance.server.intel_name)
+ dashboard = f"{appliance.server.intel_name} / Dashboard"
w = appliance.collections.dashboard_report_widgets.create(
appliance.collections.dashboard_report_widgets.MENU,
fauxfactory.gen_alphanumeric(),
@@ -160,7 +160,7 @@ def test_menuwidget_crud(appliance, request):
request.addfinalizer(w.delete_if_exists)
view = w.create_view(AllDashboardWidgetsView)
- view.flash.assert_message('Widget "{}" was saved'.format(w.title))
+ view.flash.assert_message(f'Widget "{w.title}" was saved')
with update(w):
w.active = False
w.delete()
@@ -194,7 +194,7 @@ def test_reportwidget_crud(appliance, request):
request.addfinalizer(w.delete_if_exists)
view = w.create_view(AllDashboardWidgetsView)
- view.flash.assert_message('Widget "{}" was saved'.format(w.title))
+ view.flash.assert_message(f'Widget "{w.title}" was saved')
with update(w):
w.active = False
w.delete()
@@ -222,7 +222,7 @@ def test_chartwidget_crud(appliance, request):
request.addfinalizer(w.delete_if_exists)
view = w.create_view(AllDashboardWidgetsView)
- view.flash.assert_message('Widget "{}" was saved'.format(w.title))
+ view.flash.assert_message(f'Widget "{w.title}" was saved')
with update(w):
w.active = False
w.delete()
@@ -252,7 +252,7 @@ def test_rssfeedwidget_crud(appliance, request):
request.addfinalizer(w.delete_if_exists)
view = w.create_view(AllDashboardWidgetsView)
- view.flash.assert_message('Widget "{}" was saved'.format(w.title))
+ view.flash.assert_message(f'Widget "{w.title}" was saved')
# Basic update
with update(w):
w.active = False
@@ -313,7 +313,7 @@ def test_run_report(appliance):
def rest_running_report_finishes():
response.task.reload()
if "error" in response.task.status.lower():
- pytest.fail("Error when running report: `{}`".format(response.task.message))
+ pytest.fail(f"Error when running report: `{response.task.message}`")
return response.task.state.lower() == 'finished'
result = appliance.rest_api.collections.results.get(id=response.result_id)
@@ -352,13 +352,13 @@ def _finalize():
)
report.delete_if_exists()
- assert response['message'] == 'Imported Report: [{}]'.format(menu_name)
+ assert response['message'] == f'Imported Report: [{menu_name}]'
report = appliance.rest_api.collections.reports.get(name=menu_name)
assert report.name == menu_name
response, = appliance.rest_api.collections.reports.action.execute_action("import", data)
assert_response(appliance)
- assert response['message'] == 'Skipping Report (already in DB): [{}]'.format(menu_name)
+ assert response['message'] == f'Skipping Report (already in DB): [{menu_name}]'
@pytest.mark.sauce
diff --git a/cfme/tests/intelligence/reports/test_import_export_reports_widgets.py b/cfme/tests/intelligence/reports/test_import_export_reports_widgets.py
index 706d03e891..0d04cbd848 100644
--- a/cfme/tests/intelligence/reports/test_import_export_reports_widgets.py
+++ b/cfme/tests/intelligence/reports/test_import_export_reports_widgets.py
@@ -16,7 +16,7 @@
def yaml_path(yaml_name):
""" Returns yaml path of the file with yaml_name name"""
- yaml_name = "{}.yaml".format(yaml_name)
+ yaml_name = f"{yaml_name}.yaml"
try:
fs = FTPClientWrapper(cfme_data.ftpserver.entities.reports)
@@ -115,7 +115,7 @@ def test_import_report(appliance, report):
collection.import_report(yaml_path("import_report"))
view = collection.create_view(ImportExportCustomReportsView)
assert view.is_displayed
- view.flash.assert_message("Imported Report: [{}]".format(report.menu_name))
+ view.flash.assert_message(f"Imported Report: [{report.menu_name}]")
assert report.exists
@@ -160,10 +160,10 @@ def test_import_duplicate_report(appliance, report, overwrite):
collection.import_report(file_path, overwrite=overwrite)
if overwrite:
- view.flash.assert_message("Replaced Report: [{}]".format(report.menu_name))
+ view.flash.assert_message(f"Replaced Report: [{report.menu_name}]")
else:
view.flash.assert_message(
- "Skipping Report (already in DB): [{}]".format(report.menu_name)
+ f"Skipping Report (already in DB): [{report.menu_name}]"
)
diff --git a/cfme/tests/intelligence/reports/test_metering_report.py b/cfme/tests/intelligence/reports/test_metering_report.py
index a1eff383c0..a7345ea160 100644
--- a/cfme/tests/intelligence/reports/test_metering_report.py
+++ b/cfme/tests/intelligence/reports/test_metering_report.py
@@ -58,7 +58,7 @@ def vm_ownership(enable_candu, clean_setup_provider, provider, appliance):
vm = collection.instantiate(vm_name, provider)
if not vm.exists_on_provider:
- pytest.skip("Skipping test, {} VM does not exist".format(vm_name))
+ pytest.skip(f"Skipping test, {vm_name} VM does not exist")
vm.mgmt.ensure_state(VmState.RUNNING)
group_collection = appliance.collections.groups
@@ -74,7 +74,7 @@ def vm_ownership(enable_candu, clean_setup_provider, provider, appliance):
try:
vm.set_ownership(user=user)
- logger.info('Assigned VM OWNERSHIP for {} running on {}'.format(vm_name, provider.name))
+ logger.info(f'Assigned VM OWNERSHIP for {vm_name} running on {provider.name}')
yield user.name
finally:
@@ -170,7 +170,7 @@ def verify_records_metrics_table(appliance, provider, vm_name):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_capture('realtime', 2.hour.ago.utc, Time.now.utc)\""
.format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to capture VM C&U data:".format(ret.output)
+ assert ret.success, f"Failed to capture VM C&U data:"
with appliance.db.client.transaction:
result = (
@@ -205,7 +205,7 @@ def verify_records_metrics_table(appliance, provider, vm_name):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_rollup_range(2.hour.ago.utc, Time.now.utc,'realtime')\"".
format(provider.id, repr(vm_name)))
- assert ret.success, "Failed to rollup VM C&U data:".format(ret.out)
+ assert ret.success, f"Failed to rollup VM C&U data:"
wait_for(verify_records_rollups_table, [appliance, provider, vm_name], timeout=600,
fail_condition=False, message='Waiting for hourly rollups')
@@ -260,7 +260,7 @@ def metering_report(appliance, vm_ownership, provider):
}
report = appliance.collections.reports.create(is_candu=True, **data)
- logger.info('Queuing Metering report for {} provider'.format(provider.name))
+ logger.info(f'Queuing Metering report for {provider.name} provider')
report.queue(wait_for_finish=True)
yield list(report.saved_reports.all()[0].data.rows)
diff --git a/cfme/tests/intelligence/reports/test_report_corresponds.py b/cfme/tests/intelligence/reports/test_report_corresponds.py
index d5b155c10d..5ee42e9629 100644
--- a/cfme/tests/intelligence/reports/test_report_corresponds.py
+++ b/cfme/tests/intelligence/reports/test_report_corresponds.py
@@ -77,5 +77,5 @@ def test_custom_vm_report(soft_assert, report_vms):
found = True
soft_assert(
found,
- "Host {} not found in {}!".format(possible_ips_or_hosts, provider_hosts_and_ips)
+ f"Host {possible_ips_or_hosts} not found in {provider_hosts_and_ips}!"
)
diff --git a/cfme/tests/intelligence/reports/test_validate_chargeback_report.py b/cfme/tests/intelligence/reports/test_validate_chargeback_report.py
index d2413317e0..a3edc10721 100644
--- a/cfme/tests/intelligence/reports/test_validate_chargeback_report.py
+++ b/cfme/tests/intelligence/reports/test_validate_chargeback_report.py
@@ -91,7 +91,7 @@ def vm_ownership(enable_candu, provider, appliance):
cost_center='Workload',
value_assign='Database')
vm.set_ownership(user=user)
- logger.info('Assigned VM OWNERSHIP for {} running on {}'.format(vm_name, provider.name))
+ logger.info(f'Assigned VM OWNERSHIP for {vm_name} running on {provider.name}')
yield user.name
finally:
@@ -230,7 +230,7 @@ def verify_records_metrics_table(appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_capture('realtime', 1.hour.ago.utc, Time.now.utc)\""
.format(provider.id, repr(vm_name)))
- assert result.success, "Failed to capture VM C&U data:".format(result.output)
+ assert result.success, f"Failed to capture VM C&U data:"
with appliance.db.client.transaction:
result = (
@@ -264,7 +264,7 @@ def verify_records_metrics_table(appliance, provider):
"\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\
vm.perf_rollup_range(1.hour.ago.utc, Time.now.utc,'realtime')\"".
format(provider.id, repr(vm_name)))
- assert result.success, "Failed to rollup VM C&U data:".format(result.output)
+ assert result.success, f"Failed to rollup VM C&U data:"
wait_for(verify_records_rollups_table, [appliance, provider], timeout=600, fail_condition=False,
message='Waiting for hourly rollups')
@@ -433,7 +433,7 @@ def chargeback_report_default(appliance, vm_ownership, assign_default_rate, prov
}
report = appliance.collections.reports.create(is_candu=True, **data)
- logger.info('Queuing chargeback report with default rate for {} provider'.format(provider.name))
+ logger.info(f'Queuing chargeback report with default rate for {provider.name} provider')
report.queue(wait_for_finish=True)
yield list(report.saved_reports.all()[0].data.rows)
@@ -463,7 +463,7 @@ def chargeback_report_custom(appliance, vm_ownership, assign_custom_rate, provid
}
report = appliance.collections.reports.create(is_candu=True, **data)
- logger.info('Queuing chargeback report with custom rate for {} provider'.format(provider.name))
+ logger.info(f'Queuing chargeback report with custom rate for {provider.name} provider')
report.queue(wait_for_finish=True)
yield list(report.saved_reports.all()[0].data.rows)
diff --git a/cfme/tests/intelligence/reports/test_views.py b/cfme/tests/intelligence/reports/test_views.py
index 849198390f..32259f88c0 100644
--- a/cfme/tests/intelligence/reports/test_views.py
+++ b/cfme/tests/intelligence/reports/test_views.py
@@ -54,4 +54,4 @@ def test_report_view(report, view_mode):
report.browser.refresh()
view = navigate_to(report, "Details")
view.view_selector.select(view_mode)
- assert view.view_selector.selected == view_mode, "View setting failed for {}".format(view)
+ assert view.view_selector.selected == view_mode, f"View setting failed for {view}"
diff --git a/cfme/tests/intelligence/reports/test_widgets.py b/cfme/tests/intelligence/reports/test_widgets.py
index 53d7549bb2..b2ff8ca9b7 100644
--- a/cfme/tests/intelligence/reports/test_widgets.py
+++ b/cfme/tests/intelligence/reports/test_widgets.py
@@ -94,7 +94,7 @@ def _finalize():
"Count of the widgets differ")
for custom_w in custom_widgets:
soft_assert(dashboard_view.widgets(custom_w.title).is_displayed,
- "Widget {} not found on dashboard".format(custom_w.title))
+ f"Widget {custom_w.title} not found on dashboard")
@test_requirements.dashboard
@@ -197,7 +197,7 @@ def test_generate_widget_content_by_automate(request, appliance, klass, namespac
request.addfinalizer(widget.delete)
# Added newly created widget to dashboard
view = widget.create_view(AllDashboardWidgetsView)
- view.flash.assert_message('Widget "{title}" was saved'.format(title=widget.title))
+ view.flash.assert_message(f'Widget "{widget.title}" was saved')
view = navigate_to(appliance.server, 'Dashboard')
view.add_widget.item_select(widget.title)
diff --git a/cfme/tests/intelligence/test_chargeback.py b/cfme/tests/intelligence/test_chargeback.py
index 391230b40b..b18f0617df 100644
--- a/cfme/tests/intelligence/test_chargeback.py
+++ b/cfme/tests/intelligence/test_chargeback.py
@@ -119,18 +119,18 @@ def test_chargeback_rate(rate_resource, rate_type, rate_action, request, chargeb
view = cb_rate.create_view(navigator.get_class(cb_rate.parent, 'All').VIEW, wait=10)
view.flash.assert_success_message(
- 'Chargeback Rate "{}" was added'.format(cb_rate.description))
+ f'Chargeback Rate "{cb_rate.description}" was added')
assert cb_rate.exists
if rate_action == 'delete':
cb_rate.delete()
view.flash.assert_success_message(
- 'Chargeback Rate "{}": Delete successful'.format(cb_rate.description))
+ f'Chargeback Rate "{cb_rate.description}": Delete successful')
assert not cb_rate.exists
if rate_action == 'edit':
with update(cb_rate):
- cb_rate.description = '{}_edited'.format(cb_rate.description)
+ cb_rate.description = f'{cb_rate.description}_edited'
if rate_resource == 'compute':
cb_rate.fields = {
'Fixed Compute Cost 1': random_per_time(fixed_rate='500'),
@@ -143,11 +143,11 @@ def test_chargeback_rate(rate_resource, rate_type, rate_action, request, chargeb
}
view = cb_rate.create_view(navigator.get_class(cb_rate, 'Details').VIEW, wait=10)
view.flash.assert_success_message(
- 'Chargeback Rate "{}" was saved'.format(cb_rate.description))
+ f'Chargeback Rate "{cb_rate.description}" was saved')
assert cb_rate.exists
-class TestRatesViaREST(object):
+class TestRatesViaREST:
@pytest.fixture(scope="function")
def rates(self, request, appliance):
response = _rates(request, appliance)
diff --git a/cfme/tests/intelligence/test_dashboard.py b/cfme/tests/intelligence/test_dashboard.py
index 2390667f5b..29bb73516c 100644
--- a/cfme/tests/intelligence/test_dashboard.py
+++ b/cfme/tests/intelligence/test_dashboard.py
@@ -45,9 +45,9 @@ def test_widgets_operation(dashboards, widgets, soft_assert, infra_provider):
# Then we can check the operations
for widget in widgets:
widget.minimize()
- soft_assert(widget.minimized, 'Widget {} could not be minimized'.format(widget.name))
+ soft_assert(widget.minimized, f'Widget {widget.name} could not be minimized')
widget.restore()
- soft_assert(not widget.minimized, 'Widget {} could not be maximized'.format(widget.name))
+ soft_assert(not widget.minimized, f'Widget {widget.name} could not be maximized')
# TODO: Once modal problems resolved, uncomment
# if widget.can_zoom:
# widget.zoom()
@@ -91,12 +91,12 @@ def test_custom_dashboards(request, soft_assert, number_dashboards, dashboards,
dash_dict = {d.title: d for d in dashboards_to_delete}
try:
for dash in dashboards.all():
- soft_assert(dash.name in dash_dict, "Dashboard {} not found!".format(dash.name))
+ soft_assert(dash.name in dash_dict, f"Dashboard {dash.name} not found!")
dash.dashboard_view.click()
if dash.name in list(dash_dict.keys()):
for widget in dash.collections.widgets.all():
soft_assert(widget.name in dash_dict[dash.name].widgets,
- "Widget {} not found in {}!".format(widget.name, dash.name))
+ f"Widget {widget.name} not found in {dash.name}!")
del dash_dict[dash.name]
soft_assert(not dash_dict, "Some of the dashboards were not found! ({})".format(
", ".join(list(dash_dict.keys()))))
diff --git a/cfme/tests/networks/nuage/test_events_are_triggered.py b/cfme/tests/networks/nuage/test_events_are_triggered.py
index 750c2b23ba..cc38d9f905 100644
--- a/cfme/tests/networks/nuage/test_events_are_triggered.py
+++ b/cfme/tests/networks/nuage/test_events_are_triggered.py
@@ -102,7 +102,7 @@ def cmp_function(_, full_data):
listener(
{
- 'full_data': '{} [ID={}] {}'.format(event_type, entity_id, comment),
+ 'full_data': f'{event_type} [ID={entity_id}] {comment}',
'cmp_func': cmp_function
},
source='NUAGE',
diff --git a/cfme/tests/networks/test_provision_to_virtual_network.py b/cfme/tests/networks/test_provision_to_virtual_network.py
index df389294ce..a9cd1bcad5 100644
--- a/cfme/tests/networks/test_provision_to_virtual_network.py
+++ b/cfme/tests/networks/test_provision_to_virtual_network.py
@@ -25,7 +25,7 @@
def network(provider, appliance):
"""Adding cloud network in ui."""
test_name = fauxfactory.gen_alphanumeric(18, start="test_network_")
- net_manager = '{} Network Manager'.format(provider.name)
+ net_manager = f'{provider.name} Network Manager'
collection = appliance.collections.network_providers
network_provider = collection.instantiate(prov_class=NetworkProvider, name=net_manager)
@@ -87,5 +87,5 @@ def _cleanup():
delay=50,
num_sec=900,
fail_func=appliance.server.browser.refresh,
- message='Cannot do provision for vm {}.'.format(vm_name)
+ message=f'Cannot do provision for vm {vm_name}.'
)
diff --git a/cfme/tests/networks/test_sdn_downloads.py b/cfme/tests/networks/test_sdn_downloads.py
index 66b33dc92b..7d2ab35eb0 100644
--- a/cfme/tests/networks/test_sdn_downloads.py
+++ b/cfme/tests/networks/test_sdn_downloads.py
@@ -97,4 +97,4 @@ def test_download_pdf_summary(appliance, collection_type, provider):
random_obj = random.choice(all_entities)
download_summary(random_obj)
else:
- pytest.skip('{} entities not available'.format(collection_type))
+ pytest.skip(f'{collection_type} entities not available')
diff --git a/cfme/tests/networks/test_sdn_inventory_collection.py b/cfme/tests/networks/test_sdn_inventory_collection.py
index 278f19ad7f..99b0795887 100644
--- a/cfme/tests/networks/test_sdn_inventory_collection.py
+++ b/cfme/tests/networks/test_sdn_inventory_collection.py
@@ -34,10 +34,10 @@ def test_sdn_api_inventory_networks(provider, appliance):
# Ec2 API returns only the Id of the networks, so the alternative is to count the networks
# instead of checking there names. Less accurate, but Better than nothing...
assert len(cfme_networks) == len(prov_networks), 'There is NOT the same amount of networks'
- 'in CFME than on EC2: {prov} {cfme}'.format(prov=prov_networks, cfme=cfme_networks)
+ f'in CFME than on EC2: {prov_networks} {cfme_networks}'
else:
assert cfme_networks == prov_networks, 'Prov networks list: {networks} different from '
- 'cfme list: {cfme}'.format(networks=prov_networks, cfme=cfme_networks)
+ f'cfme list: {cfme_networks}'
@pytest.mark.provider([AzureProvider, EC2Provider], scope='function')
@@ -60,7 +60,7 @@ def test_sdn_api_inventory_routers(provider, appliance):
cfme_routers = sorted([rt.name for rt in appliance.collections.network_routers.all()])
assert cfme_routers == prov_routers, 'Prov routers list: {router} different from cfme list: '
- '{cfme}'.format(router=prov_routers, cfme=cfme_routers)
+ f'{cfme_routers}'
def test_sdn_api_inventory_subnets(provider, appliance):
@@ -86,7 +86,7 @@ def test_sdn_api_inventory_subnets(provider, appliance):
prov_subnets = provider.mgmt.list_subnet()
assert sorted(cfme_subnets) == sorted(prov_subnets), 'Prov subnets list: {sub} '
- 'different from cfme list: {cfme}'.format(sub=prov_subnets, cfme=cfme_subnets)
+ f'different from cfme list: {cfme_subnets}'
@pytest.mark.provider([EC2Provider, AzureProvider], scope='function')
@@ -106,7 +106,7 @@ def test_sdn_api_inventory_security_groups(provider, appliance):
cfme_sec_gp = sorted([sec.name for sec in appliance.collections.network_security_groups.all()])
assert prov_sec_gp == cfme_sec_gp, 'Prov security groups list: {sec} different from '
- 'cfme list: {cfme}'.format(sec=prov_sec_gp, cfme=cfme_sec_gp)
+ f'cfme list: {cfme_sec_gp}'
@pytest.mark.ignore_stream('5.11') # Load Balancers are deprecated in 5.11
@@ -127,7 +127,7 @@ def test_sdn_api_inventory_loadbalancers(provider, appliance):
cfme_load_balancers = sorted([lb.name for lb in appliance.collections.balancers.all()])
assert prov_load_balancers == cfme_load_balancers, 'Provider balancer list: {prov} different '
- 'from cfme list: {cfme}'.format(prov=prov_load_balancers, cfme=cfme_load_balancers)
+ f'from cfme list: {cfme_load_balancers}'
@pytest.fixture
diff --git a/cfme/tests/networks/test_tag_tagvis.py b/cfme/tests/networks/test_tag_tagvis.py
index 0c04da3d28..c70fa13536 100644
--- a/cfme/tests/networks/test_tag_tagvis.py
+++ b/cfme/tests/networks/test_tag_tagvis.py
@@ -42,7 +42,7 @@
def child_visibility(appliance, network_provider, relationship, view):
network_provider_view = navigate_to(network_provider, 'Details')
if network_provider_view.entities.relationships.get_text_of(relationship) == "0":
- pytest.skip("There are no relationships for {}".format(relationship))
+ pytest.skip(f"There are no relationships for {relationship}")
network_provider_view.entities.relationships.click_at(relationship)
relationship_view = appliance.browser.create_view(view)
try:
diff --git a/cfme/tests/openstack/cloud/test_flavors.py b/cfme/tests/openstack/cloud/test_flavors.py
index ab557b67cf..ea176ac595 100644
--- a/cfme/tests/openstack/cloud/test_flavors.py
+++ b/cfme/tests/openstack/cloud/test_flavors.py
@@ -59,7 +59,7 @@ def private_flavor(appliance, provider):
view = appliance.browser.create_view(navigator.get_class(collection, 'All').VIEW)
view.flash.assert_success_message(
- 'Add of Flavor "{}" was successfully initialized.'.format(private_flavor.name))
+ f'Add of Flavor "{private_flavor.name}" was successfully initialized.')
wait_for(lambda: private_flavor.exists, delay=5, timeout=600, fail_func=private_flavor.refresh,
message='Wait for flavor to appear')
@@ -192,7 +192,7 @@ def cleanup():
view = appliance.browser.create_view(navigator.get_class(collection, 'All').VIEW)
view.flash.assert_success_message(
- 'Add of Flavor "{}" was successfully initialized.'.format(flavor.name))
+ f'Add of Flavor "{flavor.name}" was successfully initialized.')
wait_for(lambda: flavor.exists, delay=5, timeout=600, fail_func=flavor.refresh,
message='Wait for flavor to appear')
@@ -200,7 +200,7 @@ def cleanup():
flavor.delete()
view = appliance.browser.create_view(navigator.get_class(collection, 'All').VIEW)
view.flash.assert_success_message(
- 'Delete of Flavor "{}" was successfully initiated.'.format(flavor.name))
+ f'Delete of Flavor "{flavor.name}" was successfully initiated.')
wait_for(lambda: not flavor.exists, delay=5, timeout=600, fail_func=flavor.refresh,
message='Wait for flavor to appear')
@@ -281,7 +281,7 @@ def test_create_instance_with_private_flavor(instance_with_private_flavor, provi
flavor_obj.delete()
view = navigate_to(collection, "All")
view.flash.assert_success_message(
- 'Delete of Flavor "{name}" was successfully initiated.'.format(name=flavor_obj.name))
+ f'Delete of Flavor "{flavor_obj.name}" was successfully initiated.')
wait_for(lambda: not flavor_obj.exists, delay=5, timeout=600, fail_func=flavor_obj.refresh,
message='Wait for flavor to disappear')
@@ -311,6 +311,6 @@ def test_filter_by_flavor_via_api(appliance):
1596069
"""
flavor = choice(appliance.rest_api.collections.flavors.all)
- url = "/api/vms?filter[]=flavor.name='{}'".format(flavor.name)
+ url = f"/api/vms?filter[]=flavor.name='{flavor.name}'"
appliance.rest_api.get(appliance.url_path(url))
assert_response(appliance)
diff --git a/cfme/tests/openstack/cloud/test_instances.py b/cfme/tests/openstack/cloud/test_instances.py
index 39581ff09b..0ab94d79ca 100644
--- a/cfme/tests/openstack/cloud/test_instances.py
+++ b/cfme/tests/openstack/cloud/test_instances.py
@@ -67,7 +67,7 @@ def new_instance(provider):
@pytest.fixture(scope='function')
def volume(appliance, provider):
collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
volume = collection.create(name=fauxfactory.gen_alpha(start="vol_"),
storage_manager=storage_manager,
tenant=provider.data['provisioning']['cloud_tenant'],
@@ -91,7 +91,7 @@ def volume_type_is_displayed():
return volume_type.exists
collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
volume = collection.create(name=fauxfactory.gen_alpha(start="vol_"),
storage_manager=storage_manager,
tenant=provider.data['provisioning']['cloud_tenant'],
@@ -319,7 +319,7 @@ def test_instance_operating_system_linux(new_instance):
view = navigate_to(new_instance, 'Details')
os = view.entities.summary('Properties').get_text_of("Operating System")
prov_data_os = new_instance.provider.data['provisioning']['image']['os_distro']
- assert os == prov_data_os, 'OS type mismatch: expected {} and got {}'.format(prov_data_os, os)
+ assert os == prov_data_os, f'OS type mismatch: expected {prov_data_os} and got {os}'
@pytest.mark.regression
@@ -334,7 +334,7 @@ def test_instance_attach_volume(volume, new_instance, appliance):
new_instance.attach_volume(volume.name)
view = appliance.browser.create_view(navigator.get_class(new_instance, 'AttachVolume').VIEW)
view.flash.assert_success_message(
- 'Attaching Cloud Volume "{}" to {} finished'.format(volume.name, new_instance.name))
+ f'Attaching Cloud Volume "{volume.name}" to {new_instance.name} finished')
wait_for(lambda: new_instance.volume_count > initial_volume_count,
delay=20,
diff --git a/cfme/tests/openstack/cloud/test_networks.py b/cfme/tests/openstack/cloud/test_networks.py
index 54b03202e2..b95b6d6fcd 100644
--- a/cfme/tests/openstack/cloud/test_networks.py
+++ b/cfme/tests/openstack/cloud/test_networks.py
@@ -33,7 +33,7 @@ def create_network(appliance, provider, is_external):
tenant=provider.data.get('provisioning').get('cloud_tenant'),
provider=provider,
network_type='VXLAN',
- network_manager='{} Network Manager'.format(provider.name),
+ network_manager=f'{provider.name} Network Manager',
is_external=is_external)
return network
@@ -43,7 +43,7 @@ def create_subnet(appliance, provider, network):
subnet = collection.create(name=fauxfactory.gen_alpha(12, start="subnet_"),
tenant=provider.data.get('provisioning').get('cloud_tenant'),
provider=provider,
- network_manager='{} Network Manager'.format(provider.name),
+ network_manager=f'{provider.name} Network Manager',
network_name=network.name,
cidr=SUBNET_CIDR)
return subnet
@@ -54,7 +54,7 @@ def create_router(appliance, provider, ext_gw, ext_network=None, ext_subnet=None
router = collection.create(name=fauxfactory.gen_alpha(12, start="router_"),
tenant=provider.data.get('provisioning').get('cloud_tenant'),
provider=provider,
- network_manager='{} Network Manager'.format(provider.name),
+ network_manager=f'{provider.name} Network Manager',
has_external_gw=ext_gw,
ext_network=ext_network,
ext_network_subnet=ext_subnet)
diff --git a/cfme/tests/openstack/cloud/test_volume_backup.py b/cfme/tests/openstack/cloud/test_volume_backup.py
index 16690dcc43..2a25fbec58 100644
--- a/cfme/tests/openstack/cloud/test_volume_backup.py
+++ b/cfme/tests/openstack/cloud/test_volume_backup.py
@@ -20,7 +20,7 @@
@pytest.fixture(scope='function')
def volume_backup(appliance, provider):
volume_collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
backup_collection = appliance.collections.volume_backups.filter({'provider': provider})
# create new volume
@@ -60,7 +60,7 @@ def volume_type_is_displayed():
return volume_type.exists
volume_collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
backup_collection = appliance.collections.volume_backups.filter({'provider': provider})
# create new volume
@@ -193,7 +193,7 @@ def cleanup():
view = navigate_to(collection, "All")
view.flash.assert_success_message(
- 'Delete of Backup "{}" was successfully initiated.'.format(backup_name))
+ f'Delete of Backup "{backup_name}" was successfully initiated.')
wait_for(lambda: not incr_backup_of_attached_volume.exists, delay=5, timeout=600,
fail_func=incr_backup_of_attached_volume.refresh,
diff --git a/cfme/tests/openstack/cloud/test_volumes.py b/cfme/tests/openstack/cloud/test_volumes.py
index 94f7795650..172d0bebf4 100644
--- a/cfme/tests/openstack/cloud/test_volumes.py
+++ b/cfme/tests/openstack/cloud/test_volumes.py
@@ -21,7 +21,7 @@
@pytest.fixture(scope='function')
def volume(appliance, provider):
collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
volume = collection.create(name=fauxfactory.gen_alpha(start="vol_"),
storage_manager=storage_manager,
tenant=provider.data['provisioning']['cloud_tenant'],
@@ -49,7 +49,7 @@ def volume_type_is_displayed():
return volume_type.exists
collection = appliance.collections.volumes
- storage_manager = '{} Cinder Manager'.format(provider.name)
+ storage_manager = f'{provider.name} Cinder Manager'
volume = collection.create(name=fauxfactory.gen_alpha(start="vol_"),
storage_manager=storage_manager,
tenant=provider.data['provisioning']['cloud_tenant'],
@@ -84,7 +84,7 @@ def test_create_volume(volume, provider):
initialEstimate: 1/4h
"""
assert volume.exists
- assert volume.size == '{} GB'.format(VOLUME_SIZE)
+ assert volume.size == f'{VOLUME_SIZE} GB'
assert volume.tenant == provider.data['provisioning']['cloud_tenant']
@@ -124,7 +124,7 @@ def test_create_volume_with_type(volume_with_type, provider):
initialEstimate: 1/4h
"""
assert volume_with_type.exists
- assert volume_with_type.size == '{} GB'.format(VOLUME_SIZE)
+ assert volume_with_type.size == f'{VOLUME_SIZE} GB'
assert volume_with_type.tenant == provider.data['provisioning']['cloud_tenant']
diff --git a/cfme/tests/openstack/infrastructure/test_host_lifecycle.py b/cfme/tests/openstack/infrastructure/test_host_lifecycle.py
index 7307ee4c03..ff68c9fa42 100644
--- a/cfme/tests/openstack/infrastructure/test_host_lifecycle.py
+++ b/cfme/tests/openstack/infrastructure/test_host_lifecycle.py
@@ -55,7 +55,7 @@ def test_scale_provider_down(provider, host, has_mistral_service):
wait_for(
lambda: view.entities.summary('Properties').get_text_of('Maintenance Mode') ==
'Enabled', delay=15, timeout=300,
- message="Maintenance Mode of host {} becomes Enabled".format(host.name),
+ message=f"Maintenance Mode of host {host.name} becomes Enabled",
fail_func=host.browser.refresh)
assert view.entities.summary('Properties').get_text_of('Maintenance Mode') == 'Enabled'
provider.scale_down()
@@ -64,13 +64,13 @@ def test_scale_provider_down(provider, host, has_mistral_service):
host.name = host_uuid # host's name is changed after scale down
host.browser.refresh()
wait_for(lambda: host.exists, delay=15, timeout=600,
- message="Hostname changed to {} after scale down".format(host.name),
+ message=f"Hostname changed to {host.name} after scale down",
fail_func=provider.browser.refresh)
view = navigate_to(host, 'Details')
wait_for(
lambda: view.entities.summary('Openstack Hardware').get_text_of('Provisioning State') ==
'available', delay=15, timeout=600,
- message="Provisioning State of host {} is available".format(host.name),
+ message=f"Provisioning State of host {host.name} is available",
fail_func=host.browser.refresh)
prov_state = view.entities.summary('Openstack Hardware').get_text_of('Provisioning State')
assert prov_state == 'available'
@@ -122,7 +122,7 @@ def test_register_host(provider, host, has_mistral_service):
provider.browser.refresh()
wait_for(provider.is_refreshed, func_kwargs=dict(refresh_delta=10), timeout=600)
wait_for(lambda: host.exists, delay=15, timeout=600,
- message="Host {} become visible".format(host.name),
+ message=f"Host {host.name} become visible",
fail_func=host.browser.refresh)
assert host.exists
@@ -148,7 +148,7 @@ def test_introspect_host(host, provider, has_mistral_service):
wait_for(
lambda: view.entities.summary('Openstack Hardware').get_text_of('Introspected') ==
'true', delay=15, timeout=600, fail_func=host.browser.refresh,
- message="Introspected state of host {} is true".format(host.name))
+ message=f"Introspected state of host {host.name} is true")
assert view.entities.summary('Openstack Hardware').get_text_of('Introspected') == 'true'
diff --git a/cfme/tests/openstack/infrastructure/test_hosts.py b/cfme/tests/openstack/infrastructure/test_hosts.py
index c3580690c7..c58752fd80 100644
--- a/cfme/tests/openstack/infrastructure/test_hosts.py
+++ b/cfme/tests/openstack/infrastructure/test_hosts.py
@@ -30,13 +30,13 @@ def test_host_configuration(host_collection, provider, soft_assert, appliance):
for host in hosts:
host.run_smartstate_analysis()
task = appliance.collections.tasks.instantiate(
- name="SmartState Analysis for '{}'".format(host.name), tab='MyOtherTasks')
+ name=f"SmartState Analysis for '{host.name}'", tab='MyOtherTasks')
task.wait_for_finished()
fields = ['Packages', 'Services', 'Files']
view = navigate_to(host, 'Details')
for field in fields:
value = int(view.entities.summary('Configuration').get_text_of(field))
- soft_assert(value > 0, 'Nodes number of {} is 0'.format(field))
+ soft_assert(value > 0, f'Nodes number of {field} is 0')
@pytest.mark.regression
@@ -55,7 +55,7 @@ def test_host_cpu_resources(host_collection, provider, soft_assert):
view = navigate_to(host, 'Details')
for field in fields:
value = int(view.entities.summary('Properties').get_text_of(field))
- soft_assert(value > 0, "Aggregate Node {} is 0".format(field))
+ soft_assert(value > 0, f"Aggregate Node {field} is 0")
@pytest.mark.regression
@@ -73,7 +73,7 @@ def test_host_auth(host_collection, provider, soft_assert):
auth_status = view.entities.summary('Authentication Status').get_text_of(
'SSH Key Pair Credentials')
soft_assert(auth_status == 'Valid',
- 'Incorrect SSH authentication status {}'.format(auth_status))
+ f'Incorrect SSH authentication status {auth_status}')
@pytest.mark.regression
@@ -193,7 +193,7 @@ def test_hypervisor_hostname(host_collection, provider, soft_assert):
view = navigate_to(host, 'Details')
hv_name = view.entities.summary('Properties').get_text_of('Hypervisor Hostname')
soft_assert(hv_name in hvisors,
- "Hypervisor hostname {} is not in Hypervisor list".format(hv_name))
+ f"Hypervisor hostname {hv_name} is not in Hypervisor list")
@pytest.mark.rfe
@@ -212,7 +212,7 @@ def test_hypervisor_hostname_views(host_collection, provider, view_type, soft_as
for item in items:
hv_name = item.data['hypervisor_hostname']
soft_assert(hv_name in hvisors,
- "Hypervisor hostname {} is not in Hypervisor list".format(hv_name))
+ f"Hypervisor hostname {hv_name} is not in Hypervisor list")
@pytest.mark.rfe
diff --git a/cfme/tests/openstack/infrastructure/test_relationships.py b/cfme/tests/openstack/infrastructure/test_relationships.py
index 5483af4175..aa972a8e55 100644
--- a/cfme/tests/openstack/infrastructure/test_relationships.py
+++ b/cfme/tests/openstack/infrastructure/test_relationships.py
@@ -64,7 +64,7 @@ def test_templates(provider, soft_assert):
template_names = templates_view.entities.entity_names
for image in images:
- soft_assert(image in template_names, 'Missing template: {}'.format(image))
+ soft_assert(image in template_names, f'Missing template: {image}')
@pytest.mark.regression
diff --git a/cfme/tests/openstack/infrastructure/test_roles.py b/cfme/tests/openstack/infrastructure/test_roles.py
index a396a56a8c..81eda0ac40 100644
--- a/cfme/tests/openstack/infrastructure/test_roles.py
+++ b/cfme/tests/openstack/infrastructure/test_roles.py
@@ -40,7 +40,7 @@ def test_host_role_association(appliance, provider, soft_assert):
host.run_smartstate_analysis()
task = appliance.collections.tasks.instantiate(
- name="SmartState Analysis for '{}'".format(host.name), tab='MyOtherTasks')
+ name=f"SmartState Analysis for '{host.name}'", tab='MyOtherTasks')
task.wait_for_finished()
view = navigate_to(host, 'Details')
role_name = str(view.title.text.split()[1]).translate(None, '()')
diff --git a/cfme/tests/perf/workloads/test_capacity_and_utilization.py b/cfme/tests/perf/workloads/test_capacity_and_utilization.py
index b6cf33b9c5..72319b1518 100644
--- a/cfme/tests/perf/workloads/test_capacity_and_utilization.py
+++ b/cfme/tests/perf/workloads/test_capacity_and_utilization.py
@@ -52,7 +52,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, quantifiers, scenario_data))
monitor_thread.start()
diff --git a/cfme/tests/perf/workloads/test_capacity_and_utilization_replication.py b/cfme/tests/perf/workloads/test_capacity_and_utilization_replication.py
index cdcd3c9cc9..2f0e9aa8e4 100644
--- a/cfme/tests/perf/workloads/test_capacity_and_utilization_replication.py
+++ b/cfme/tests/perf/workloads/test_capacity_and_utilization_replication.py
@@ -52,9 +52,9 @@ def test_workload_capacity_and_utilization_rep(appliance, request, scenario, set
# under test is cleaned first, followed by master appliance
sshtail_evm = SSHTail('/var/www/miq/vmdb/log/evm.log')
sshtail_evm.set_initial_file_end()
- logger.info('Clean appliance under test ({})'.format(ssh_client))
+ logger.info(f'Clean appliance under test ({ssh_client})')
appliance.clean_appliance()
- logger.info('Clean master appliance ({})'.format(ssh_client_master))
+ logger.info(f'Clean master appliance ({ssh_client_master})')
master_appliance.clean_appliance() # Clean Replication master appliance
if is_pglogical:
@@ -84,7 +84,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, quantifiers, scenario_data))
monitor_thread.start()
diff --git a/cfme/tests/perf/workloads/test_idle.py b/cfme/tests/perf/workloads/test_idle.py
index 0b825aeb76..159e470c56 100644
--- a/cfme/tests/perf/workloads/test_idle.py
+++ b/cfme/tests/perf/workloads/test_idle.py
@@ -51,7 +51,7 @@ def cleanup_workload(from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(from_ts, quantifiers, scenario_data))
monitor_thread.start()
@@ -59,7 +59,7 @@ def cleanup_workload(from_ts, quantifiers, scenario_data):
appliance.wait_for_miq_server_workers_started(poll_interval=2)
appliance.update_server_roles({role: True for role in scenario['roles']})
s_time = scenario['total_time']
- logger.info('Idling appliance for {}s'.format(s_time))
+ logger.info(f'Idling appliance for {s_time}s')
time.sleep(s_time)
quantifiers['Elapsed_Time'] = s_time
diff --git a/cfme/tests/perf/workloads/test_memory_leak.py b/cfme/tests/perf/workloads/test_memory_leak.py
index e46a310d78..a98f92b625 100644
--- a/cfme/tests/perf/workloads/test_memory_leak.py
+++ b/cfme/tests/perf/workloads/test_memory_leak.py
@@ -85,7 +85,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, quantifiers, scenario_data))
monitor_thread.start()
diff --git a/cfme/tests/perf/workloads/test_provisioning.py b/cfme/tests/perf/workloads/test_provisioning.py
index 1fd35e1e19..d4237f5e58 100644
--- a/cfme/tests/perf/workloads/test_provisioning.py
+++ b/cfme/tests/perf/workloads/test_provisioning.py
@@ -36,7 +36,7 @@ def get_provision_data(rest_api, provider, template_name, auto_approve=True):
guid = template.guid
break
else:
- raise Exception("No such template {} on provider!".format(template_name))
+ raise Exception(f"No such template {template_name} on provider!")
result = {
"version": "1.1",
@@ -121,7 +121,7 @@ def cleanup_workload(scenario, from_ts, vms_to_cleanup, quantifiers, scenario_da
quantifiers['Leftover_VMs'] = vms_to_cleanup
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, vm_name, quantifiers,
scenario_data))
@@ -169,7 +169,7 @@ def cleanup_workload(scenario, from_ts, vms_to_cleanup, quantifiers, scenario_da
def _finished():
provision_request.reload()
if "error" in provision_request.status.lower():
- pytest.fail("Error when provisioning: `{}`".format(provision_request.message))
+ pytest.fail(f"Error when provisioning: `{provision_request.message}`")
return provision_request.request_state.lower() in ("finished", "provisioned")
wait_for(_finished, num_sec=800, delay=5, message="REST provisioning finishes")
@@ -177,8 +177,8 @@ def _finished():
vm = appliance.rest_api.collections.vms.get(name=vm_name)
creation_time = time.time()
provision_time = round(creation_time - start_iteration_time, 2)
- logger.debug('Time to initiate provisioning: {}'.format(provision_time))
- logger.info('{} VMs provisioned so far'.format(total_provisioned_vms))
+ logger.debug(f'Time to initiate provisioning: {provision_time}')
+ logger.info(f'{total_provisioned_vms} VMs provisioned so far')
if provisioned_vms > cleanup_size * len(scenario['providers']):
start_remove_time = time.time()
@@ -187,13 +187,13 @@ def _finished():
provisioned_vms -= 1
total_deleted_vms += 1
deletion_time = round(time.time() - start_remove_time, 2)
- logger.debug('Time to initate deleting: {}'.format(deletion_time))
- logger.info('{} VMs deleted so far'.format(total_deleted_vms))
+ logger.debug(f'Time to initate deleting: {deletion_time}')
+ logger.info(f'{total_deleted_vms} VMs deleted so far')
end_iteration_time = time.time()
iteration_time = round(end_iteration_time - start_iteration_time, 2)
elapsed_time = end_iteration_time - starttime
- logger.debug('Time to initiate provisioning and deletion: {}'.format(iteration_time))
+ logger.debug(f'Time to initiate provisioning and deletion: {iteration_time}')
logger.info('Time elapsed: {}/{}'.format(round(elapsed_time, 2), total_time))
if iteration_time < time_between_provision:
diff --git a/cfme/tests/perf/workloads/test_refresh_providers.py b/cfme/tests/perf/workloads/test_refresh_providers.py
index 5ab8bf2f6d..87ff03f843 100644
--- a/cfme/tests/perf/workloads/test_refresh_providers.py
+++ b/cfme/tests/perf/workloads/test_refresh_providers.py
@@ -54,7 +54,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts,
quantifiers, scenario_data))
@@ -81,7 +81,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
refresh_time = round(iteration_time - start_refresh_time, 2)
elapsed_time = iteration_time - starttime
- logger.debug('Time to Queue Refreshes: {}'.format(refresh_time))
+ logger.debug(f'Time to Queue Refreshes: {refresh_time}')
logger.info('Time elapsed: {}/{}'.format(round(elapsed_time, 2), total_time))
if refresh_time < time_between_refresh:
diff --git a/cfme/tests/perf/workloads/test_refresh_vms.py b/cfme/tests/perf/workloads/test_refresh_vms.py
index 0822e3352e..f83050973b 100644
--- a/cfme/tests/perf/workloads/test_refresh_vms.py
+++ b/cfme/tests/perf/workloads/test_refresh_vms.py
@@ -54,7 +54,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, quantifiers, scenario_data))
monitor_thread.start()
@@ -97,7 +97,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
refresh_time = round(iteration_time - start_refresh_time, 2)
elapsed_time = iteration_time - starttime
- logger.debug('Time to Queue VM Refreshes: {}'.format(refresh_time))
+ logger.debug(f'Time to Queue VM Refreshes: {refresh_time}')
logger.info('Time elapsed: {}/{}'.format(round(elapsed_time, 2), total_time))
if refresh_time < time_between_refresh:
diff --git a/cfme/tests/perf/workloads/test_smartstate_analysis.py b/cfme/tests/perf/workloads/test_smartstate_analysis.py
index 770906a59a..b2fef2abd1 100644
--- a/cfme/tests/perf/workloads/test_smartstate_analysis.py
+++ b/cfme/tests/perf/workloads/test_smartstate_analysis.py
@@ -61,7 +61,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
monitor_thread.join()
add_workload_quantifiers(quantifiers, scenario_data)
timediff = time.time() - starttime
- logger.info('Finished cleaning up monitoring thread in {}'.format(timediff))
+ logger.info(f'Finished cleaning up monitoring thread in {timediff}')
request.addfinalizer(lambda: cleanup_workload(scenario, from_ts, quantifiers, scenario_data))
monitor_thread.start()
@@ -99,7 +99,7 @@ def cleanup_workload(scenario, from_ts, quantifiers, scenario_data):
ssa_time = round(iteration_time - start_ssa_time, 2)
elapsed_time = iteration_time - starttime
- logger.debug('Time to Queue SmartState Analyses: {}'.format(ssa_time))
+ logger.debug(f'Time to Queue SmartState Analyses: {ssa_time}')
logger.info('Time elapsed: {}/{}'.format(round(elapsed_time, 2), total_time))
if ssa_time < time_between_analyses:
diff --git a/cfme/tests/physical_infrastructure/api/test_physical_server_inventory_api.py b/cfme/tests/physical_infrastructure/api/test_physical_server_inventory_api.py
index 78913a0d31..2515ccacbf 100644
--- a/cfme/tests/physical_infrastructure/api/test_physical_server_inventory_api.py
+++ b/cfme/tests/physical_infrastructure/api/test_physical_server_inventory_api.py
@@ -35,7 +35,7 @@ def test_get_hardware_attributes(appliance, physical_server, attribute):
casecomponent: Rest
initialEstimate: 1/4h
"""
- expanded_attribute = 'hardware.{}'.format(attribute)
+ expanded_attribute = f'hardware.{attribute}'
physical_server.reload(attributes=[expanded_attribute])
assert_response(appliance)
assert physical_server.hardware[attribute] is not None
diff --git a/cfme/tests/physical_infrastructure/api/test_physical_switch_inventory_api.py b/cfme/tests/physical_infrastructure/api/test_physical_switch_inventory_api.py
index 76c132687f..b9f2c8a26e 100644
--- a/cfme/tests/physical_infrastructure/api/test_physical_switch_inventory_api.py
+++ b/cfme/tests/physical_infrastructure/api/test_physical_switch_inventory_api.py
@@ -29,7 +29,7 @@ def test_get_hardware_attributes(appliance, physical_switch, attribute):
casecomponent: Rest
initialEstimate: 1/4h
"""
- expanded_attribute = 'hardware.{}'.format(attribute)
+ expanded_attribute = f'hardware.{attribute}'
physical_switch.reload(attributes=[expanded_attribute])
assert_response(appliance)
assert physical_switch.hardware[attribute] is not None
diff --git a/cfme/tests/physical_infrastructure/ui/test_physical_server_list_buttons.py b/cfme/tests/physical_infrastructure/ui/test_physical_server_list_buttons.py
index cfb3b2cd51..190260f889 100644
--- a/cfme/tests/physical_infrastructure/ui/test_physical_server_list_buttons.py
+++ b/cfme/tests/physical_infrastructure/ui/test_physical_server_list_buttons.py
@@ -82,7 +82,7 @@ def test_server_actions(physical_servers_collection, physical_servers, provider,
view = provider.create_view(PhysicalServersView)
last_part = 's' if len(physical_servers) > 1 else ''
- message = 'Requested Server {} for the selected server{}'.format(method, last_part)
+ message = f'Requested Server {method} for the selected server{last_part}'
physical_servers_collection.custom_button_action(button, item, physical_servers)
def assert_handler_displayed():
diff --git a/cfme/tests/pod/test_appliance_crud.py b/cfme/tests/pod/test_appliance_crud.py
index 0a9f7b35b6..cf8c00e6fc 100644
--- a/cfme/tests/pod/test_appliance_crud.py
+++ b/cfme/tests/pod/test_appliance_crud.py
@@ -102,7 +102,7 @@ def appliance_data(provider):
def read_host_file(appliance, path):
""" Read file on the host """
- out = appliance.ssh_client.run_command('cat {}'.format(path), ensure_host=True)
+ out = appliance.ssh_client.run_command(f'cat {path}', ensure_host=True)
if out.failed:
pytest.fail("Can't read host file")
@@ -136,7 +136,7 @@ def template_tags(template):
try:
return yaml.safe_load(template['custom_data'])['TAGS']
except (KeyError, AttributeError) as e:
- pytest.fail("Can't retrieve template tags: {}".format(e.message))
+ pytest.fail(f"Can't retrieve template tags: {e.message}")
@pytest.fixture
@@ -171,7 +171,7 @@ def create_external_database(appliance):
ip=db_host,
name=db_name,
user=user))
- assert result.success, "DB failed creation: {}".format(result.output)
+ assert result.success, f"DB failed creation: {result.output}"
yield (db_host, db_name)
result = appliance.ssh_client.run_command(('env PGPASSWORD={pwd} psql -t -q -d '
'vmdb_production -h {ip} -U {user} -c '
@@ -179,7 +179,7 @@ def create_external_database(appliance):
ip=db_host,
name=db_name,
user=user))
- assert result.success, "DB drop failed: {}".format(result.output)
+ assert result.success, f"DB drop failed: {result.output}"
@pytest.fixture
@@ -277,7 +277,7 @@ def temp_pod_ansible_appliance(provider, appliance_data, template_tags):
memcached_tag=tags['cfme-openshift-memcached']['tag'],
db_url=tags['cfme-openshift-postgresql']['url'],
db_tag=tags['cfme-openshift-postgresql']['tag'])
- logger.info("ansible config file:\n {conf}".format(conf=fulfilled_config))
+ logger.info(f"ansible config file:\n {fulfilled_config}")
with tempfile.NamedTemporaryFile('w') as f:
f.write(fulfilled_config)
f.flush()
@@ -290,8 +290,8 @@ def temp_pod_ansible_appliance(provider, appliance_data, template_tags):
'/usr/share/ansible/openshift-ansible/playbooks/'
'openshift-management/config.yml').format(inventory_file=remote_file)
cmd_result = ssh_client.run_command(ansible_cmd, ensure_host=True)
- logger.info("deployment result: {result}".format(result=cmd_result.output))
- ssh_client.run_command('rm -f {f}'.format(f=remote_file))
+ logger.info(f"deployment result: {cmd_result.output}")
+ ssh_client.run_command(f'rm -f {remote_file}')
assert cmd_result.success
# retrieve data of created appliance
@@ -364,7 +364,7 @@ def new_ssa_image(temp_pod_appliance, template_folder, aws_provider):
# tag image
registry_host = registry_data['registry'].split('://')[-1]
- dst_url = "{}/{}".format(registry_host, SSA_IMAGE_STREAM)
+ dst_url = f"{registry_host}/{SSA_IMAGE_STREAM}"
result = docker_client.tag(image=image_url,
repository=dst_url,
tag=ss_image_version)
@@ -766,13 +766,13 @@ def test_pod_appliance_basic_ipa_auth(temp_pod_appliance, provider, setup_provid
output_file = '/tmp/ipa_configmap'
generator_cmd = ['/usr/bin/bash -c',
'"httpd_configmap_generator', 'ipa',
- '--host={}'.format(appliance.hostname),
- '--ipa-server={}'.format(auth_prov.host1),
- '--ipa-domain={}'.format(auth_prov.iparealm), # looks like yaml value is wrong
- '--ipa-realm={}'.format(auth_prov.iparealm),
- '--ipa-principal={}'.format(auth_prov.ipaprincipal),
- '--ipa-password={}'.format(auth_prov.bind_password),
- '--output={}'.format(output_file), '-d', '-f"']
+ f'--host={appliance.hostname}',
+ f'--ipa-server={auth_prov.host1}',
+ f'--ipa-domain={auth_prov.iparealm}', # looks like yaml value is wrong
+ f'--ipa-realm={auth_prov.iparealm}',
+ f'--ipa-principal={auth_prov.ipaprincipal}',
+ f'--ipa-password={auth_prov.bind_password}',
+ f'--output={output_file}', '-d', '-f"']
# todo: implement this in wrapanapi by resolving chain dc->rc->po/st
def get_pod_name(pattern):
@@ -791,14 +791,14 @@ def func(name):
logger.info("generator pod name: {}", generator_pod_name)
# workaround generator pod becomes ready but cannot property run commands for some time
sleep(60)
- logger.info(appliance.ssh_client.run_command('oc get pods -n {}'.format(appliance.project),
+ logger.info(appliance.ssh_client.run_command(f'oc get pods -n {appliance.project}',
ensure_host=True))
generator_output = str(appliance.ssh_client.run_command(
'oc exec {pod} -n {ns} -- {cmd}'.format(pod=generator_pod_name, ns=appliance.project,
cmd=" ".join(generator_cmd)),
ensure_host=True))
- assert_output = "config map generation failed because of {}".format(generator_output)
+ assert_output = f"config map generation failed because of {generator_output}"
assert 'Saving Auth Config-Map to' in generator_output, assert_output
httpd_config = provider.mgmt.run_command(namespace=appliance.project,
diff --git a/cfme/tests/services/test_ansible_workflow_servicecatalogs.py b/cfme/tests/services/test_ansible_workflow_servicecatalogs.py
index 73caf7227c..42bebd04bf 100644
--- a/cfme/tests/services/test_ansible_workflow_servicecatalogs.py
+++ b/cfme/tests/services/test_ansible_workflow_servicecatalogs.py
@@ -25,7 +25,7 @@ def ansible_workflow_catitem(appliance, provider, dialog, catalog, workflow_type
try:
template = config_manager_obj.data['provisioning_data'][workflow_type]
except KeyError:
- pytest.skip("No such Ansible template: {} found in cfme_data.yaml".format(workflow_type))
+ pytest.skip(f"No such Ansible template: {workflow_type} found in cfme_data.yaml")
catalog_item = appliance.collections.catalog_items.create(
appliance.collections.catalog_items.ANSIBLE_TOWER,
name=dialog.label,
@@ -33,7 +33,7 @@ def ansible_workflow_catitem(appliance, provider, dialog, catalog, workflow_type
display_in=True,
catalog=catalog,
dialog=dialog,
- provider='{} Automation Manager'.format(provider_name),
+ provider=f'{provider_name} Automation Manager',
config_template=template)
yield catalog_item
catalog_item.delete_if_exists()
@@ -61,7 +61,7 @@ def test_tower_workflow_item(appliance, ansible_workflow_catitem, workflow_type,
cells = {'Description': ansible_workflow_catitem.name}
order_request = appliance.collections.requests.instantiate(cells=cells, partial_check=True)
order_request.wait_for_request(method='ui')
- msg = 'Request failed with the message {}'.format(order_request.row.last_message.text)
+ msg = f'Request failed with the message {order_request.row.last_message.text}'
assert order_request.is_succeeded(method='ui'), msg
appliance.user.my_settings.default_views.set_default_view(
'Configuration Management Providers',
@@ -89,7 +89,7 @@ def test_retire_ansible_workflow(appliance, ansible_workflow_catitem, workflow_t
cells = {'Description': ansible_workflow_catitem.name}
order_request = appliance.collections.requests.instantiate(cells=cells, partial_check=True)
order_request.wait_for_request(method='ui')
- msg = "Request failed with the message {}".format(order_request.row.last_message.text)
+ msg = f"Request failed with the message {order_request.row.last_message.text}"
assert order_request.is_succeeded(method='ui'), msg
myservice = MyService(appliance, ansible_workflow_catitem.name)
myservice.retire()
diff --git a/cfme/tests/services/test_catalog_item.py b/cfme/tests/services/test_catalog_item.py
index c5a9465f51..a62dbffed1 100644
--- a/cfme/tests/services/test_catalog_item.py
+++ b/cfme/tests/services/test_catalog_item.py
@@ -182,7 +182,7 @@ def test_catalog_item_duplicate_name(appliance, dialog, catalog):
dialog=dialog
)
view = cat_item.create_view(AllCatalogItemView, wait='10s')
- view.flash.assert_success_message('Service Catalog Item "{}" was added'.format(cat_item.name))
+ view.flash.assert_success_message(f'Service Catalog Item "{cat_item.name}" was added')
with pytest.raises(AssertionError):
appliance.collections.catalog_items.create(
appliance.collections.catalog_items.GENERIC,
diff --git a/cfme/tests/services/test_cloud_service_catalogs.py b/cfme/tests/services/test_cloud_service_catalogs.py
index 2def8ee29b..3f1f617365 100644
--- a/cfme/tests/services/test_cloud_service_catalogs.py
+++ b/cfme/tests/services/test_cloud_service_catalogs.py
@@ -44,7 +44,7 @@ def test_cloud_catalog_item(appliance, vm_name, setup_provider, provider, dialog
initialEstimate: 1/4h
"""
wait_for(provider.is_refreshed, func_kwargs=dict(refresh_delta=10), timeout=600)
- vm = appliance.collections.cloud_instances.instantiate("{}0001".format(vm_name), provider)
+ vm = appliance.collections.cloud_instances.instantiate(f"{vm_name}0001", provider)
request.addfinalizer(lambda: vm.cleanup_on_provider())
image = provisioning['image']['name']
@@ -96,5 +96,5 @@ def test_cloud_catalog_item(appliance, vm_name, setup_provider, provider, dialog
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request()
- msg = "Request failed with the message {}".format(provision_request.rest.message)
+ msg = f"Request failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
diff --git a/cfme/tests/services/test_config_provider_servicecatalogs.py b/cfme/tests/services/test_config_provider_servicecatalogs.py
index 1114d958ca..7029bbde55 100644
--- a/cfme/tests/services/test_config_provider_servicecatalogs.py
+++ b/cfme/tests/services/test_config_provider_servicecatalogs.py
@@ -30,7 +30,7 @@ def catalog_item(appliance, request, provider, ansible_tower_dialog, catalog, jo
display_in=True,
catalog=catalog,
dialog=ansible_tower_dialog,
- provider='{} Automation Manager'.format(provider_name),
+ provider=f'{provider_name} Automation Manager',
config_template=template)
request.addfinalizer(catalog_item.delete)
return catalog_item
@@ -70,7 +70,7 @@ def test_order_tower_catalog_item(appliance, provider, catalog_item, request, jo
cells = {'Description': catalog_item.name}
order_request = appliance.collections.requests.instantiate(cells=cells, partial_check=True)
order_request.wait_for_request(method='ui')
- msg = 'Request failed with the message {}'.format(order_request.row.last_message.text)
+ msg = f'Request failed with the message {order_request.row.last_message.text}'
assert order_request.is_succeeded(method='ui'), msg
appliance.user.my_settings.default_views.set_default_view('Configuration Management Providers',
'List View')
@@ -95,7 +95,7 @@ def test_retire_ansible_service(appliance, catalog_item, request, job_type,
cells = {'Description': catalog_item.name}
order_request = appliance.collections.requests.instantiate(cells=cells, partial_check=True)
order_request.wait_for_request(method='ui')
- msg = "Request failed with the message {}".format(order_request.row.last_message.text)
+ msg = f"Request failed with the message {order_request.row.last_message.text}"
assert order_request.is_succeeded(method='ui'), msg
myservice = MyService(appliance, catalog_item.name)
myservice.retire()
diff --git a/cfme/tests/services/test_generic_service_catalogs.py b/cfme/tests/services/test_generic_service_catalogs.py
index 54544e1943..d3fec4e593 100644
--- a/cfme/tests/services/test_generic_service_catalogs.py
+++ b/cfme/tests/services/test_generic_service_catalogs.py
@@ -87,7 +87,7 @@ def test_service_generic_catalog_bundle(appliance, catalog_item):
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request()
- msg = "Request failed with the message {}".format(provision_request.rest.message)
+ msg = f"Request failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
@@ -108,7 +108,7 @@ def test_delete_dialog_before_parent_item(appliance, catalog_item):
dialog.delete()
-class TestServiceCatalogViaREST(object):
+class TestServiceCatalogViaREST:
@pytest.fixture(scope="function")
def service_catalogs(self, request, appliance):
return _service_catalogs(request, appliance)
diff --git a/cfme/tests/services/test_iso_service_catalogs.py b/cfme/tests/services/test_iso_service_catalogs.py
index efa8858c45..f638aa0e97 100644
--- a/cfme/tests/services/test_iso_service_catalogs.py
+++ b/cfme/tests/services/test_iso_service_catalogs.py
@@ -110,7 +110,7 @@ def test_rhev_iso_servicecatalog(appliance, provider, setup_provider, setup_iso_
vm_name = catalog_item.prov_data['catalog']["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
@@ -120,5 +120,5 @@ def test_rhev_iso_servicecatalog(appliance, provider, setup_provider, setup_iso_
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request()
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
diff --git a/cfme/tests/services/test_myservice.py b/cfme/tests/services/test_myservice.py
index fd3222d981..c6dd1809ce 100644
--- a/cfme/tests/services/test_myservice.py
+++ b/cfme/tests/services/test_myservice.py
@@ -417,7 +417,7 @@ def test_retire_service_bundle_and_vms(appliance, provider, catalog_item, reques
"""
collection = provider.appliance.provider_based_collection(provider)
vm_name = "{}0001".format(catalog_item.prov_data["catalog"]["vm_name"])
- vm = collection.instantiate("{}".format(vm_name), provider)
+ vm = collection.instantiate(f"{vm_name}", provider)
bundle_name = fauxfactory.gen_alphanumeric(12, start="bundle_")
catalog_bundle = appliance.collections.catalog_bundles.create(
diff --git a/cfme/tests/services/test_operations.py b/cfme/tests/services/test_operations.py
index 51afb355a9..0f8dda9d22 100644
--- a/cfme/tests/services/test_operations.py
+++ b/cfme/tests/services/test_operations.py
@@ -48,7 +48,7 @@ def generated_request(appliance, provider, provisioning, template_name, vm_name)
first_name = fauxfactory.gen_alphanumeric()
last_name = fauxfactory.gen_alphanumeric()
notes = fauxfactory.gen_alphanumeric()
- e_mail = "{}@{}.test".format(first_name, last_name)
+ e_mail = f"{first_name}@{last_name}.test"
host, datastore = list(map(provisioning.get, ('host', 'datastore')))
vm = appliance.collections.infra_vms.instantiate(name=vm_name,
provider=provider,
@@ -83,7 +83,7 @@ def generated_request(appliance, provider, provisioning, template_name, vm_name)
view.form.fill_with(provisioning_data, on_change=view.form.submit_button)
request_cells = {
- "Description": "Provision from [{}] to [{}###]".format(template_name, vm_name),
+ "Description": f"Provision from [{template_name}] to [{vm_name}###]",
}
provision_request = appliance.collections.requests.instantiate(cells=request_cells)
yield provision_request
@@ -126,7 +126,7 @@ def test_copy_request(request, generated_request, vm_name, template_name):
initialEstimate: 1/4h
casecomponent: Services
"""
- new_vm_name = '{}-xx'.format(vm_name)
+ new_vm_name = f'{vm_name}-xx'
modifications = {'catalog': {'vm_name': new_vm_name}}
new_request = generated_request.copy_request(values=modifications)
request.addfinalizer(new_request.remove_request)
diff --git a/cfme/tests/services/test_orchestration_template.py b/cfme/tests/services/test_orchestration_template.py
index fe09731b41..083ba535ea 100644
--- a/cfme/tests/services/test_orchestration_template.py
+++ b/cfme/tests/services/test_orchestration_template.py
@@ -107,7 +107,7 @@ def test_copy_template(created_template):
"""
copied_method = METHOD_TORSO_copied.replace('CloudFormation', fauxfactory.gen_alphanumeric())
template = created_template
- template_copy = template.copy_template("{}_copied".format(template.template_name),
+ template_copy = template.copy_template(f"{template.template_name}_copied",
copied_method)
assert template_copy.exists
template_copy.delete()
@@ -202,7 +202,7 @@ def test_duplicated_content_error_validation(appliance, created_template, templa
"""
collection = appliance.collections.orchestration_templates
if action == "copy":
- copy_name = "{}_copied".format(created_template.template_name)
+ copy_name = f"{created_template.template_name}_copied"
flash_msg = ("Unable to create a new template copy \"{}\": old and new template content "
"have to differ.".format(copy_name))
with pytest.raises(AssertionError, match=flash_msg):
diff --git a/cfme/tests/services/test_provision_stack.py b/cfme/tests/services/test_provision_stack.py
index 54587d9b4b..e1dbb585f1 100644
--- a/cfme/tests/services/test_provision_stack.py
+++ b/cfme/tests/services/test_provision_stack.py
@@ -45,8 +45,8 @@
@pytest.fixture
def stack_data(appliance, provider, provisioning, request):
random_base = fauxfactory.gen_alphanumeric()
- stackname = 'test{}'.format(random_base)
- vm_name = 'test-{}'.format(random_base)
+ stackname = f'test{random_base}'
+ vm_name = f'test-{random_base}'
stack_timeout = '20'
if provider.one_of(AzureProvider):
try:
@@ -54,7 +54,7 @@ def stack_data(appliance, provider, provisioning, request):
vm_user = credentials[template.creds].username
vm_password = credentials[template.creds].password
except AttributeError:
- pytest.skip('Could not find small_template or credentials for {}'.format(provider.name))
+ pytest.skip(f'Could not find small_template or credentials for {provider.name}')
stack_data = {
'stack_name': stackname,
diff --git a/cfme/tests/services/test_pxe_service_catalogs.py b/cfme/tests/services/test_pxe_service_catalogs.py
index b2f905a1e6..91c9da5134 100644
--- a/cfme/tests/services/test_pxe_service_catalogs.py
+++ b/cfme/tests/services/test_pxe_service_catalogs.py
@@ -134,7 +134,7 @@ def test_pxe_servicecatalog(appliance, setup_provider, provider, catalog_item, r
vm_name = catalog_item.prov_data['catalog']["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
@@ -144,5 +144,5 @@ def test_pxe_servicecatalog(appliance, setup_provider, provider, catalog_item, r
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request(num_sec=3600)
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
diff --git a/cfme/tests/services/test_request.py b/cfme/tests/services/test_request.py
index 3ad2752125..d7152b7de3 100644
--- a/cfme/tests/services/test_request.py
+++ b/cfme/tests/services/test_request.py
@@ -28,7 +28,7 @@ def test_copy_request_bz1194479(appliance, provider, catalog_item, request):
vm_name = catalog_item.prov_data["catalog"]["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
diff --git a/cfme/tests/services/test_rest_services.py b/cfme/tests/services/test_rest_services.py
index d6fd8614b3..51ef78be67 100644
--- a/cfme/tests/services/test_rest_services.py
+++ b/cfme/tests/services/test_rest_services.py
@@ -82,8 +82,8 @@ def is_retired(entity):
def service_body(**kwargs):
uid = fauxfactory.gen_alphanumeric(5)
body = {
- 'name': 'test_rest_service_{}'.format(uid),
- 'description': 'Test REST Service {}'.format(uid),
+ 'name': f'test_rest_service_{uid}',
+ 'description': f'Test REST Service {uid}',
}
body.update(kwargs)
return body
@@ -118,10 +118,10 @@ def catalog_bundle(request, dialog, service_catalog_obj, appliance, provider):
num=NUM_BUNDLE_ITEMS)
uid = fauxfactory.gen_alphanumeric()
- bundle_name = 'test_rest_bundle_{}'.format(uid)
+ bundle_name = f'test_rest_bundle_{uid}'
bundle = appliance.collections.catalog_bundles.create(
bundle_name,
- description='Test REST Bundle {}'.format(uid),
+ description=f'Test REST Bundle {uid}',
display_in=True,
catalog=service_catalog_obj,
dialog=dialog,
@@ -236,7 +236,7 @@ def unassign_templates(templates):
template.reload()
-class TestServiceRESTAPI(object):
+class TestServiceRESTAPI:
def test_query_service_attributes(self, services, soft_assert):
"""Tests access to service attributes.
@@ -253,7 +253,7 @@ def test_query_service_attributes(self, services, soft_assert):
for failure in outcome.failed:
if failure.name == "reconfigure_dialog"and BZ(1663972).blocks:
continue
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
def test_edit_service(self, appliance, services):
@@ -692,7 +692,7 @@ def test_delete_parent_service(self, appliance):
parent = collection.action.create(service_body(parent_service={'id': grandparent.id}))[0]
child = collection.action.create(service_body(parent_service={'id': parent.id}))[0]
assert parent.ancestry == str(grandparent.id)
- assert child.ancestry == '{}/{}'.format(grandparent.id, parent.id)
+ assert child.ancestry == f'{grandparent.id}/{parent.id}'
grandparent.action.delete()
assert_response(appliance)
wait_for(
@@ -809,7 +809,7 @@ def test_retire_parent_service_now(self, request, appliance):
@test_requirements.rest
-class TestServiceDialogsRESTAPI(object):
+class TestServiceDialogsRESTAPI:
def check_returned_dialog(self, appliance):
returned = appliance.rest_api.response.json()
if 'results' in returned:
@@ -930,7 +930,7 @@ def test_delete_service_dialogs(self, service_dialogs):
delete_resources_from_collection(service_dialogs)
-class TestServiceTemplateRESTAPI(object):
+class TestServiceTemplateRESTAPI:
def test_query_service_templates_attributes(self, service_templates, soft_assert):
"""Tests access to service template attributes.
@@ -1110,7 +1110,7 @@ def test_edit_multiple_service_templates(self, appliance, service_templates):
assert service_template.name == new_names[i]
-class TestServiceCatalogsRESTAPI(object):
+class TestServiceCatalogsRESTAPI:
def test_query_service_catalog_attributes(self, service_catalogs, soft_assert):
"""Tests access to service catalog attributes.
@@ -1125,7 +1125,7 @@ def test_query_service_catalog_attributes(self, service_catalogs, soft_assert):
"""
outcome = query_resource_attributes(service_catalogs[0])
for failure in outcome.failed:
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
@pytest.mark.parametrize('from_detail', [True, False], ids=['from_detail', 'from_collection'])
@@ -1212,7 +1212,7 @@ def _order_finished():
wait_for(_order_finished, num_sec=180, delay=10)
service_name = get_dialog_service_name(appliance, service_request, template.name)
- assert '[{}]'.format(service_name) in service_request.message
+ assert f'[{service_name}]' in service_request.message
source_id = str(service_request.source_id)
new_service = appliance.rest_api.collections.services.get(service_template_id=source_id)
assert new_service.name == service_name
@@ -1267,7 +1267,7 @@ def _order_finished(service_request):
service_request,
*[t.name for t in catalog.service_templates.all]
)
- assert '[{}]'.format(service_name) in service_request.message
+ assert f'[{service_name}]' in service_request.message
# Service name can no longer be used to uniquely identify service when multiple
# services are using the same dialog (all services have the same name).
@@ -1310,7 +1310,7 @@ def _order_finished():
wait_for(_order_finished, num_sec=2000, delay=10)
service_name = get_dialog_service_name(appliance, service_request, catalog_bundle.name)
- assert '[{}]'.format(service_name) in service_request.message
+ assert f'[{service_name}]' in service_request.message
source_id = str(service_request.source_id)
new_service = appliance.rest_api.collections.services.get(service_template_id=source_id)
assert new_service.name == service_name
@@ -1355,7 +1355,7 @@ def test_delete_catalog_from_collection(self, service_catalogs):
delete_resources_from_collection(service_catalogs, num_sec=300, delay=5)
-class TestPendingRequestsRESTAPI(object):
+class TestPendingRequestsRESTAPI:
def _get_instance(self, miq_domain):
auto_class = (miq_domain
.namespaces.instantiate(name='Service')
@@ -1516,7 +1516,7 @@ def _order_approved():
source_id = str(pending_request.source_id)
new_service = appliance.rest_api.collections.services.get(service_template_id=source_id)
- assert '[{}]'.format(new_service.name) in pending_request.message
+ assert f'[{new_service.name}]' in pending_request.message
request.addfinalizer(new_service.action.delete)
@@ -1545,7 +1545,7 @@ def _order_denied():
wait_for(_order_denied, num_sec=30, delay=2)
-class TestServiceRequests(object):
+class TestServiceRequests:
@pytest.fixture(scope='class')
def new_role(self, appliance):
role = copy_role(appliance, 'EvmRole-user_self_service')
@@ -1596,7 +1596,7 @@ def test_user_item_order(self, appliance, request, user_api):
catalog = user_api.get_entity('service_catalogs', catalog_id)
templates_collection = catalog.service_templates
- template_href = '{}/service_templates/{}'.format(catalog.href, template_id)
+ template_href = f'{catalog.href}/service_templates/{template_id}'
# The "order" action doesn't return resource in the "service_requests" collection
# using workaround with `response.json()`
@@ -1616,14 +1616,14 @@ def _order_finished():
wait_for(_order_finished, num_sec=180, delay=10)
service_name = get_dialog_service_name(appliance, service_request, new_template.name)
- assert '[{}]'.format(service_name) in service_request.message
+ assert f'[{service_name}]' in service_request.message
source_id = str(service_request.source_id)
new_service = appliance.rest_api.collections.services.get(service_template_id=source_id)
assert new_service.name == service_name
request.addfinalizer(new_service.action.delete)
-class TestOrchestrationTemplatesRESTAPI(object):
+class TestOrchestrationTemplatesRESTAPI:
@pytest.fixture(scope='function')
def orchestration_templates(self, request, appliance):
num = 2
@@ -1768,8 +1768,8 @@ def test_copy_orchestration_templates(self, request, appliance, orchestration_te
for _ in range(num_orch_templates):
uniq = fauxfactory.gen_alphanumeric(5)
new.append({
- "name": "test_copied_{}".format(uniq),
- "content": "{{ 'Description' : '{}' }}\n".format(uniq)
+ "name": f"test_copied_{uniq}",
+ "content": f"{{ 'Description' : '{uniq}' }}\n"
})
if from_detail:
copied = []
@@ -1845,8 +1845,8 @@ def test_invalid_template_type(self, appliance):
"""
uniq = fauxfactory.gen_alphanumeric(5)
payload = {
- 'name': 'test_{}'.format(uniq),
- 'description': 'Test Template {}'.format(uniq),
+ 'name': f'test_{uniq}',
+ 'description': f'Test Template {uniq}',
'type': 'InvalidOrchestrationTemplateType',
'orderable': False,
'draft': False,
@@ -1857,7 +1857,7 @@ def test_invalid_template_type(self, appliance):
assert_response(appliance, http_status=400)
-class TestServiceOrderCart(object):
+class TestServiceOrderCart:
@pytest.fixture(scope="class")
def service_templates_class(self, request, appliance):
return service_templates(request, appliance)
@@ -1898,7 +1898,7 @@ def test_create_empty_cart(self, appliance, cart):
tags: service
"""
assert cart.state == 'cart'
- cart_dict = appliance.rest_api.get('{}/cart'.format(cart.collection._href))
+ cart_dict = appliance.rest_api.get(f'{cart.collection._href}/cart')
assert cart_dict['id'] == cart.id
@pytest.mark.tier(3)
@@ -1949,7 +1949,7 @@ def delete_cart():
cart.action.delete()
assert_response(appliance)
- cart_dict = appliance.rest_api.get('{}/cart'.format(href))
+ cart_dict = appliance.rest_api.get(f'{href}/cart')
assert response['id'] == cart_dict['id']
@pytest.mark.tier(3)
@@ -2098,7 +2098,7 @@ def _order_finished():
sr,
*[t.name for t in selected_templates]
)
- assert '[{}]'.format(service_name) in sr.message
+ assert f'[{service_name}]' in sr.message
service_description = selected_templates[index].description
new_service = appliance.rest_api.collections.services.get(
description=service_description)
@@ -2107,7 +2107,7 @@ def _order_finished():
# when cart is ordered, it can not longer be accessed using /api/service_orders/cart
with pytest.raises(Exception, match='ActiveRecord::RecordNotFound'):
- appliance.rest_api.get('{}/cart'.format(cart.collection._href))
+ appliance.rest_api.get(f'{cart.collection._href}/cart')
@pytest.mark.tier(3)
@pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE'])
diff --git a/cfme/tests/services/test_service_catalogs.py b/cfme/tests/services/test_service_catalogs.py
index 2295e1a7b6..61bf8b7fd2 100644
--- a/cfme/tests/services/test_service_catalogs.py
+++ b/cfme/tests/services/test_service_catalogs.py
@@ -44,7 +44,7 @@ def test_order_catalog_item(appliance, provider, catalog_item, request,
vm_name = catalog_item.prov_data['catalog']["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
register_event(target_type='Service', target_name=catalog_item.name,
@@ -52,12 +52,12 @@ def test_order_catalog_item(appliance, provider, catalog_item, request,
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
- logger.info("Waiting for cfme provision request for service {}".format(catalog_item.name))
+ logger.info(f"Waiting for cfme provision request for service {catalog_item.name}")
request_description = catalog_item.name
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request()
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
@@ -117,7 +117,7 @@ def test_order_catalog_bundle(appliance, provider, catalog_item, request):
vm_name = catalog_item.prov_data['catalog']["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
bundle_name = fauxfactory.gen_alphanumeric(12, start="bundle_")
catalog_bundle = appliance.collections.catalog_bundles.create(
@@ -126,12 +126,12 @@ def test_order_catalog_bundle(appliance, provider, catalog_item, request):
dialog=catalog_item.dialog, catalog_items=[catalog_item.name])
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_bundle.name)
service_catalogs.order()
- logger.info("Waiting for cfme provision request for service {}".format(bundle_name))
+ logger.info(f"Waiting for cfme provision request for service {bundle_name}")
request_description = bundle_name
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
provision_request.wait_for_request()
- msg = "Provisioning failed with the message {}".format(provision_request.rest.message)
+ msg = f"Provisioning failed with the message {provision_request.rest.message}"
assert provision_request.is_succeeded(), msg
@@ -175,7 +175,7 @@ def test_request_with_orphaned_template(appliance, provider, catalog_item):
"""
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
- logger.info("Waiting for cfme provision request for service {}".format(catalog_item.name))
+ logger.info(f"Waiting for cfme provision request for service {catalog_item.name}")
request_description = catalog_item.name
provision_request = appliance.collections.requests.instantiate(request_description,
partial_check=True)
diff --git a/cfme/tests/services/test_service_customer_bz.py b/cfme/tests/services/test_service_customer_bz.py
index 0da4c3c59e..3cacafb968 100644
--- a/cfme/tests/services/test_service_customer_bz.py
+++ b/cfme/tests/services/test_service_customer_bz.py
@@ -56,7 +56,7 @@ def test_edit_bundle_entry_point(appliance, provider, catalog_item, request):
vm_name = catalog_item.prov_data['catalog']["vm_name"]
request.addfinalizer(
lambda: appliance.collections.infra_vms.instantiate(
- "{}0001".format(vm_name), provider).cleanup_on_provider()
+ f"{vm_name}0001", provider).cleanup_on_provider()
)
bundle_name = fauxfactory.gen_alphanumeric(12, start="bundle_")
catalog_bundle = appliance.collections.catalog_bundles.create(
diff --git a/cfme/tests/services/test_service_manual_approval.py b/cfme/tests/services/test_service_manual_approval.py
index f0e17cba40..7d0cacbcc4 100644
--- a/cfme/tests/services/test_service_manual_approval.py
+++ b/cfme/tests/services/test_service_manual_approval.py
@@ -106,7 +106,7 @@ def test_service_manual_approval(appliance, provider, modify_instance,
service_catalogs = ServiceCatalogs(appliance, catalog_item.catalog, catalog_item.name)
service_catalogs.order()
- logger.info("Waiting for cfme provision request for service {}".format(catalog_item.name))
+ logger.info(f"Waiting for cfme provision request for service {catalog_item.name}")
request_description = catalog_item.name
service_request = appliance.collections.requests.instantiate(description=request_description,
partial_check=True)
@@ -162,6 +162,6 @@ def test_service_retire_manual_approval(request, appliance, service_retirement_r
service_request.approve_request(method='ui', reason="Approved")
assert service_request.row.approval_state.text == 'Approved'
service_request.wait_for_request()
- msg = "Request failed with the message {}".format(service_request.rest.message)
+ msg = f"Request failed with the message {service_request.rest.message}"
request.addfinalizer(service_request.remove_request)
assert service_request.is_succeeded(), msg
diff --git a/cfme/tests/ssui/test_ssui_dashboard.py b/cfme/tests/ssui/test_ssui_dashboard.py
index 7b2f5fb9c8..741b81dd11 100644
--- a/cfme/tests/ssui/test_ssui_dashboard.py
+++ b/cfme/tests/ssui/test_ssui_dashboard.py
@@ -67,7 +67,7 @@ def new_compute_rate(appliance, enable_candu):
}
)
except Exception as ex:
- pytest.fail('Exception during chargeback creation for test setup: {}'.format(ex.message))
+ pytest.fail(f'Exception during chargeback creation for test setup: {ex.message}')
yield desc
@@ -149,7 +149,7 @@ def verify_records_rollups_table(appliance, provider):
result = appliance.ssh_client.run_rails_command(
'Service.queue_chargeback_reports')
- assert result.success, "Failed to run Service Chargeback report".format(result.output)
+ assert result.success, f"Failed to run Service Chargeback report"
@pytest.mark.rhel_testing
@@ -232,7 +232,7 @@ def test_monthly_charges(appliance, has_no_providers_modscope, setup_provider, c
with appliance.context.use(context):
dashboard = Dashboard(appliance)
monthly_charges = dashboard.monthly_charges()
- logger.info('Monthly charges is {}'.format(monthly_charges))
+ logger.info(f'Monthly charges is {monthly_charges}')
assert monthly_charges != '$0'
diff --git a/cfme/tests/ssui/test_ssui_myservice.py b/cfme/tests/ssui/test_ssui_myservice.py
index ceb5b430ce..56a9eec143 100644
--- a/cfme/tests/ssui/test_ssui_myservice.py
+++ b/cfme/tests/ssui/test_ssui_myservice.py
@@ -54,7 +54,7 @@ def test_myservice_crud(appliance, setup_provider, context, order_service):
with appliance.context.use(context):
my_service = MyService(appliance, catalog_item.name)
my_service.set_ownership("Administrator", "EvmGroup-approver")
- my_service.update({'description': '{}_edited'.format(catalog_item.name)})
+ my_service.update({'description': f'{catalog_item.name}_edited'})
my_service.edit_tags("Cost Center", "Cost Center 002")
my_service.delete()
diff --git a/cfme/tests/storage/test_manager.py b/cfme/tests/storage/test_manager.py
index 1b2052e693..6424858309 100644
--- a/cfme/tests/storage/test_manager.py
+++ b/cfme/tests/storage/test_manager.py
@@ -132,7 +132,7 @@ def test_storage_manager_navigation_from_cloudprovider(manager, provider):
assert storage_view.table.row_count == manager_count
storage_view.paginator.find_row_on_pages(storage_view.table, Name=manager.name).click()
storage_detail_view = storage_view.browser.create_view(StorageManagerDetailsView)
- assert storage_detail_view.title.text == "{} (Summary)".format(manager.name)
+ assert storage_detail_view.title.text == f"{manager.name} (Summary)"
@pytest.mark.meta(automates=[1650086])
diff --git a/cfme/tests/storage/test_volume.py b/cfme/tests/storage/test_volume.py
index 7b2ce893f4..21af6b3f8f 100644
--- a/cfme/tests/storage/test_volume.py
+++ b/cfme/tests/storage/test_volume.py
@@ -104,7 +104,7 @@ def create_volume(appliance, provider, is_from_manager=False, az=None, cancel=Fa
cancel=cancel,
from_manager=is_from_manager)
elif provider.one_of(EC2Provider):
- az = az if az else "{}a".format(provider.region)
+ az = az if az else f"{provider.region}a"
volume = volume_collection.create(name=name,
volume_type='General Purpose SSD (GP2)',
volume_size=STORAGE_SIZE,
@@ -304,7 +304,7 @@ def test_multiple_cloud_volumes_tag_edit(appliance, soft_assert):
soft_assert(any(
tag.category.display_name == assigned_tag.category.display_name and
tag.display_name == assigned_tag.display_name for tag in tag_available), (
- 'Tag is not assigned to volume {}'.format(item.name)))
+ f'Tag is not assigned to volume {item.name}'))
# remove tags to multiple items at once
appliance.collections.volumes.remove_tag(volumes, assigned_tag)
diff --git a/cfme/tests/storage/test_volume_snapshot.py b/cfme/tests/storage/test_volume_snapshot.py
index a99e1d67fd..2cc5b6aae9 100644
--- a/cfme/tests/storage/test_volume_snapshot.py
+++ b/cfme/tests/storage/test_volume_snapshot.py
@@ -42,7 +42,7 @@ def volume(appliance, provider):
volume_kwargs['az'] = provider.data['provisioning']['availability_zone']
elif provider.one_of(EC2Provider):
- volume_kwargs['az'] = "{}a".format(provider.region)
+ volume_kwargs['az'] = f"{provider.region}a"
volume_kwargs['volume_type'] = 'General Purpose SSD (GP2)'
else:
return False
@@ -111,7 +111,7 @@ def test_storage_snapshot_create_cancelled_validation(volume, snapshot_create_fr
else:
view = volume.create_view(VolumeDetailsView, wait='10s')
view.flash.assert_message(
- 'Snapshot of Cloud Volume "{}" was cancelled by the user'.format(volume.name))
+ f'Snapshot of Cloud Volume "{volume.name}" was cancelled by the user')
@pytest.mark.parametrize('snapshot_create_from', [True, False], ids=['from_manager', 'from_volume'])
@@ -164,7 +164,7 @@ def test_storage_volume_snapshot_crud(volume, provider, snapshot_create_from):
snapshot = volume.create_snapshot(snapshot_name, from_manager=snapshot_create_from)
view = volume.create_view(VolumeDetailsView, wait='10s')
view.flash.assert_success_message(
- 'Snapshot for Cloud Volume "{}" created'.format(volume.name))
+ f'Snapshot for Cloud Volume "{volume.name}" created')
# check for volume relationship tables snapshot count
try:
diff --git a/cfme/tests/test_appliance.py b/cfme/tests/test_appliance.py
index dd9106ac8c..c030756d9f 100644
--- a/cfme/tests/test_appliance.py
+++ b/cfme/tests/test_appliance.py
@@ -37,7 +37,7 @@ def test_rpms_present(appliance, package):
testtype: functional
casecomponent: Appliance
"""
- result = appliance.ssh_client.run_command('rpm -q {}'.format(package))
+ result = appliance.ssh_client.run_command(f'rpm -q {package}')
assert 'is not installed' not in result.output
assert result.success
@@ -122,11 +122,11 @@ def test_firewalld_services_are_active(appliance):
"""
manageiq_zone = "manageiq"
result = appliance.ssh_client.run_command(
- 'firewall-cmd --permanent --zone={} --list-services'.format(manageiq_zone))
+ f'firewall-cmd --permanent --zone={manageiq_zone} --list-services')
assert {'ssh', 'http', 'https'} <= set(result.output.split())
default_iface_zone = appliance.ssh_client.run_command(
- "firewall-cmd --get-zone-of-interface {}".format(appliance.default_iface)
+ f"firewall-cmd --get-zone-of-interface {appliance.default_iface}"
).output.strip()
assert default_iface_zone == manageiq_zone
@@ -153,7 +153,7 @@ def test_firewalld_active_zone_after_restart(appliance):
def get_def_iface_zone():
default_iface_zone_cmd = appliance.ssh_client.run_command(
- "firewall-cmd --get-zone-of-interface {}".format(appliance.default_iface)
+ f"firewall-cmd --get-zone-of-interface {appliance.default_iface}"
)
assert default_iface_zone_cmd.success
return default_iface_zone_cmd.output.strip()
@@ -221,7 +221,7 @@ def test_certificates_present(appliance, soft_assert):
).success
for cert in known_certs:
- assert appliance.ssh_client.run_command("test -f '{}'".format(cert)).success
+ assert appliance.ssh_client.run_command(f"test -f '{cert}'").success
assert appliance.ssh_client.run_command(
"openssl verify -CAfile {ca_cert} '{cert_file}'"
.format(ca_cert=rhsm_ca_cert, cert_file=cert)
@@ -250,7 +250,7 @@ def test_html5_ssl_files_present(appliance, soft_assert):
for ssl_file in ssl_files:
# Test for files existance
- assert appliance.ssh_client.run_command("test -f '{}'".format(ssl_file)).success
+ assert appliance.ssh_client.run_command(f"test -f '{ssl_file}'").success
@pytest.mark.ignore_stream("upstream")
@@ -295,8 +295,8 @@ def test_keys_included(appliance, soft_assert):
keys = ['v0_key', 'v1_key', 'v2_key']
for k in keys:
soft_assert(appliance.ssh_client.run_command(
- "test -e /var/www/miq/vmdb/certs/{}".format(k)).success,
- "{} was not included in the build".format(k))
+ f"test -e /var/www/miq/vmdb/certs/{k}").success,
+ f"{k} was not included in the build")
def test_appliance_console_packages(appliance):
@@ -459,7 +459,7 @@ def test_codename_in_stdout(appliance):
@wait_for_decorator
def codename_in_stdout():
r = appliance.ssh_client.run_command(
- r'journalctl -u evmserverd -c "{}" | egrep -i "codename: \w+$"'.format(cursor))
+ fr'journalctl -u evmserverd -c "{cursor}" | egrep -i "codename: \w+$"')
return r.success
appliance.wait_for_web_ui()
diff --git a/cfme/tests/test_db_migrate.py b/cfme/tests/test_db_migrate.py
index a7ed8a3212..8937c59a58 100644
--- a/cfme/tests/test_db_migrate.py
+++ b/cfme/tests/test_db_migrate.py
@@ -66,7 +66,7 @@ def appliance_preupdate(temp_appliance_preconfig_funcscope_upgrade, appliance):
temp_appliance_preconfig_funcscope_upgrade.db.extend_partition()
urls = cfme_data["basic_info"][update_url]
temp_appliance_preconfig_funcscope_upgrade.ssh_client.run_command(
- "curl {} -o /etc/yum.repos.d/update.repo".format(urls)
+ f"curl {urls} -o /etc/yum.repos.d/update.repo"
)
return temp_appliance_preconfig_funcscope_upgrade
@@ -87,7 +87,7 @@ def fetch(src, dst):
assert result.success, f"Failed to download {src}:\n{result.output}"
# Download the database
- logger.info("Downloading database: {}".format(db_url))
+ logger.info(f"Downloading database: {db_url}")
url_basename = os_path.basename(db_url)
loc = "/tmp/"
v2key_url = os_path.join(os_path.dirname(db_url), "v2_key.bak")
@@ -108,13 +108,13 @@ def fetch(src, dst):
# restore new DB
if db_format == "pg_dump":
result = app.ssh_client.run_command(
- 'pg_restore -v --dbname=vmdb_production {}{}'.format(loc, url_basename), timeout=600)
+ f'pg_restore -v --dbname=vmdb_production {loc}{url_basename}', timeout=600)
elif db_format == "pg_dumpall":
result = app.ssh_client.run_command(
- 'psql postgres < {}{}'.format(loc, url_basename), timeout=600)
+ f'psql postgres < {loc}{url_basename}', timeout=600)
else:
raise Exception(f'Unknown db format: {db_format}')
- assert result.success, "Failed to restore new database: {}".format(result.output)
+ assert result.success, f"Failed to restore new database: {result.output}"
# fetch the files needed for decrypt the db
try:
@@ -149,7 +149,7 @@ def fetch(src, dst):
app.evmserverd.start()
except ApplianceException:
result = app.ssh_client.run_rake_command("evm:start")
- assert result.success, "Couldn't start evmserverd: {}".format(result.output)
+ assert result.success, f"Couldn't start evmserverd: {result.output}"
app.wait_for_web_ui(timeout=600)
app.db.reset_user_pass()
wait_for(navigate_to, (app.server, 'LoginScreen'), handle_exception=True, timeout='5m')
@@ -188,12 +188,12 @@ def test_db_migrate_replication(temp_appliance_remote, dbversion, temp_appliance
app = temp_appliance_remote
app2 = temp_appliance_global_region
# Download the database
- logger.info("Downloading database: {}".format(dbversion))
+ logger.info(f"Downloading database: {dbversion}")
db_url = cfme_data['db_backups'][dbversion]['url']
url_basename = os_path.basename(db_url)
result = app.ssh_client.run_command(
- 'curl -o "/tmp/{}" "{}"'.format(url_basename, db_url), timeout=30)
- assert result.success, "Failed to download database: {}".format(result.output)
+ f'curl -o "/tmp/{url_basename}" "{db_url}"', timeout=30)
+ assert result.success, f"Failed to download database: {result.output}"
# The v2_key is potentially here
v2key_url = os_path.join(os_path.dirname(db_url), "v2_key")
# Stop EVM service and drop vmdb_production DB
@@ -202,18 +202,18 @@ def test_db_migrate_replication(temp_appliance_remote, dbversion, temp_appliance
app.db.create()
# restore new DB and migrate it
result = app.ssh_client.run_command(
- 'pg_restore -v --dbname=vmdb_production /tmp/{}'.format(url_basename), timeout=600)
- assert result.success, "Failed to restore new database: {}".format(result.output)
+ f'pg_restore -v --dbname=vmdb_production /tmp/{url_basename}', timeout=600)
+ assert result.success, f"Failed to restore new database: {result.output}"
app.db.migrate()
# fetch v2_key
try:
result = app.ssh_client.run_command(
- 'curl "{}"'.format(v2key_url), timeout=15)
- assert result.success, "Failed to download v2_key: {}".format(result.output)
- assert ":key:" in result.output, "Not a v2_key file: {}".format(result.output)
+ f'curl "{v2key_url}"', timeout=15)
+ assert result.success, f"Failed to download v2_key: {result.output}"
+ assert ":key:" in result.output, f"Not a v2_key file: {result.output}"
result = app.ssh_client.run_command(
- 'curl -o "/var/www/miq/vmdb/certs/v2_key" "{}"'.format(v2key_url), timeout=15)
- assert result.success, "Failed to download v2_key: {}".format(result.output)
+ f'curl -o "/var/www/miq/vmdb/certs/v2_key" "{v2key_url}"', timeout=15)
+ assert result.success, f"Failed to download v2_key: {result.output}"
# or change all invalid (now unavailable) passwords to 'invalid'
except AssertionError:
app.db.fix_auth_key()
@@ -223,7 +223,7 @@ def test_db_migrate_replication(temp_appliance_remote, dbversion, temp_appliance
app.evmserverd.start()
except ApplianceException:
result = app.ssh_client.run_rake_command("evm:start")
- assert result.success, "Couldn't start evmserverd: {}".format(result.output)
+ assert result.success, f"Couldn't start evmserverd: {result.output}"
app.wait_for_web_ui(timeout=600)
# Reset user's password, just in case (necessary for customer DBs)
app.db.reset_user_pass()
@@ -253,7 +253,7 @@ def test_upgrade_single_inplace(appliance_preupdate, appliance):
"""
appliance_preupdate.evmserverd.stop()
result = appliance_preupdate.ssh_client.run_command('yum update -y', timeout=3600)
- assert result.success, "update failed {}".format(result.output)
+ assert result.success, f"update failed {result.output}"
appliance_preupdate.db.migrate()
appliance_preupdate.db.automate_reset()
appliance_preupdate.db_service.restart()
diff --git a/cfme/tests/test_modules_importable.py b/cfme/tests/test_modules_importable.py
index 2d9a23f9fe..372d1872bc 100644
--- a/cfme/tests/test_modules_importable.py
+++ b/cfme/tests/test_modules_importable.py
@@ -10,7 +10,7 @@
MODULES = sorted(x for x in ROOT.visit("*.py") if 'test_' not in x.basename)
-KNOWN_FAILURES = set(ROOT.dirpath().join(x) for x in[
+KNOWN_FAILURES = {ROOT.dirpath().join(x) for x in[
'cfme/utils/ports.py', # module object
'cfme/utils/dockerbot/check_prs.py', # unprotected script
'cfme/utils/conf.py', # config object that replaces the module
@@ -23,7 +23,7 @@
'cfme/configure/tasks.py',
'cfme/scripting/bz.py',
'cfme/scripting/miq.py',
-])
+]}
@pytest.mark.parametrize('module_path', MODULES, ids=ROOT.dirpath().bestrelpath)
diff --git a/cfme/tests/test_replication.py b/cfme/tests/test_replication.py
index fe61b76ead..dbffe951f5 100644
--- a/cfme/tests/test_replication.py
+++ b/cfme/tests/test_replication.py
@@ -18,7 +18,7 @@ def create_vm(provider, vm_name):
try:
template_name = provider.data['templates']['full_template']['name']
except KeyError:
- pytest.skip('Unable to identify full_template for provider: {}'.format(provider))
+ pytest.skip(f'Unable to identify full_template for provider: {provider}')
vm = collection.instantiate(
vm_name,
diff --git a/cfme/tests/test_rest.py b/cfme/tests/test_rest.py
index 0775ac666a..4601d89d99 100644
--- a/cfme/tests/test_rest.py
+++ b/cfme/tests/test_rest.py
@@ -630,7 +630,7 @@ def test_rest_paging(appliance, paging):
limit, offset = paging
url_string = '{}{}'.format(
appliance.rest_api.collections.features._href,
- '?limit={}&offset={}'.format(limit, offset))
+ f'?limit={limit}&offset={offset}')
if limit == 0:
# testing BZ1489885
with pytest.raises(Exception, match='Api::BadRequestError'):
@@ -652,15 +652,15 @@ def test_rest_paging(appliance, paging):
assert response['pages'] == expected_pages_num
links = response['links']
- assert 'limit={}&offset={}'.format(limit, offset) in links['self']
+ assert f'limit={limit}&offset={offset}' in links['self']
if (offset + limit) < response['count']:
assert 'limit={}&offset={}'.format(limit, offset + limit) in links['next']
if offset > 0:
expected_previous_offset = offset - limit if offset > limit else 0
- assert 'limit={}&offset={}'.format(limit, expected_previous_offset) in links['previous']
+ assert f'limit={limit}&offset={expected_previous_offset}' in links['previous']
assert 'limit={}&offset={}'.format(limit, 0) in links['first']
expected_last_offset = (response['pages'] - (1 if response['count'] % limit else 0)) * limit
- assert 'limit={}&offset={}'.format(limit, expected_last_offset) in links['last']
+ assert f'limit={limit}&offset={expected_last_offset}' in links['last']
@pytest.mark.tier(3)
@@ -690,7 +690,7 @@ def test_attributes_present(appliance, collection_name):
attrs = 'href,id,href_slug'
collection = getattr(appliance.rest_api.collections, collection_name)
response = appliance.rest_api.get(
- '{0}{1}{2}'.format(collection._href, '?expand=resources&attributes=', attrs))
+ '{}{}{}'.format(collection._href, '?expand=resources&attributes=', attrs))
assert_response(appliance)
for resource in response.get('resources', []):
assert 'id' in resource
@@ -716,7 +716,7 @@ def test_collection_class_valid(appliance, provider, vendor):
collection = appliance.rest_api.collections.vms
collection.reload()
resource_type = collection[0].type
- tested_type = 'ManageIQ::Providers::{}::InfraManager::Vm'.format(vendor)
+ tested_type = f'ManageIQ::Providers::{vendor}::InfraManager::Vm'
response = collection.query_string(collection_class=tested_type)
if resource_type == tested_type:
@@ -793,11 +793,11 @@ def test_rest_ping(appliance):
caseimportance: medium
initialEstimate: 1/4h
"""
- ping_addr = '{}/ping'.format(appliance.rest_api._entry_point)
+ ping_addr = f'{appliance.rest_api._entry_point}/ping'
assert appliance.rest_api._session.get(ping_addr).text == 'pong'
-class TestPicturesRESTAPI(object):
+class TestPicturesRESTAPI:
def create_picture(self, appliance):
picture = appliance.rest_api.collections.pictures.action.create({
"extension": "png",
@@ -824,7 +824,7 @@ def test_query_picture_attributes(self, appliance, soft_assert):
# BZ 1547852, some attrs were not working
# bad_attrs = ('href_slug', 'region_description', 'region_number', 'image_href')
for failure in outcome.failed:
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
def test_add_picture(self, appliance):
@@ -893,7 +893,7 @@ def test_add_picture_invalid_data(self, appliance):
assert collection.count == count
-class TestBulkQueryRESTAPI(object):
+class TestBulkQueryRESTAPI:
def test_bulk_query(self, appliance):
"""Tests bulk query referencing resources by attributes id, href and guid
@@ -976,7 +976,7 @@ def test_bulk_query_groups(self, appliance):
assert data0 == response[0]._data and data1 == response[1]._data
-class TestNotificationsRESTAPI(object):
+class TestNotificationsRESTAPI:
@pytest.fixture(scope='function')
def generate_notifications(self, appliance):
requests_data = automation_requests_data('nonexistent_vm')
@@ -1064,7 +1064,7 @@ def test_delete_notifications_from_collection(self, appliance, generate_notifica
delete_resources_from_collection(notifications)
-class TestEventStreamsRESTAPI(object):
+class TestEventStreamsRESTAPI:
@pytest.fixture(scope='function')
def gen_events(self, appliance, vm_obj, provider):
vm_name = vm_obj
@@ -1129,7 +1129,7 @@ def test_find_created_events(self, appliance, vm_obj, gen_events, provider, soft
try:
evt_col.get(id=found_evts[-1].id)
except (IndexError, ValueError):
- soft_assert(False, "Couldn't get event {} for vm {}".format(evt, vm_name))
+ soft_assert(False, f"Couldn't get event {evt} for vm {vm_name}")
@pytest.mark.tier(3)
@@ -1252,7 +1252,7 @@ def test_custom_logos_via_api(appliance, image_type, request):
def _finalize():
appliance.server.upload_custom_logo(file_type=image_type, enable=False)
- href = "https://{}/api/product_info".format(appliance.hostname)
+ href = f"https://{appliance.hostname}/api/product_info"
api = appliance.rest_api
# wait until product info is updated
diff --git a/cfme/tests/v2v/test_csv_import.py b/cfme/tests/v2v/test_csv_import.py
index 6de8959c9f..6c4edd158d 100644
--- a/cfme/tests/v2v/test_csv_import.py
+++ b/cfme/tests/v2v/test_csv_import.py
@@ -68,7 +68,7 @@ def check_vm_status(appliance, infra_map, filetype='csv', content=False,
table_hover=False, alert=False, security_group=False):
"""Function to import csv, select vm and return hover error from migration plan table"""
plan_view = migration_plan(appliance, infra_map)
- temp_file = tempfile.NamedTemporaryFile(suffix='.{}'.format(filetype))
+ temp_file = tempfile.NamedTemporaryFile(suffix=f'.{filetype}')
if content:
with open(temp_file.name, 'w') as f:
f.write(content)
@@ -229,7 +229,7 @@ def test_csv_valid_vm(appliance, infra_map, valid_vm):
casecomponent: V2V
initialEstimate: 1/8h
"""
- content = "Name\n{}".format(valid_vm)
+ content = f"Name\n{valid_vm}"
error_msg = "VM available for migration"
hover_error = check_vm_status(
appliance, infra_map, error_msg, content=content, table_hover=True)
@@ -245,7 +245,7 @@ def test_csv_duplicate_vm(appliance, infra_map, valid_vm):
casecomponent: V2V
initialEstimate: 1/8h
"""
- content = "Name\n{}\n{}".format(valid_vm, valid_vm)
+ content = f"Name\n{valid_vm}\n{valid_vm}"
error_msg = "Duplicate VM"
hover_error = check_vm_status(
appliance, infra_map, error_msg, content=content, table_hover='duplicate')
@@ -261,7 +261,7 @@ def test_csv_archived_vm(appliance, infra_map, archived_vm):
casecomponent: V2V
initialEstimate: 1/8h
"""
- content = "Name\n{}".format(archived_vm)
+ content = f"Name\n{archived_vm}"
error_msg = "VM is inactive"
hover_error = check_vm_status(
appliance, infra_map, error_msg, content=content, table_hover=True)
diff --git a/cfme/tests/v2v/test_v2v_ansible.py b/cfme/tests/v2v/test_v2v_ansible.py
index 51826aeceb..d404e2830c 100644
--- a/cfme/tests/v2v/test_v2v_ansible.py
+++ b/cfme/tests/v2v/test_v2v_ansible.py
@@ -70,7 +70,7 @@ def catalog_item(request, appliance, machine_credential, ansible_repository, pla
description=fauxfactory.gen_alphanumeric(),
provisioning={
"repository": ansible_repository.name,
- "playbook": "{}.yml".format(playbook_type),
+ "playbook": f"{playbook_type}.yml",
"machine_credential": machine_credential,
"create_new": True,
"provisioning_dialog_name": fauxfactory.gen_alphanumeric(),
diff --git a/cfme/tests/webui/test_advanced_search.py b/cfme/tests/webui/test_advanced_search.py
index d06f39c552..daca9f3f1d 100644
--- a/cfme/tests/webui/test_advanced_search.py
+++ b/cfme/tests/webui/test_advanced_search.py
@@ -97,10 +97,10 @@ def _filter_crud(param, appliance):
filter_value = fauxfactory.gen_numeric_string(3)
filter_value_updated = fauxfactory.gen_numeric_string(3)
view.search.save_filter(
- "fill_count({}, =, {})".format(param.filter, filter_value), filter_name)
+ f"fill_count({param.filter}, =, {filter_value})", filter_name)
else:
view.search.save_filter(
- "fill_field({}, =, {})".format(param.filter, filter_value), filter_name)
+ f"fill_field({param.filter}, =, {filter_value})", filter_name)
view.search.close_advanced_search()
view.flash.assert_no_error()
# read
@@ -193,7 +193,7 @@ def base_pytestmarks(param_values, setup_prov=False):
@inject_tests
@pytest.mark.provider([CloudProvider], selector=ONE_PER_CATEGORY)
-class TestCloud(object):
+class TestCloud:
params_values = [
SearchParam('cloud_providers', 'All', 'cloudprovider', 'Cloud Provider : Name', None),
SearchParam('cloud_av_zones', 'All', 'availabilityzone', 'Availability Zone : Name', None),
@@ -213,7 +213,7 @@ class TestCloud(object):
@inject_tests
@pytest.mark.provider([CloudProvider], selector=ONE_PER_CATEGORY)
-class TestNetwork(object):
+class TestNetwork:
params_values = [
SearchParam('network_providers', 'All', 'network_managers', 'Network Manager : Name', None),
SearchParam('network_providers', 'All', 'network_managers', 'Network Manager : Name', None),
@@ -231,7 +231,7 @@ class TestNetwork(object):
@inject_tests
@pytest.mark.provider([InfraProvider], selector=ONE_PER_CATEGORY, )
-class TestInfra(object):
+class TestInfra:
params_values = [
SearchParam('infra_providers', 'All', 'infraproviders',
'Infrastructure Provider : Name', None),
@@ -255,7 +255,7 @@ class TestInfra(object):
@inject_tests
@pytest.mark.provider([PhysicalProvider], selector=ONE_PER_CATEGORY)
-class TestPhysical(object):
+class TestPhysical:
params_values = [
SearchParam('physical_providers', 'All', 'physical_providers',
'Physical Infrastructure Provider : Name', None),
@@ -266,7 +266,7 @@ class TestPhysical(object):
@inject_tests
@pytest.mark.provider([ContainersProvider], selector=ONE_PER_CATEGORY)
-class TestContainers(object):
+class TestContainers:
params_values = [
SearchParam(
'containers_providers', 'All', 'container_providers', 'Containers Provider : Name',
@@ -298,7 +298,7 @@ class TestContainers(object):
@inject_tests
@pytest.mark.meta(blockers=[GH('ManageIQ/integration_tests:9723')])
-class TestAnsibleTower(object):
+class TestAnsibleTower:
params_values = [
SearchParam('ansible_tower_providers', 'All', 'ansible_tower_explorer_provider',
'Automation Manager (Ansible Tower) : Name',
@@ -316,7 +316,7 @@ class TestAnsibleTower(object):
@inject_tests
-class TestStorage(object):
+class TestStorage:
params_values = [
SearchParam('volumes', 'All', 'block_store_volumes', 'Cloud Volume : Name', None),
SearchParam('volume_snapshots', 'All', 'block_store_snapshots',
@@ -333,7 +333,7 @@ class TestStorage(object):
@inject_tests
@pytest.mark.meta(blockers=[GH('ManageIQ/integration_tests:9723')])
-class TestConfigManagement(object):
+class TestConfigManagement:
params_values = [
SearchParam(ConfigManagerProvider, 'All', 'configuration_management',
'Configuration Manager : Name',
@@ -347,6 +347,6 @@ class TestConfigManagement(object):
@inject_tests
@pytest.mark.meta(blockers=[BZ(1733489)])
-class TestServices(object):
+class TestServices:
params_values = [SearchParam(MyService, 'All', 'myservices', 'Service : Name', 'myservice')]
pytestmark = base_pytestmarks(params_values)
diff --git a/cfme/tests/webui/test_general_ui.py b/cfme/tests/webui/test_general_ui.py
index 1572161bb7..807199dbfc 100644
--- a/cfme/tests/webui/test_general_ui.py
+++ b/cfme/tests/webui/test_general_ui.py
@@ -79,7 +79,7 @@ def import_tags(appliance):
except AssertionError:
for script in scripts:
client.run_command(
- 'cd /var/www/miq/vmdb/lib/tasks/ && rm -f {}'.format(script))
+ f'cd /var/www/miq/vmdb/lib/tasks/ && rm -f {script}')
pytest.skip('Not all scripts were successfully downloaded')
try:
assert client.run_command(
@@ -102,7 +102,7 @@ def import_tags(appliance):
yield tags
for script in scripts:
client.run_command(
- 'cd /var/www/miq/vmdb/lib/tasks/ && rm -f {}'.format(script))
+ f'cd /var/www/miq/vmdb/lib/tasks/ && rm -f {script}')
client.run_command('cd /tmp && rm -f tags.yml*')
@@ -140,9 +140,9 @@ def create_20k_vms(appliance):
' :vendor => "vmware", :location => "foo" }')
rails_cleanup_command = ('20000.times { |i| ManageIQ::Providers::Vmware::InfraManager::'
'Vm.where(:name => "vm_%05d" % (1+i)).first.delete}')
- appliance.ssh_client.run_rails_command("'{}'".format(rails_create_command))
+ appliance.ssh_client.run_rails_command(f"'{rails_create_command}'")
yield
- appliance.ssh_client.run_rails_command("'{}'".format(rails_cleanup_command))
+ appliance.ssh_client.run_rails_command(f"'{rails_cleanup_command}'")
@pytest.fixture
@@ -192,7 +192,7 @@ def test_configuration_large_number_of_tags(appliance, import_tags, soft_assert)
for tag in tags:
tag = tag.strip()
soft_assert(view.entities.my_company_tags.tree.has_path(category, tag), (
- 'Tag {} was not imported'.format(tag)
+ f'Tag {tag} was not imported'
))
@@ -213,7 +213,7 @@ def test_configuration_help_menu(appliance, set_help_menu_options, soft_assert):
view = navigate_to(appliance.server, 'Dashboard')
for option in set_help_menu_options:
soft_assert(view.help.has_item(
- option), '{} option is not available in help menu'.format(option))
+ option), f'{option} option is not available in help menu')
def test_automate_can_edit_copied_method(appliance, request):
diff --git a/cfme/tests/webui/test_rest.py b/cfme/tests/webui/test_rest.py
index 6567e2bf82..dbbadce129 100644
--- a/cfme/tests/webui/test_rest.py
+++ b/cfme/tests/webui/test_rest.py
@@ -25,7 +25,7 @@ def search_filter_obj(appliance, request):
view = navigate_to(appliance.collections.infra_providers, "All")
view.search.save_filter(
- "fill_field({}, =, {})".format(param_filter, filter_value),
+ f"fill_field({param_filter}, =, {filter_value})",
filter_name,
global_search=request.param,
)
diff --git a/cfme/tests/webui/test_splitter.py b/cfme/tests/webui/test_splitter.py
index e106fc2ad1..7f84536351 100644
--- a/cfme/tests/webui/test_splitter.py
+++ b/cfme/tests/webui/test_splitter.py
@@ -89,4 +89,4 @@ def test_pull_splitter_persistence(request, appliance, model_object, destination
if not selenium.find_element_by_xpath(
"//div[@id='left_div'][contains(@class, {})]".format(
unescape(quoteattr(position)))):
- pytest.fail("Splitter did not persist when on '{}' position!".format(position))
+ pytest.fail(f"Splitter did not persist when on '{position}' position!")
diff --git a/cfme/utils/__init__.py b/cfme/utils/__init__.py
index 6dd6ded2aa..b1c8974122 100644
--- a/cfme/utils/__init__.py
+++ b/cfme/utils/__init__.py
@@ -19,7 +19,7 @@ class TriesExceeded(Exception):
pass
-class FakeObject(object):
+class FakeObject:
def __init__(self, **kwargs):
self.__dict__ = kwargs
@@ -163,7 +163,7 @@ def read_env(file):
if file.check():
# parse the file with bash, since it's pretty good at it, and dump the env
# Use env -i to clean up the env (except the very few variables provider by bash itself)
- command = ['env', '-i', 'bash', '-c', 'source {} && env'.format(file.strpath)]
+ command = ['env', '-i', 'bash', '-c', f'source {file.strpath} && env']
proc = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1)
# filter out the remaining unwanted things
@@ -255,7 +255,7 @@ def process_shell_output(value):
result_lines.append(entry)
elif isinstance(value, dict):
for key, value in value.items():
- result_lines.append('{}={}'.format(key, value))
+ result_lines.append(f'{key}={value}')
elif isinstance(value, str):
result_lines.append(value)
elif isinstance(value, bool):
@@ -319,7 +319,7 @@ def castmap(t, i, *args, **kwargs):
return list(icastmap(t, i, *args, **kwargs))
-class InstanceClassMethod(object):
+class InstanceClassMethod:
""" Decorator-descriptor that enables you to use any method both as class and instance one
Usage:
@@ -360,7 +360,7 @@ def __get__(self, o, t):
return partial(self.instance_or_class_method, o)
-class ParamClassName(object):
+class ParamClassName:
""" ParamClassName is a Descriptor to help when using classes and instances as parameters
Note: This descriptor is a hack until collections are implemented everywhere
diff --git a/cfme/utils/ansible.py b/cfme/utils/ansible.py
index c0f24595cd..71254c1cbb 100644
--- a/cfme/utils/ansible.py
+++ b/cfme/utils/ansible.py
@@ -282,7 +282,7 @@ def run_ansible(script):
ansible_playbook_cmd = "ansible-playbook -e ansible_python_interpreter="
interpreter_path = sys.executable
script_path = path.join(basic_yml_path, script + ".yml")
- cmd = '{}{} {}'.format(ansible_playbook_cmd, interpreter_path, script_path)
+ cmd = f'{ansible_playbook_cmd}{interpreter_path} {script_path}'
return run_cmd(cmd)
@@ -293,7 +293,7 @@ def run_cmd(cmd):
print("Status : FAIL", exc.returncode, exc.output)
return exc.output
else:
- print("Output: \n{}\n".format(response))
+ print(f"Output: \n{response}\n")
# TODO For further usage with reply statuses test. Not being used at the moment
diff --git a/cfme/utils/appliance/__init__.py b/cfme/utils/appliance/__init__.py
index 7602c53088..0be9acf83c 100644
--- a/cfme/utils/appliance/__init__.py
+++ b/cfme/utils/appliance/__init__.py
@@ -94,7 +94,7 @@ def get_entity_by_href(self, href):
collection = getattr(self.collections, path.pop(0))
entity = collection(int(path.pop(0)))
if path:
- raise ValueError('Subcollections not supported! ({})'.format(parsed.path))
+ raise ValueError(f'Subcollections not supported! ({parsed.path})')
return entity
@@ -102,7 +102,7 @@ class ApplianceException(Exception):
pass
-class IPAppliance(object):
+class IPAppliance:
"""IPAppliance represents an already provisioned cfme appliance whos provider is unknown
but who has an IP address. This has a lot of core functionality that Appliance uses, since
it knows both the provider, vm_name and can there for derive the IP address.
@@ -345,7 +345,7 @@ def _screenshot_capture_at_context_leave(self, exc_type, exc_val, exc_tb):
ss, ss_error = take_screenshot()
full_tb = "".join(traceback.format_tb(exc_tb))
short_tb = "{}: {}".format(exc_type.__name__, str(exc_val))
- full_tb = "{}\n{}".format(full_tb, short_tb)
+ full_tb = f"{full_tb}\n{short_tb}"
g_id = fauxfactory.gen_alpha(length=30, start="appliance-cm-screenshot-")
@@ -401,14 +401,14 @@ def fix_httpd_issue(self, log_callback=None):
filename = 'httpd.service'
src = os.path.join('/usr/lib/systemd/system', filename)
dst = os.path.join('/etc/systemd/system', filename)
- copy_cmd = 'cp {} {}'.format(src, dst)
+ copy_cmd = f'cp {src} {dst}'
assert ssh.run_command(copy_cmd).success
exec_pre = r"""
[Service]
ExecStartPre=/usr/bin/bash -c "ipcs -s|grep apache|cut -d\ -f2|while read line; \
do ipcrm sem $line; done"
"""
- full_cmd = """echo '{cmd}' >> {dst}""".format(cmd=exec_pre, dst=dst)
+ full_cmd = f"""echo '{exec_pre}' >> {dst}"""
assert ssh.run_command(full_cmd).success
log_callback('systemd httpd.service file written')
self.httpd.daemon_reload()
@@ -463,7 +463,7 @@ def configure(self, log_callback=None, **kwargs):
To hard-fault on rails deprecations, use ``:raise``
"""
- log_callback("Configuring appliance {}".format(self.hostname))
+ log_callback(f"Configuring appliance {self.hostname}")
fix_ntp_clock = kwargs.pop('fix_ntp_clock', True)
region = kwargs.pop('region', 0)
key_address = kwargs.pop('key_address', None)
@@ -662,7 +662,7 @@ def from_url(cls, url, **kwargs):
# If you only pass the hostname (+ port possibly) without scheme or anything else
host_part = parsed.path
else:
- raise ValueError('Unsupported url specification: {}'.format(url))
+ raise ValueError(f'Unsupported url specification: {url}')
if ':' in host_part:
hostname, port = host_part.rsplit(':', 1)
@@ -712,9 +712,9 @@ def url(self):
"""
show_port = self.PROTOCOL_PORT_MAPPING[self.ui_protocol] != self.ui_port
if show_port:
- return '{}://{}:{}/'.format(self.ui_protocol, self.hostname, self.ui_port)
+ return f'{self.ui_protocol}://{self.hostname}:{self.ui_port}/'
else:
- return '{}://{}/'.format(self.ui_protocol, self.hostname)
+ return f'{self.ui_protocol}://{self.hostname}/'
def url_path(self, path):
"""generates URL with an additional path. Useful for generating REST or SSUI URLs."""
@@ -726,7 +726,7 @@ def disks_and_partitions(self):
disks_and_partitions = self.ssh_client.run_command(
"ls -1 /dev/ | egrep '^[sv]d[a-z][0-9]?'").output.strip()
disks_and_partitions = re.split(r'\s+', disks_and_partitions)
- return sorted('/dev/{}'.format(disk) for disk in disks_and_partitions)
+ return sorted(f'/dev/{disk}' for disk in disks_and_partitions)
@property
def disks(self):
@@ -756,7 +756,7 @@ def unpartitioned_disks(self):
def product_name(self):
try:
return self.rest_api.product_info['name']
- except (AttributeError, KeyError, IOError, ConnectionError):
+ except (AttributeError, KeyError, OSError, ConnectionError):
self.log.info(
'appliance.product_name could not be retrieved from REST, falling back')
try:
@@ -793,7 +793,7 @@ def version(self):
def _version_from_rest(self):
try:
return Version(self.rest_api.server_info['version'])
- except (AttributeError, KeyError, IOError, APIException):
+ except (AttributeError, KeyError, OSError, APIException):
self.log.exception('Exception fetching appliance version from REST, trying ssh')
return self.ssh_client.vmdb_version
@@ -805,7 +805,7 @@ def verify_version(self):
def build(self):
try:
return self.rest_api.server_info['build']
- except (AttributeError, KeyError, IOError):
+ except (AttributeError, KeyError, OSError):
self.log.exception('appliance.build could not be retrieved from REST, falling back')
res = self.ssh_client.run_command('cat /var/www/miq/vmdb/BUILD')
if res.failed:
@@ -896,7 +896,7 @@ def create_ssh_connection():
logger.info('default appliance ssh credentials are valid')
except Exception as e:
if self.is_dev:
- raise Exception('SSH access on a dev appliance (unsupported): {}'.format(e))
+ raise Exception(f'SSH access on a dev appliance (unsupported): {e}')
logger.exception(
('default appliance ssh credentials failed: {}, '
'trying establish ssh connection using ssh private key').format(e))
@@ -932,7 +932,7 @@ def swap(self):
try:
server = self.rest_api.get_entity_by_href(self.rest_api.server_info['server_href'])
return server.system_swap_used / 1024 / 1024
- except (AttributeError, KeyError, IOError):
+ except (AttributeError, KeyError, OSError):
self.log.exception('appliance.swap could not be retrieved from REST, falling back')
value = self.ssh_client.run_command(
'free -m | tr -s " " " " | cut -f 3 -d " " | tail -n 1', timeout=15)
@@ -973,7 +973,7 @@ def diagnose_evm_failure(self):
try:
self.db_service.restart()
except SystemdException as ex:
- return 'postgres failed to start: \n{}'.format(ex.message)
+ return f'postgres failed to start: \n{ex.message}'
else:
return 'postgres was not running for unknown reasons'
@@ -1069,7 +1069,7 @@ def patch_with_miqqe(self, log_callback=None):
timeout=300)
logger.info("Web UI is up and running")
self.ssh_client.run_command(
- "echo '{}' > /var/www/miq/vmdb/.miqqe_version".format(current_miqqe_version))
+ f"echo '{current_miqqe_version}' > /var/www/miq/vmdb/.miqqe_version")
# Invalidate cached version
del self.miqqe_version
@@ -1110,14 +1110,14 @@ def precompile_assets(self, log_callback=None):
store.terminalreporter.write_line('Phase 1 of 2: rake assets:clobber')
result = client.run_rake_command("assets:clobber")
if result.failed:
- msg = 'Appliance {} failed to nuke old assets'.format(self.hostname)
+ msg = f'Appliance {self.hostname} failed to nuke old assets'
log_callback(msg)
raise ApplianceException(msg)
store.terminalreporter.write_line('Phase 2 of 2: rake assets:precompile')
result = client.run_rake_command("assets:precompile")
if result.failed:
- msg = 'Appliance {} failed to precompile assets'.format(self.hostname)
+ msg = f'Appliance {self.hostname} failed to precompile assets'
log_callback(msg)
raise ApplianceException(msg)
@@ -1140,15 +1140,15 @@ def clone_domain(self, source="ManageIQ", dest="Default", log_callback=None):
self.db.wait_for()
# Make sure the working dir exists
- client.run_command('mkdir -p /tmp/{}'.format(source))
+ client.run_command(f'mkdir -p /tmp/{source}')
export_opts = 'DOMAIN={} EXPORT_DIR=/tmp/{} PREVIEW=false OVERWRITE=true'.format(source,
source)
- export_cmd = 'evm:automate:export {}'.format(export_opts)
- log_callback('Exporting domain ({}) ...'.format(export_cmd))
+ export_cmd = f'evm:automate:export {export_opts}'
+ log_callback(f'Exporting domain ({export_cmd}) ...')
result = client.run_rake_command(export_cmd)
if result.failed:
- msg = 'Failed to export {} domain'.format(source)
+ msg = f'Failed to export {source} domain'
log_callback(msg)
raise ApplianceException(msg)
@@ -1156,17 +1156,17 @@ def clone_domain(self, source="ManageIQ", dest="Default", log_callback=None):
"/tmp/{}/{}/__domain__.yaml".format(source, source))
result = client.run_command(ro_fix_cmd)
if result.failed:
- msg = 'Setting {} domain to read/write failed'.format(dest)
+ msg = f'Setting {dest} domain to read/write failed'
log_callback(msg)
raise ApplianceException(msg)
- import_opts = 'DOMAIN={} IMPORT_DIR=/tmp/{} PREVIEW=false'.format(source, source)
- import_opts += ' OVERWRITE=true IMPORT_AS={} ENABLED=true'.format(dest)
- import_cmd = 'evm:automate:import {}'.format(import_opts)
- log_callback('Importing domain ({}) ...'.format(import_cmd))
+ import_opts = f'DOMAIN={source} IMPORT_DIR=/tmp/{source} PREVIEW=false'
+ import_opts += f' OVERWRITE=true IMPORT_AS={dest} ENABLED=true'
+ import_cmd = f'evm:automate:import {import_opts}'
+ log_callback(f'Importing domain ({import_cmd}) ...')
result = client.run_rake_command(import_cmd)
if result.failed:
- msg = 'Failed to import {} domain'.format(dest)
+ msg = f'Failed to import {dest} domain'
log_callback(msg)
raise ApplianceException(msg)
@@ -1186,7 +1186,7 @@ def read_repos(self):
name_regexp = re.compile(r"^\[update-([^\]]+)\]")
baseurl_regexp = re.compile(r"baseurl\s*=\s*([^\s]+)")
for repofile in self.get_repofile_list():
- ssh_result = self.ssh_client.run_command("cat /etc/yum.repos.d/{}".format(repofile))
+ ssh_result = self.ssh_client.run_command(f"cat /etc/yum.repos.d/{repofile}")
if ssh_result.failed:
# Something happened meanwhile?
continue
@@ -1225,13 +1225,13 @@ def write_repofile(self, repo_id, repo_url, **kwargs):
kwargs["gpgcheck"] = 0
if "enabled" not in kwargs:
kwargs["enabled"] = 1
- filename = "/etc/yum.repos.d/{}.repo".format(repo_id)
+ filename = f"/etc/yum.repos.d/{repo_id}.repo"
logger.info("Writing a new repofile %s %s", repo_id, repo_url)
- self.ssh_client.run_command('echo "[update-{}]" > {}'.format(repo_id, filename))
- self.ssh_client.run_command('echo "name=update-url-{}" >> {}'.format(repo_id, filename))
- self.ssh_client.run_command('echo "baseurl={}" >> {}'.format(repo_url, filename))
+ self.ssh_client.run_command(f'echo "[update-{repo_id}]" > {filename}')
+ self.ssh_client.run_command(f'echo "name=update-url-{repo_id}" >> {filename}')
+ self.ssh_client.run_command(f'echo "baseurl={repo_url}" >> {filename}')
for k, v in kwargs.items():
- self.ssh_client.run_command('echo "{}={}" >> {}'.format(k, v, filename))
+ self.ssh_client.run_command(f'echo "{k}={v}" >> {filename}')
return repo_id
def add_product_repo(self, repo_url, **kwargs):
@@ -1326,7 +1326,7 @@ def update_rhel(self, *urls, **kwargs):
# clean yum beforehand to clear metadata from earlier update repos, if any
try:
skip = '--skip-broken' if skip_broken else ''
- result = client.run_command('yum update -y --nogpgcheck {}'.format(skip),
+ result = client.run_command(f'yum update -y --nogpgcheck {skip}',
timeout=3600)
except socket.timeout:
msg = 'SSH timed out while updating appliance, exiting'
@@ -1337,7 +1337,7 @@ def update_rhel(self, *urls, **kwargs):
self.log.error(result.output)
if result.failed:
self.log.error('appliance update failed')
- msg = 'Appliance {} failed to update RHEL, error in logs'.format(self.hostname)
+ msg = f'Appliance {self.hostname} failed to update RHEL, error in logs'
log_callback(msg)
raise ApplianceException(msg)
@@ -1410,7 +1410,7 @@ def utc_time(self):
if result.success:
return dateutil.parser.parse(result.output)
else:
- raise Exception("Couldn't get datetime: {}".format(result.output))
+ raise Exception(f"Couldn't get datetime: {result.output}")
def _check_appliance_ui_wait_fn(self):
# Get the URL, don't verify ssl cert
@@ -1535,18 +1535,18 @@ def log_raise(exception_class, message):
# download
log_callback('Downloading VDDK')
- result = client.run_command('curl {} -o {}'.format(vddk_url, filename))
+ result = client.run_command(f'curl {vddk_url} -o {filename}')
if result.failed:
log_raise(Exception, "Could not download VDDK")
# install
log_callback('Installing vddk')
result = client.run_command(
- 'yum -y install {}'.format(filename))
+ f'yum -y install {filename}')
if result.failed:
log_raise(
Exception,
- 'VDDK installation failure (rc: {})\n{}'.format(result.rc, result.output)
+ f'VDDK installation failure (rc: {result.rc})\n{result.output}'
)
# verify
@@ -1599,23 +1599,23 @@ def log_raise(exception_class, message):
foldername = os.path.splitext(filename)[0]
with self.ssh_client as ssh:
- log_callback('Downloading SDK from {}'.format(sdk_url))
+ log_callback(f'Downloading SDK from {sdk_url}')
result = ssh.run_command(
'wget {url} -O {file} > /root/unzip.out 2>&1'.format(
url=sdk_url, file=filename))
if result.failed:
- log_raise(Exception, 'Could not download Netapp SDK: {}'.format(result.output))
+ log_raise(Exception, f'Could not download Netapp SDK: {result.output}')
- log_callback('Extracting SDK ({})'.format(filename))
+ log_callback(f'Extracting SDK ({filename})')
result = ssh.run_command(
- 'unzip -o -d /var/www/miq/vmdb/lib/ {}'.format(filename))
+ f'unzip -o -d /var/www/miq/vmdb/lib/ {filename}')
if result.failed:
- log_raise(Exception, 'Could not extract Netapp SDK: {}'.format(result.output))
+ log_raise(Exception, f'Could not extract Netapp SDK: {result.output}')
- path = '/var/www/miq/vmdb/lib/{}/lib/linux-64'.format(foldername)
+ path = f'/var/www/miq/vmdb/lib/{foldername}/lib/linux-64'
# Check if we haven't already added this line
- if ssh.run_command("grep -F '{}' /etc/default/evm".format(path)).failed:
- log_callback('Installing SDK ({})'.format(foldername))
+ if ssh.run_command(f"grep -F '{path}' /etc/default/evm").failed:
+ log_callback(f'Installing SDK ({foldername})')
result = ssh.run_command(
'echo "export LD_LIBRARY_PATH=\\$LD_LIBRARY_PATH:{}"'
'>> /etc/default/evm'.format(
@@ -1646,7 +1646,7 @@ def log_raise(exception_class, message):
@logger_wrap('Updating appliance UUID: {}')
def update_guid(self, log_callback=None):
guid_gen = 'uuidgen |tee /var/www/miq/vmdb/GUID'
- log_callback('Running {} to generate UUID'.format(guid_gen))
+ log_callback(f'Running {guid_gen} to generate UUID')
with self.ssh_client as ssh:
result = ssh.run_command(guid_gen)
assert result.success, 'Failed to generate UUID'
@@ -1789,7 +1789,7 @@ def guid(self):
try:
server = self.rest_api.get_entity_by_href(self.rest_api.server_info['server_href'])
return server.guid
- except (AttributeError, KeyError, IOError):
+ except (AttributeError, KeyError, OSError):
self.log.exception('appliance.guid could not be retrieved from REST, falling back')
result = self.ssh_client.run_command('cat /var/www/miq/vmdb/GUID')
return result.output
@@ -1799,7 +1799,7 @@ def evm_id(self):
try:
server = self.rest_api.get_entity_by_href(self.rest_api.server_info['server_href'])
return server.id
- except (AttributeError, KeyError, IOError):
+ except (AttributeError, KeyError, OSError):
self.log.exception('appliance.evm_id could not be retrieved from REST, falling back')
miq_servers = self.db.client['miq_servers']
return self.db.client.session.query(
@@ -1973,7 +1973,7 @@ def server_region_string(self):
self.product_name, r, r)
def region(self):
- return "Region {}".format(self.server.zone.region.number)
+ return f"Region {self.server.zone.region.number}"
def rename(self, new_name):
"""Changes appliance name
@@ -2115,7 +2115,7 @@ def set_cfme_server_relationship(self, vm_name, server_id=1):
def set_pglogical_replication(self, replication_type=':none'):
"""Set pglogical replication type (:none, :remote, :global) without using the Web UI."""
- command = ('MiqRegion.replication_type = {}'.format(replication_type))
+ command = (f'MiqRegion.replication_type = {replication_type}')
self.ssh_client.run_rails_console(command, timeout=None)
def add_pglogical_replication_subscription(self, host):
@@ -2147,7 +2147,7 @@ def set_rubyrep_replication(self, host, port=5432, database='vmdb_production',
dest['password'] = password
dest['port'] = port
dest['host'] = host
- logger.debug('Dest: {}'.format(yaml_data))
+ logger.debug(f'Dest: {yaml_data}')
self.update_advanced_settings(yaml_data)
def wait_for_miq_server_workers_started(self, evm_tail=None, poll_interval=5):
@@ -2163,7 +2163,7 @@ def wait_for_miq_server_workers_started(self, evm_tail=None, poll_interval=5):
detected = False
max_attempts = 60
while (not detected and attempts < max_attempts):
- logger.debug('Attempting to detect MIQ Server workers started: {}'.format(attempts))
+ logger.debug(f'Attempting to detect MIQ Server workers started: {attempts}')
for line in evm_tail:
if 'MiqServer#wait_for_started_workers' in line:
if ('All workers have been started' in line):
@@ -2186,7 +2186,7 @@ def use_dev_branch(self, repo, branch, log_callback=None):
branch: Branch of that repo
"""
with self.ssh_client as ssh_client:
- dev_branch_cmd = 'cd /var/www/miq/vmdb; git remote add dev_branch {}'.format(repo)
+ dev_branch_cmd = f'cd /var/www/miq/vmdb; git remote add dev_branch {repo}'
if not ssh_client.run_command(dev_branch_cmd):
ssh_client.run_command('cd /var/www/miq/vmdb; git remote remove dev_branch')
if not ssh_client.run_command(dev_branch_cmd):
@@ -2195,7 +2195,7 @@ def use_dev_branch(self, repo, branch, log_callback=None):
ssh_client.run_command('cd /var/www/miq/vmdb; git remote update')
self.evmserverd.stop()
ssh_client.run_command(
- 'cd /var/www/miq/vmdb; git checkout dev_branch/{}'.format(branch))
+ f'cd /var/www/miq/vmdb; git checkout dev_branch/{branch}')
ssh_client.run_command('cd /var/www/miq/vmdb; bin/update')
self.evmserverd.start()
self.evmserverd.wait_for_running()
@@ -2208,7 +2208,7 @@ def check_domain_enabled(self, domain):
try:
return list(q)[0].enabled
except IndexError:
- raise KeyError("No such Domain: {}".format(domain))
+ raise KeyError(f"No such Domain: {domain}")
@logger_wrap('Configuring openldap external auth provider')
def configure_openldap(self, auth_provider, log_callback=None):
@@ -2268,7 +2268,7 @@ def disable_openldap(self, log_callback=None):
self.CONF_FILES['httpd_remote_user']
]
for conf_file in files_to_remove:
- assert self.ssh_client.run_command('rm -f $(ls {})'.format(conf_file))
+ assert self.ssh_client.run_command(f'rm -f $(ls {conf_file})')
self.evmserverd.restart()
self.httpd.restart()
self.wait_for_web_ui()
@@ -2506,18 +2506,18 @@ def get_resolvable_hostname(self, log_callback=None):
# 137.3.2.1.in-addr.arpa domain name pointer 137.test.miq.com.
# [root@host-192-168-55-85 ~]# host 137.test.miq.com
# 137.test.miq.com has address 1.2.3.137
- host_check = self.ssh_client.run_command('host {}'.format(self.hostname), ensure_host=True)
- log_callback('Parsing for resolvable hostname from "{}"'.format(host_check.output))
+ host_check = self.ssh_client.run_command(f'host {self.hostname}', ensure_host=True)
+ log_callback(f'Parsing for resolvable hostname from "{host_check.output}"')
fqdn = None # just in case the logic gets weird
if host_check.success and 'domain name pointer' in host_check.output:
# resolvable and reverse lookup
# parse out the resolved hostname
fqdn = host_check.output.split(' ')[-1].rstrip('\n').rstrip('.')
- log_callback('Found FQDN by appliance IP: "{}"'.format(fqdn))
+ log_callback(f'Found FQDN by appliance IP: "{fqdn}"')
elif host_check.success and 'has address' in host_check.output:
# resolvable and address returned
fqdn = self.hostname
- log_callback('appliance hostname attr is FQDN: "{}"'.format(fqdn))
+ log_callback(f'appliance hostname attr is FQDN: "{fqdn}"')
else:
logger.warning('Bad RC from host command or unexpected output,'
' no resolvable hostname found')
@@ -2539,7 +2539,7 @@ def set_resolvable_hostname(self, log_callback=None):
"""
fqdn = self.get_resolvable_hostname()
if fqdn is not None:
- log_callback('Setting FQDN "{}" via appliance_console_cli'.format(fqdn))
+ log_callback(f'Setting FQDN "{fqdn}" via appliance_console_cli')
result = self.appliance_console_cli.set_hostname(str(fqdn))
return result.success
else:
@@ -2709,10 +2709,10 @@ def configure(self, log_callback=None, on_openstack=False, **kwargs):
``None`` (default ``None``)
on_openstack: If appliance is running on Openstack provider (default ``False``)
"""
- log_callback("Configuring appliance {} on {}".format(self.vm_name, self.provider_key))
+ log_callback(f"Configuring appliance {self.vm_name} on {self.provider_key}")
# Defer to the IPAppliance.
- super(Appliance, self).configure(log_callback=log_callback, on_openstack=on_openstack)
+ super().configure(log_callback=log_callback, on_openstack=on_openstack)
# TODO Can we remove this?
@logger_wrap("Configure fleecing: {}")
@@ -2829,7 +2829,7 @@ def set_ansible_url(self, log_callback=None):
@property
def _lun_name(self):
- return "{}LUNDISK".format(self.vm_name)
+ return f"{self.vm_name}LUNDISK"
def add_rhev_direct_lun_disk(self, log_callback=None):
if log_callback is None:
@@ -2843,7 +2843,7 @@ def add_rhev_direct_lun_disk(self, log_callback=None):
try:
self.mgmt.connect_direct_lun(lun_name=self._lun_name)
except Exception as e:
- log_callback("Appliance {} failed to connect RHEV direct LUN.".format(self.vm_name))
+ log_callback(f"Appliance {self.vm_name} failed to connect RHEV direct LUN.")
log_callback(str(e))
raise
@@ -2858,7 +2858,7 @@ def remove_rhev_direct_lun_disk(self, log_callback=None):
try:
self.mgmt.disconnect_disk(self._lun_name)
except Exception as e:
- log_callback("Appliance {} failed to connect RHEV direct LUN.".format(self.vm_name))
+ log_callback(f"Appliance {self.vm_name} failed to connect RHEV direct LUN.")
log_callback(str(e))
raise
@@ -2924,7 +2924,7 @@ def _get_latest_template():
logger.warning('No template found matching version %s, using %s instead.',
version, template_name)
else:
- raise ApplianceException('No template found matching version {}'.format(version))
+ raise ApplianceException(f'No template found matching version {version}')
else:
raise ApplianceException('Either version or template name must be specified')
@@ -2958,7 +2958,7 @@ class ApplianceStack(LocalStack):
def push(self, obj):
stack_parent = self.top
- super(ApplianceStack, self).push(obj)
+ super().push(obj)
logger.info(f"Pushed appliance hostname [{obj.hostname}] on stack \n"
f"Previous stack head was {getattr(stack_parent, 'hostname', 'empty')}")
@@ -2967,7 +2967,7 @@ def push(self, obj):
browser.start()
def pop(self):
- stack_parent = super(ApplianceStack, self).pop()
+ stack_parent = super().pop()
current = self.top
logger.info(f"Popped appliance {getattr(stack_parent, 'hostname', 'empty')} from stack\n"
f"Stack head is {getattr(current, 'hostname', 'empty')}")
@@ -3004,7 +3004,7 @@ def load_appliances(appliance_list, global_kwargs):
if not any(k in mapping for k in kwargs):
raise ValueError(
- "No valid IPAppliance kwargs found in config for appliance #{}".format(idx)
+ f"No valid IPAppliance kwargs found in config for appliance #{idx}"
)
appliance = IPAppliance(**{mapping[k]: v for k, v in kwargs.items() if k in mapping})
@@ -3039,7 +3039,7 @@ def collections_for_appliance(appliance):
@attr.s
-class DummyAppliance(object):
+class DummyAppliance:
"""a dummy with minimal attribute set"""
hostname = 'DummyApplianceHostname'
browser_steal = False
@@ -3150,12 +3150,12 @@ def get_or_create_current_appliance():
current_appliance = LocalProxy(get_or_create_current_appliance)
-class _CurrentAppliance(object):
+class _CurrentAppliance:
def __get__(self, instance, owner):
return get_or_create_current_appliance()
-class NavigatableMixin(object):
+class NavigatableMixin:
"""NavigatableMixin ensures that an object can navigate properly
The NavigatableMixin object ensures that a Collection/Entity object inside the
diff --git a/cfme/utils/appliance/console.py b/cfme/utils/appliance/console.py
index b96bd6357f..89db814510 100644
--- a/cfme/utils/appliance/console.py
+++ b/cfme/utils/appliance/console.py
@@ -48,8 +48,8 @@ def run_commands(self, commands, autoreturn=True, timeout=10, channel=None):
else:
cmd, timeout = command
channel.settimeout(timeout)
- cmd = "{}\n".format(cmd) if autoreturn else "{}".format(cmd)
- logger.info("Executing sub-command: %s, timeout:%s" % (cmd, timeout))
+ cmd = f"{cmd}\n" if autoreturn else f"{cmd}"
+ logger.info(f"Executing sub-command: {cmd}, timeout:{timeout}")
channel.send(cmd)
result = ''
try:
@@ -102,7 +102,7 @@ def scap_check_rules(self):
self.appliance.ssh_client.get_file(
'/tmp/scap-results.xccdf.xml', '/tmp/scap-results.xccdf.xml')
self.appliance.ssh_client.get_file(
- '{rules}'.format(rules=rules), '/tmp/scap_rules.yml') # Get the scap rules
+ f'{rules}', '/tmp/scap_rules.yml') # Get the scap rules
with open('/tmp/scap_rules.yml') as f:
yml = yaml.safe_load(f.read())
@@ -112,7 +112,7 @@ def scap_check_rules(self):
root = tree.getroot()
for rule in rules:
elements = root.findall(
- './/{{http://checklists.nist.gov/xccdf/1.1}}rule-result[@idref="{}"]'.format(rule))
+ f'.//{{http://checklists.nist.gov/xccdf/1.1}}rule-result[@idref="{rule}"]')
if elements:
result = elements[0].findall('./{http://checklists.nist.gov/xccdf/1.1}result')
if result:
@@ -120,9 +120,9 @@ def scap_check_rules(self):
rules_failures.append(rule)
logger.info("{}: {}".format(rule, result[0].text))
else:
- logger.info("{}: no result".format(rule))
+ logger.info(f"{rule}: no result")
else:
- logger.info("{}: rule not found".format(rule))
+ logger.info(f"{rule}: rule not found")
return rules_failures
def configure_primary_replication_node(self, pwd):
@@ -406,12 +406,12 @@ def answer_cluster_related_questions(interaction, node_uid, db_name,
class ApplianceConsoleCli(AppliancePlugin):
def _run(self, appliance_console_cli_command, timeout=35):
result = self.appliance.ssh_client.run_command(
- "appliance_console_cli {}".format(appliance_console_cli_command),
+ f"appliance_console_cli {appliance_console_cli_command}",
timeout)
return result
def set_hostname(self, hostname):
- return self._run("--host {host}".format(host=hostname), timeout=60)
+ return self._run(f"--host {hostname}", timeout=60)
def configure_appliance_external_join(self, dbhostname,
username, password, dbname, fetch_key, sshlogin, sshpass):
@@ -454,8 +454,8 @@ def configure_ipa(self, ipaserver, ipaprincipal, ipapassword, ipadomain=None, ip
cmd_result = self._run(
'--ipaserver {s} --ipaprincipal {u} --ipapassword {p} {d} {r}'
.format(s=ipaserver, u=ipaprincipal, p=ipapassword,
- d='--ipadomain {}'.format(ipadomain) if ipadomain else '',
- r='--iparealm {}'.format(iparealm) if iparealm else ''), timeout=90)
+ d=f'--ipadomain {ipadomain}' if ipadomain else '',
+ r=f'--iparealm {iparealm}' if iparealm else ''), timeout=90)
logger.debug('IPA configuration output: %s', str(cmd_result))
assert cmd_result.success
assert 'ipa-client-install exit code: 1' not in cmd_result.output
diff --git a/cfme/utils/appliance/db.py b/cfme/utils/appliance/db.py
index a94d9d8d3b..a9d0ae52b3 100644
--- a/cfme/utils/appliance/db.py
+++ b/cfme/utils/appliance/db.py
@@ -66,7 +66,7 @@ def address(self):
return self.appliance.hostname
else:
return db_addr
- except (IOError, KeyError) as exc:
+ except (OSError, KeyError) as exc:
self.logger.error('Unable to pull database address from appliance')
self.logger.error(exc)
return self.appliance.hostname
@@ -116,14 +116,14 @@ def create(self):
Note: EVM service has to be stopped for this to work.
"""
result = self.appliance.ssh_client.run_command('createdb vmdb_production', timeout=30)
- assert result.success, "Failed to create clean database: {}".format(result.output)
+ assert result.success, f"Failed to create clean database: {result.output}"
def migrate(self, env_vars=None):
"""migrates a given database and updates REGION/GUID files"""
env_vars = env_vars if env_vars else []
ssh = self.ssh_client
result = ssh.run_rake_command("db:migrate", rake_cmd_prefix=' '.join(env_vars), timeout=300)
- assert result.success, "Failed to migrate new database: {}".format(result.output)
+ assert result.success, f"Failed to migrate new database: {result.output}"
result = ssh.run_rake_command(
r'db:migrate:status 2>/dev/null | grep "^\s*down"', timeout=30)
assert result.failed, ("Migration failed; migrations in 'down' state found: {}"
@@ -137,29 +137,29 @@ def migrate(self, env_vars=None):
for data_type, db_query in data_query.items():
data_filepath = '/var/www/miq/vmdb/{}'.format(data_type.upper())
result = ssh.run_command(
- 'psql -d vmdb_production -t -c "{}"'.format(db_query), timeout=15)
- assert result.success, "Failed to fetch {}: {}".format(data_type, result.output)
+ f'psql -d vmdb_production -t -c "{db_query}"', timeout=15)
+ assert result.success, f"Failed to fetch {data_type}: {result.output}"
db_data = result.output.strip()
assert db_data, "No {} found in database; query '{}' returned no records".format(
data_type, db_query)
result = ssh.run_command(
- "echo -n '{}' > {}".format(db_data, data_filepath), timeout=15)
+ f"echo -n '{db_data}' > {data_filepath}", timeout=15)
assert result.success, "Failed to replace data in {} with '{}': {}".format(
data_filepath, db_data, result.output)
def automate_reset(self):
result = self.ssh_client.run_rake_command("evm:automate:reset", timeout=300)
- assert result.success, "Failed to reset automate: {}".format(result.output)
+ assert result.success, f"Failed to reset automate: {result.output}"
def fix_auth_key(self):
result = self.ssh_client.run_command("fix_auth -i invalid", timeout=45)
- assert result.success, "Failed to change invalid passwords: {}".format(result.output)
+ assert result.success, f"Failed to change invalid passwords: {result.output}"
# fix db password
def fix_auth_dbyml(self):
result = self.ssh_client.run_command("fix_auth --databaseyml -i {}".format(
credentials['database']['password']), timeout=45)
- assert result.success, "Failed to change invalid password: {}".format(result.output)
+ assert result.success, f"Failed to change invalid password: {result.output}"
def reset_user_pass(self):
result = self.ssh_client.run_rails_command(
@@ -208,7 +208,7 @@ def restore(self, database_path="/tmp/evm_db.backup"):
from cfme.utils.appliance import ApplianceException
self.logger.info('Restoring database')
result = self.appliance.ssh_client.run_rake_command(
- 'evm:db:restore:local --trace -- --local-file "{}"'.format(database_path))
+ f'evm:db:restore:local --trace -- --local-file "{database_path}"')
if result.failed:
msg = 'Failed to restore database on appl {}, output is {}'.format(self.address,
result.output)
@@ -222,7 +222,7 @@ def restore(self, database_path="/tmp/evm_db.backup"):
)
if result.failed:
self.logger.error(
- "Failed to change invalid db password: {}".format(result.output)
+ f"Failed to change invalid db password: {result.output}"
)
def setup(self, **kwargs):
@@ -258,7 +258,7 @@ def _run_cmd_show_output(self, cmd):
# Indent the output by 1 tab (makes it easier to read...)
if str(result):
output = str(result)
- output = '\n'.join(['\t{}'.format(line) for line in output.splitlines()])
+ output = '\n'.join([f'\t{line}' for line in output.splitlines()])
else:
output = ""
self.logger.info("Return code: %d, Output:\n%s", result.rc, output)
@@ -303,7 +303,7 @@ def _find_disk_with_free_space(self, needed_size):
disk_name = start = end = size = None
for disk in self.appliance.disks:
- result = self._run_cmd_show_output('parted {} unit GB print free'.format(disk))
+ result = self._run_cmd_show_output(f'parted {disk} unit GB print free')
if result.failed:
self.logger.error("Unable to run 'parted' on disk %s, skipping...", disk)
continue
@@ -354,7 +354,7 @@ def _create_partition_from_free_space(self, needed_size):
old_disks_and_parts = self.appliance.disks_and_partitions
result = self._run_cmd_show_output(
- 'parted {} --script mkpart primary {}GB {}GB'.format(disk, start, end))
+ f'parted {disk} --script mkpart primary {start}GB {end}GB')
if result.failed:
self.logger.error("Creating partition failed, aborting LVM creation!")
return
@@ -403,11 +403,11 @@ def create_db_lvm(self, size=5):
fstab_line = '/dev/mapper/dbvg-dblv $APPLIANCE_PG_MOUNT_POINT xfs defaults 0 0'
commands_to_run = [
- 'pvcreate {}'.format(partition),
- 'vgcreate dbvg {}'.format(partition),
- 'lvcreate --yes -n dblv --size {}G dbvg'.format(size),
+ f'pvcreate {partition}',
+ f'vgcreate dbvg {partition}',
+ f'lvcreate --yes -n dblv --size {size}G dbvg',
'mkfs.xfs /dev/dbvg/dblv',
- 'echo -e "{}" >> /etc/fstab'.format(fstab_line),
+ f'echo -e "{fstab_line}" >> /etc/fstab',
'mount -a'
]
@@ -438,7 +438,7 @@ def enable_internal(self, region=0, key_address=None, db_password=None, ssh_pass
Note:
If key_address is None, a new encryption key is generated for the appliance.
"""
- self.logger.info('Enabling internal DB (region {}) on {}.'.format(region, self.address))
+ self.logger.info(f'Enabling internal DB (region {region}) on {self.address}.')
self.address = self.appliance.hostname
clear_property_cache(self, 'client')
@@ -469,7 +469,7 @@ def enable_internal(self, region=0, key_address=None, db_password=None, ssh_pass
self.logger.warning('Failed to find a mounted DB disk, or a free unpartitioned disk.')
if self.appliance.has_cli:
- base_command = 'appliance_console_cli --region {}'.format(region)
+ base_command = f'appliance_console_cli --region {region}'
# use the cli
if key_address:
command_options = ('--internal --fetch-key {key} -p {db_pass} -a {ssh_pass}'
@@ -477,18 +477,18 @@ def enable_internal(self, region=0, key_address=None, db_password=None, ssh_pass
ssh_pass=ssh_password))
else:
- command_options = '--internal --force-key -p {db_pass}'.format(db_pass=db_password)
+ command_options = f'--internal --force-key -p {db_password}'
if db_disk:
# make sure the dbdisk is unmounted, RHOS ephemeral disks come up mounted
- result = client.run_command('umount {}'.format(db_disk))
+ result = client.run_command(f'umount {db_disk}')
if not result.success:
- self.logger.warning('umount non-zero return, output was: '.format(result))
- command_options = ' '.join([command_options, '--dbdisk {}'.format(db_disk)])
+ self.logger.warning(f'umount non-zero return, output was: ')
+ command_options = ' '.join([command_options, f'--dbdisk {db_disk}'])
result = client.run_command(' '.join([base_command, command_options]))
if result.failed or 'failed' in result.output.lower():
- raise Exception('Could not set up the database:\n{}'.format(result.output))
+ raise Exception(f'Could not set up the database:\n{result.output}')
else:
# no cli, use the enable internal db script
rbt_repl = {
@@ -508,8 +508,8 @@ def enable_internal(self, region=0, key_address=None, db_password=None, ssh_pass
client.put_file(rb.name, remote_file)
# Run the rb script, clean it up when done
- result = client.run_command('ruby {}'.format(remote_file))
- client.run_command('rm {}'.format(remote_file))
+ result = client.run_command(f'ruby {remote_file}')
+ client.run_command(f'rm {remote_file}')
self.logger.info('Output from appliance db configuration: %s', result.output)
@@ -573,8 +573,8 @@ def enable_external(self, db_address, region=0, db_name=None, db_username=None,
appliance_client.put_file(rb.name, remote_file)
# Run the rb script, clean it up when done
- result = appliance_client.run_command('ruby {}'.format(remote_file))
- appliance_client.run_command('rm {}'.format(remote_file))
+ result = appliance_client.run_command(f'ruby {remote_file}')
+ appliance_client.run_command(f'rm {remote_file}')
if result.failed:
self.logger.error('error enabling external db')
diff --git a/cfme/utils/appliance/implementations/__init__.py b/cfme/utils/appliance/implementations/__init__.py
index a7edc63165..0ecce2d58b 100644
--- a/cfme/utils/appliance/implementations/__init__.py
+++ b/cfme/utils/appliance/implementations/__init__.py
@@ -2,7 +2,7 @@
from cfme.utils.log import logger
-class Implementation(object):
+class Implementation:
"""UI implementation using the normal ux"""
navigator = None
diff --git a/cfme/utils/appliance/implementations/common.py b/cfme/utils/appliance/implementations/common.py
index e85b9337aa..45c1148b77 100644
--- a/cfme/utils/appliance/implementations/common.py
+++ b/cfme/utils/appliance/implementations/common.py
@@ -8,7 +8,7 @@
from cfme.utils.wait import wait_for
-class HandleModalsMixin(object):
+class HandleModalsMixin:
IGNORE_SUBSEQUENT_ALERTS = False
@property
def _modal_alert(self):
diff --git a/cfme/utils/appliance/implementations/rest.py b/cfme/utils/appliance/implementations/rest.py
index 15dd7ea5b0..315b08642d 100644
--- a/cfme/utils/appliance/implementations/rest.py
+++ b/cfme/utils/appliance/implementations/rest.py
@@ -1,6 +1,6 @@
-class ViaREST(object):
+class ViaREST:
name = "REST"
navigator = None
diff --git a/cfme/utils/appliance/implementations/ssui.py b/cfme/utils/appliance/implementations/ssui.py
index 8b02007d89..1d52ac8894 100644
--- a/cfme/utils/appliance/implementations/ssui.py
+++ b/cfme/utils/appliance/implementations/ssui.py
@@ -28,7 +28,7 @@ def __init__(self, selenium, endpoint, extra_objects=None):
'endpoint': endpoint,
'store': store,
})
- super(MiqSSUIBrowser, self).__init__(
+ super().__init__(
selenium,
plugin_class=MiqSSUIBrowserPlugin,
logger=create_sublogger('MiqSSUIBrowser'),
@@ -144,7 +144,7 @@ def do_nav(self, _tries=0, *args, **kwargs):
def log_message(self, msg, level="debug"):
class_name = self.obj.__name__ if isclass(self.obj) else self.obj.__class__.__name__
- str_msg = "[SUI-NAV/{}/{}]: {}".format(class_name, self._name, msg)
+ str_msg = f"[SUI-NAV/{class_name}/{self._name}]: {msg}"
getattr(logger, level)(str_msg)
def construct_message(self, here, resetter, view, duration, waited, force):
@@ -187,7 +187,7 @@ def go(self, _tries=0, *args, **kwargs):
"is_displayed not implemented for {} view".format(self.VIEW or ""), level="warn")
except Exception as e:
self.log_message(
- "Exception raised [{}] whilst checking if already here".format(e), level="error")
+ f"Exception raised [{e}] whilst checking if already here", level="error")
if not here or nav_args['force']:
if nav_args['force']:
@@ -206,7 +206,7 @@ def go(self, _tries=0, *args, **kwargs):
waited = True
wait_for(
lambda: view.is_displayed, num_sec=nav_args['wait_for_view'],
- message="Waiting for view [{}] to display".format(view.__class__.__name__)
+ message=f"Waiting for view [{view.__class__.__name__}] to display"
)
self.log_message(
self.construct_message(here, resetter_used, view, duration, waited, force_used),
diff --git a/cfme/utils/appliance/implementations/ui.py b/cfme/utils/appliance/implementations/ui.py
index cb45c93721..761d362c64 100644
--- a/cfme/utils/appliance/implementations/ui.py
+++ b/cfme/utils/appliance/implementations/ui.py
@@ -49,7 +49,7 @@ def get_rails_error(self):
"""Gets the displayed error messages"""
if self.browser.is_displayed("//body[./h1 and ./p and ./hr and ./address]"):
try:
- return "{}: {}".format(self.title.text, self.body.text)
+ return f"{self.title.text}: {self.body.text}"
except NoSuchElementException:
return None
elif self.browser.is_displayed(
@@ -238,7 +238,7 @@ def __init__(self, selenium, endpoint, extra_objects=None):
'endpoint': endpoint,
'store': store,
})
- super(MiqBrowser, self).__init__(
+ super().__init__(
selenium,
plugin_class=MiqBrowserPlugin,
logger=create_sublogger('MiqBrowser'),
@@ -403,7 +403,7 @@ def check_for_badness(self, fn, _tries, nav_args, *args, **kwargs):
try:
self.pre_badness_check(_tries, *args, **go_kwargs)
self.log_message(
- "Invoking {}, with {} and {}".format(fn.__name__, args, kwargs), level="debug")
+ f"Invoking {fn.__name__}, with {args} and {kwargs}", level="debug")
return fn(*args, **kwargs)
except (KeyboardInterrupt, ValueError):
# KeyboardInterrupt: Don't block this while navigating
@@ -459,13 +459,13 @@ def check_for_badness(self, fn, _tries, nav_args, *args, **kwargs):
req = br.widgetastic.text(req[0]) if req else "No request stated"
reason = br.widgetastic.elements("/html/body/p[2]/strong")
reason = br.widgetastic.text(reason[0]) if reason else "No reason stated"
- logger.info("Proxy error: {} / {}".format(req, reason))
+ logger.info(f"Proxy error: {req} / {reason}")
restart_evmserverd = True
elif br.widgetastic.is_displayed("//body[./h1 and ./p and ./hr and ./address]"):
# 503 and similar sort of errors
title = br.widgetastic.text("//body/h1")
body = br.widgetastic.text("//body/p")
- logger.exception("Application error {}: {}".format(title, body))
+ logger.exception(f"Application error {title}: {body}")
sleep(5) # Give it a little bit of rest
recycle = True
elif br.widgetastic.is_displayed("//body/div[@class='dialog' and ./h1 and ./p]"):
@@ -505,7 +505,7 @@ def check_for_badness(self, fn, _tries, nav_args, *args, **kwargs):
if recycle or restart_evmserverd:
self.appliance.browser.quit_browser()
- logger.debug('browser killed on try {}'.format(_tries))
+ logger.debug(f'browser killed on try {_tries}')
# If given a "start" nav destination, it won't be valid after quitting the browser
self.go(_tries, *args, **go_kwargs)
@@ -523,7 +523,7 @@ def post_navigate(self, *args, **kwargs):
def log_message(self, msg, level="debug"):
class_name = self.obj.__name__ if isclass(self.obj) else self.obj.__class__.__name__
- str_msg = "[UI-NAV/{}/{}]: {}".format(class_name, self._name, msg)
+ str_msg = f"[UI-NAV/{class_name}/{self._name}]: {msg}"
getattr(logger, level)(str_msg)
def construct_message(self, here, resetter, view, duration, waited, force):
@@ -564,7 +564,7 @@ def go(self, _tries=0, *args, **kwargs):
"is_displayed not implemented for {} view".format(self.VIEW or ""), level="warn")
except Exception as e:
self.log_message(
- "Exception raised [{}] whilst checking if already here".format(e), level="error")
+ f"Exception raised [{e}] whilst checking if already here", level="error")
if not here or nav_args['force']:
if nav_args['force']:
force_used = True
@@ -590,7 +590,7 @@ def go(self, _tries=0, *args, **kwargs):
waited = True
wait_for(
lambda: view.is_displayed, num_sec=nav_args['wait_for_view'],
- message="Waiting for view [{}] to display".format(view.__class__.__name__)
+ message=f"Waiting for view [{view.__class__.__name__}] to display"
)
self.log_message(
self.construct_message(here, resetter_used, view, duration, waited, force_used),
diff --git a/cfme/utils/appliance/plugin.py b/cfme/utils/appliance/plugin.py
index 638974d7e4..01fe8136ed 100644
--- a/cfme/utils/appliance/plugin.py
+++ b/cfme/utils/appliance/plugin.py
@@ -10,7 +10,7 @@ class AppliancePluginException(Exception):
@attr.s(slots=True)
-class AppliancePluginDescriptor(object):
+class AppliancePluginDescriptor:
cls = attr.ib()
args = attr.ib()
kwargs = attr.ib()
@@ -27,7 +27,7 @@ def __get__(self, o, t=None):
@attr.s
-class AppliancePlugin(object):
+class AppliancePlugin:
"""Base class for all appliance plugins.
Usage:
diff --git a/cfme/utils/appliance/services.py b/cfme/utils/appliance/services.py
index 0ab9182c29..43458ea915 100644
--- a/cfme/utils/appliance/services.py
+++ b/cfme/utils/appliance/services.py
@@ -37,7 +37,7 @@ def _run_service_command(
unit = self.unit_name if unit_name is None else unit_name
with self.appliance.ssh_client as ssh:
cmd = 'systemctl {} {}'.format(quote(command), quote(unit))
- log_callback('Running {}'.format(cmd))
+ log_callback(f'Running {cmd}')
result = ssh.run_command(cmd,
container=self.appliance.ansible_pod_name)
diff --git a/cfme/utils/auth/__init__.py b/cfme/utils/auth/__init__.py
index fb77ea50e6..7675c5c2d0 100644
--- a/cfme/utils/auth/__init__.py
+++ b/cfme/utils/auth/__init__.py
@@ -42,7 +42,7 @@ def auth_class_from_type(auth_prov_type):
try:
return auth_provider_types()[auth_prov_type]
except KeyError:
- raise UnknownProviderType('Unknown auth provider type: {}'.format(auth_prov_type))
+ raise UnknownProviderType(f'Unknown auth provider type: {auth_prov_type}')
def get_auth_crud(auth_prov_key):
@@ -56,7 +56,7 @@ def get_auth_crud(auth_prov_key):
auth_prov_config = auth_prov_data[auth_prov_key]
klass = auth_class_from_type(auth_prov_config.get('type'))
if auth_prov_config.get('type') != klass.auth_type:
- raise ValueError('{} must have type "{}"'.format(klass.__name__, klass.auth_type))
+ raise ValueError(f'{klass.__name__} must have type "{klass.auth_type}"')
return klass.from_config(auth_prov_config, auth_prov_key)
@@ -93,7 +93,7 @@ def auth_user_data(provider_key, user_type):
@attr.s
-class BaseAuthProvider(object):
+class BaseAuthProvider:
"""Base class for authentication provider objects """
auth_type = None
view_class = None
@@ -123,7 +123,7 @@ def from_config(cls, prov_config, prov_key):
def as_fill_value(self, user_type=None, auth_mode=None):
"""Basic implementation matches instance attributes to view form attributes"""
if user_type not in list(USER_TYPES.keys()):
- raise ValueError('invalid user_type "{}", must be key in USER_TYPES'.format(user_type))
+ raise ValueError(f'invalid user_type "{user_type}", must be key in USER_TYPES')
class_attrs = attr.fields_dict(type(self)) # dict of attr objects keyed by name
# attr filter needs the Attribute object
include_attrs = [class_attrs.get(name)
@@ -198,7 +198,7 @@ def as_fill_value(self, user_type='upn', auth_mode='ldap'):
user_type: key for USER_TYPES, used to lookup user_suffix
auth_mode: key for AUTH_MODES, used to lookup port
"""
- fill = super(MIQAuthProvider, self).as_fill_value(user_type=user_type, auth_mode=auth_mode)
+ fill = super().as_fill_value(user_type=user_type, auth_mode=auth_mode)
# Handle args that have multiple possibilities depending on user_type and auth_mode
if self.ports:
diff --git a/cfme/utils/blockers.py b/cfme/utils/blockers.py
index 4339f76343..26a588c8a6 100644
--- a/cfme/utils/blockers.py
+++ b/cfme/utils/blockers.py
@@ -12,7 +12,7 @@
from cfme.utils.log import logger
-class Blocker(object):
+class Blocker:
"""Base class for all blockers
REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values
@@ -64,7 +64,7 @@ def parse(cls, blocker, **kwargs):
# React to the typical JIRA format of FOO-42
return JIRA(blocker)
# EXTEND: If someone has other ideas, put them here
- raise ValueError("Could not parse blocker {}".format(blocker))
+ raise ValueError(f"Could not parse blocker {blocker}")
else:
raise ValueError("Wrong specification of the blockers!")
@@ -84,7 +84,7 @@ def github(cls):
return cls._github
def __init__(self, description, **kwargs):
- super(GH, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self._repo = None
self.issue = None
self.upstream_only = kwargs.get('upstream_only', False)
@@ -109,14 +109,14 @@ def __init__(self, description, **kwargs):
raise ValueError(
"Could not parse '{}' as a proper GH issue anchor!".format(str(description)))
else:
- self._repo = "{}/{}".format(owner, repo)
+ self._repo = f"{owner}/{repo}"
self.issue = int(issue_num)
else:
raise ValueError("GH issue specified wrong")
@property
def data(self):
- identifier = "{}:{}".format(self.repo, self.issue)
+ identifier = f"{self.repo}:{self.issue}"
if identifier not in self._issue_cache:
self._issue_cache[identifier] = self.github.get_repo(self.repo).get_issue(self.issue)
return self._issue_cache[identifier]
@@ -147,11 +147,11 @@ def repo(self):
return self._repo or self.DEFAULT_REPOSITORY
def __str__(self):
- return "GitHub Issue https://github.com/{}/issues/{}".format(self.repo, self.issue)
+ return f"GitHub Issue https://github.com/{self.repo}/issues/{self.issue}"
@property
def url(self):
- return "https://github.com/{}/issues/{}".format(self.repo, self.issue)
+ return f"https://github.com/{self.repo}/issues/{self.issue}"
class BZ(Blocker):
@@ -166,7 +166,7 @@ def bugzilla(cls):
def __init__(self, bug_id, **kwargs):
self.ignore_bugs = kwargs.pop("ignore_bugs", [])
- super(BZ, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.bug_id = int(bug_id)
@property
@@ -241,12 +241,12 @@ def blocks(self):
logger.error("Bugzilla thrown a fault: %s/%s", code, s)
logger.warning("Ignoring and taking the bug as non-blocking")
store.terminalreporter.write(
- "Bugzila made a booboo: {}/{}\n".format(code, s), bold=True)
+ f"Bugzila made a booboo: {code}/{s}\n", bold=True)
return False
def get_bug_url(self):
bz_url = urlparse(self.bugzilla.bugzilla.url)
- return "{}://{}/show_bug.cgi?id={}".format(bz_url.scheme, bz_url.netloc, self.bug_id)
+ return f"{bz_url.scheme}://{bz_url.netloc}/show_bug.cgi?id={self.bug_id}"
@property
def url(self):
@@ -268,7 +268,7 @@ def jira(cls): # noqa
return cls._jira
def __init__(self, jira_id, **kwargs):
- super(JIRA, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.jira_id = jira_id
@property
@@ -289,4 +289,4 @@ def blocks(self):
return issue.fields.status.name.lower() != 'done'
def __str__(self):
- return 'Jira card {}'.format(self.url)
+ return f'Jira card {self.url}'
diff --git a/cfme/utils/browser.py b/cfme/utils/browser.py
index d72acbf951..a20faf56c7 100644
--- a/cfme/utils/browser.py
+++ b/cfme/utils/browser.py
@@ -59,7 +59,7 @@ def _load_firefox_profile():
return profile
-class Wharf(object):
+class Wharf:
# class level to allow python level atomic removal of instance values
docker_id = None
@@ -76,7 +76,7 @@ def _get(self, *args):
return json.loads(response.content)
except ValueError:
raise ValueError(
- "JSON could not be decoded:\n{}".format(response.content))
+ f"JSON could not be decoded:\n{response.content}")
def checkout(self):
if self.docker_id is not None:
@@ -122,7 +122,7 @@ def __bool__(self):
return self.docker_id is not None
-class BrowserFactory(object):
+class BrowserFactory:
def __init__(self, webdriver_class, browser_kwargs):
self.webdriver_class = webdriver_class
self.browser_kwargs = browser_kwargs
@@ -174,7 +174,7 @@ def close(self, browser):
class WharfFactory(BrowserFactory):
def __init__(self, webdriver_class, browser_kwargs, wharf):
- super(WharfFactory, self).__init__(webdriver_class, browser_kwargs)
+ super().__init__(webdriver_class, browser_kwargs)
self.wharf = wharf
if browser_kwargs.get('desired_capabilities', {}).get('browserName') == 'chrome':
@@ -196,7 +196,7 @@ def processed_browser_args(self):
log.info(view_msg)
write_line(view_msg, cyan=True)
return dict(
- super(WharfFactory, self).processed_browser_args(),
+ super().processed_browser_args(),
command_executor=command_executor,
)
@@ -222,12 +222,12 @@ def inner():
def close(self, browser):
try:
- super(WharfFactory, self).close(browser)
+ super().close(browser)
finally:
self.wharf.checkin()
-class BrowserManager(object):
+class BrowserManager:
def __init__(self, browser_factory):
self.factory = browser_factory
self.browser = None
@@ -338,7 +338,7 @@ def open_fresh(self, url_key=None):
return self.browser
-class WithZoom(object):
+class WithZoom:
"""
This class is a decorator that used to wrap function with zoom level.
this class perform zoom by , call the target function and exit
diff --git a/cfme/utils/bz.py b/cfme/utils/bz.py
index a4ced241c7..5f0c35e2e3 100644
--- a/cfme/utils/bz.py
+++ b/cfme/utils/bz.py
@@ -15,7 +15,7 @@
NONE_FIELDS = {"---", "undefined", "unspecified"}
-class Product(object):
+class Product:
def __init__(self, data):
self._data = data
@@ -48,7 +48,7 @@ def latest_version(self):
return self.versions[-1]
-class Bugzilla(object):
+class Bugzilla:
def __init__(self, **kwargs):
# __kwargs passed to _Bugzilla instantiation, pop our args out
self.__product = kwargs.pop("product", None)
@@ -66,8 +66,7 @@ def bug_count(self):
@property
def bugs(self):
- for bug in self.__bug_cache.values():
- yield bug
+ yield from self.__bug_cache.values()
def products(self, *names):
return [Product(p) for p in self.bugzilla._proxy.Product.get({"names": names})["products"]]
@@ -143,9 +142,9 @@ def get_bug_variants(self, id):
bug = id
else:
bug = self.get_bug(id)
- expanded = set([])
- found = set([])
- stack = set([bug])
+ expanded = set()
+ found = set()
+ stack = {bug}
while stack:
b = stack.pop()
if b.status == "CLOSED" and b.resolution == "DUPLICATE":
@@ -163,7 +162,7 @@ def get_bug_variants(self, id):
def resolve_blocker(self, blocker, version=None, ignore_bugs=None, force_block_streams=None):
# ignore_bugs is mutable but is not mutated here! Same force_block_streams
force_block_streams = force_block_streams or []
- ignore_bugs = set([]) if not ignore_bugs else ignore_bugs
+ ignore_bugs = set() if not ignore_bugs else ignore_bugs
if isinstance(id, BugWrapper):
bug = blocker
else:
@@ -174,7 +173,7 @@ def resolve_blocker(self, blocker, version=None, ignore_bugs=None, force_block_s
version = bug.product.latest_version
is_upstream = version == bug.product.latest_version
variants = self.get_bug_variants(bug)
- filtered = set([])
+ filtered = set()
version_series = ".".join(str(version).split(".")[:2])
for variant in sorted(variants, key=lambda variant: variant.id):
if variant.id in ignore_bugs:
@@ -279,7 +278,7 @@ def check_fixed_in(fixed_in, version_series):
return fixed_in.is_in_series(version_series)
-class BugWrapper(object):
+class BugWrapper:
_copy_matchers = list(map(re.compile, [
r'^[+]{3}\s*This bug is a CFME zstream clone. The original bug is:\s*[+]{3}\n[+]{3}\s*'
r'https://bugzilla.redhat.com/show_bug.cgi\?id=(\d+)\.\s*[+]{3}',
diff --git a/cfme/utils/category.py b/cfme/utils/category.py
index 8a290c6332..5987b48129 100644
--- a/cfme/utils/category.py
+++ b/cfme/utils/category.py
@@ -1,7 +1,7 @@
"""Module used for handling categories of let's say form values and for categorizing them."""
-class CategoryBase(object):
+class CategoryBase:
"""Base class for categories
Args:
diff --git a/cfme/utils/db.py b/cfme/utils/db.py
index feae169423..d02990d521 100644
--- a/cfme/utils/db.py
+++ b/cfme/utils/db.py
@@ -95,7 +95,7 @@ def __getitem__(self, table_name):
try:
return self._table(table_name)
except InvalidRequestError:
- raise KeyError('Table {} could not be found'.format(table_name))
+ raise KeyError(f'Table {table_name} could not be found')
def __iter__(self):
"""Iterator of table names in this db"""
@@ -283,7 +283,7 @@ def _table(self, table_name):
return table_cls
except ArgumentError:
# This usually happens on join tables with no PKs
- logger.info('Unable to create table class for table "{}"'.format(table_name))
+ logger.info(f'Unable to create table class for table "{table_name}"')
return None
diff --git a/cfme/utils/dockerbot/check_prs.py b/cfme/utils/dockerbot/check_prs.py
index b94ae95b60..eddbb7217e 100755
--- a/cfme/utils/dockerbot/check_prs.py
+++ b/cfme/utils/dockerbot/check_prs.py
@@ -32,12 +32,12 @@
def send_message_to_bot(msg):
- required_fields = set(['rabbitmq_url', 'gh_queue', 'gh_channel', 'gh_message_type'])
+ required_fields = {'rabbitmq_url', 'gh_queue', 'gh_channel', 'gh_message_type'}
if not required_fields.issubset(docker_conf.keys()):
- logger.warning("Skipping - docker.yaml doesn't have {}".format(required_fields))
+ logger.warning(f"Skipping - docker.yaml doesn't have {required_fields}")
return
- logger.info("Github PR bot: about to send '{}'".format(msg))
+ logger.info(f"Github PR bot: about to send '{msg}'")
url = docker_conf['rabbitmq_url']
queue = docker_conf['gh_queue']
irc_channel = docker_conf['gh_channel']
@@ -53,7 +53,7 @@ def send_message_to_bot(msg):
body=json.dumps(message, ensure_ascii=True))
except Exception:
output = traceback.format_exc()
- logger.warning("Exception while sending a message to the bot: {}".format(output))
+ logger.warning(f"Exception while sending a message to the bot: {output}")
finally:
if connection:
connection.close()
@@ -70,8 +70,8 @@ def perform_request(url):
"""
out = {}
if token:
- headers = {'Authorization': 'token {}'.format(token)}
- full_url = "https://api.github.com/repos/{}/{}/{}".format(owner, repo, url)
+ headers = {'Authorization': f'token {token}'}
+ full_url = f"https://api.github.com/repos/{owner}/{repo}/{url}"
r = requests.get(full_url, headers=headers)
out = r.json()
return out
@@ -110,7 +110,7 @@ def create_run(db_pr, pr):
run_record = tapi.run.post(new_run)
for group in tapi.group.get(stream=True, use_for_prt=True)['objects']:
stream = group['name']
- logger.info(' Adding task stream {}...'.format(stream))
+ logger.info(f' Adding task stream {stream}...')
task_data = dict(output="",
tid=fauxfactory.gen_alphanumeric(8),
result="pending",
@@ -129,7 +129,7 @@ def check_prs():
numbers = []
while True:
- json_data = perform_request('pulls?per_page=100&page={}'.format(page))
+ json_data = perform_request(f'pulls?per_page=100&page={page}')
if not json_data:
break
for pr in json_data:
@@ -227,7 +227,7 @@ def vm_reaper():
appliance = Appliance.from_provider(task['provider'], task['vm_name'])
try:
if appliance.does_vm_exist():
- logger.info("Destroying {}".format(appliance.vm_name))
+ logger.info(f"Destroying {appliance.vm_name}")
appliance.destroy()
vm_cleanup = True
except Exception:
@@ -260,13 +260,13 @@ def set_status(commit, status, context, runid):
"""
data = {
"state": status,
- "description": "{} #{}".format(status, runid),
- "context": "ci/{}".format(context)
+ "description": f"{status} #{runid}",
+ "context": f"ci/{context}"
}
data_json = json.dumps(data)
if not DEBUG:
- headers = {'Authorization': 'token {}'.format(token)}
+ headers = {'Authorization': f'token {token}'}
requests.post("https://api.github.com/repos/{}/{}/commits/{}/statuses".format(
owner, repo, commit), data=data_json, headers=headers)
@@ -305,7 +305,7 @@ def check_status(pr):
try:
tasks = tapi.task.get(run=run_id)['objects']
- statuses = perform_request("commits/{}/statuses".format(commit))
+ statuses = perform_request(f"commits/{commit}/statuses")
for task in tasks:
for status in statuses:
if status['context'] == "ci/{}".format(task['stream']):
diff --git a/cfme/utils/dockerbot/dockerbot.py b/cfme/utils/dockerbot/dockerbot.py
index cf02c9f00e..e12ac6f277 100755
--- a/cfme/utils/dockerbot/dockerbot.py
+++ b/cfme/utils/dockerbot/dockerbot.py
@@ -37,7 +37,7 @@ def _name(docker_info):
**kwargs_from_env(assert_hostname=False))
-class DockerInstance(object):
+class DockerInstance:
def process_bindings(self, bindings):
self.port_bindings = {}
self.ports = []
@@ -120,7 +120,7 @@ def run(self):
print("Dry run running pytest")
-class DockerBot(object):
+class DockerBot:
def __init__(self, **args):
links = []
self.args = args
@@ -185,9 +185,9 @@ def get_base_branch(self, pr):
owner = self.args['gh_owner']
repo = self.args['gh_repo']
if token:
- headers = {'Authorization': 'token {}'.format(token)}
+ headers = {'Authorization': f'token {token}'}
r = requests.get(
- 'https://api.github.com/repos/{}/{}/pulls/{}'.format(owner, repo, pr),
+ f'https://api.github.com/repos/{owner}/{repo}/pulls/{pr}',
headers=headers)
return r.json()['base']['ref']
@@ -196,21 +196,21 @@ def get_dev_branch(self, pr=None):
owner = self.args['gh_dev_owner']
repo = self.args['gh_dev_repo']
if token:
- headers = {'Authorization': 'token {}'.format(token)}
+ headers = {'Authorization': f'token {token}'}
r = requests.get(
- 'https://api.github.com/repos/{}/{}/pulls/{}'.format(owner, repo, pr),
+ f'https://api.github.com/repos/{owner}/{repo}/pulls/{pr}',
headers=headers)
user, user_branch = r.json()['head']['label'].split(":")
- return "https://github.com/{}/{}.git".format(user, repo), user_branch
+ return f"https://github.com/{user}/{repo}.git", user_branch
def get_pr_metadata(self, pr=None):
token = self.args['gh_token']
owner = self.args['gh_owner']
repo = self.args['gh_repo']
if token:
- headers = {'Authorization': 'token {}'.format(token)}
+ headers = {'Authorization': f'token {token}'}
r = requests.get(
- 'https://api.github.com/repos/{}/{}/pulls/{}'.format(owner, repo, pr),
+ f'https://api.github.com/repos/{owner}/{repo}/pulls/{pr}',
headers=headers)
body = r.json()['body'] or ""
metadata = re.findall("{{(.*?)}}", body)
@@ -227,7 +227,7 @@ def find_files_by_pr(self, pr=None):
owner = self.args['gh_owner']
repo = self.args['gh_repo']
if token:
- headers = {'Authorization': 'token {}'.format(token)}
+ headers = {'Authorization': f'token {token}'}
page = 1
while True:
r = requests.get(
@@ -381,7 +381,7 @@ def display_banner(self):
def process_appliance(self):
self.appliance = self.args['appliance']
self.app_name = self.args.get('appliance_name', "Unnamed")
- print(" APPLIANCE: {} ({})".format(self.appliance, self.app_name))
+ print(f" APPLIANCE: {self.appliance} ({self.app_name})")
def create_pytest_command(self):
if self.args['auto_gen_test'] and self.args['pr']:
@@ -393,7 +393,7 @@ def create_pytest_command(self):
self.pr_metadata))
sprout_appliances = self.pr_metadata.get('sprouts', 1)
if pytest:
- self.args['pytest'] = "py.test {}".format(pytest)
+ self.args['pytest'] = f"py.test {pytest}"
else:
files = self.modified_files
if files:
@@ -408,14 +408,14 @@ def create_pytest_command(self):
self.base_branch = self.get_base_branch(self.args['pr']) or self.base_branch
if self.args['sprout'] and False:
- self.args['pytest'] += ' --use-sprout --sprout-appliances {}'.format(sprout_appliances)
+ self.args['pytest'] += f' --use-sprout --sprout-appliances {sprout_appliances}'
self.args['pytest'] += ' --sprout-group {}'.format(self.args['sprout_stream'])
self.args['pytest'] += ' --sprout-desc {}'.format(self.args['sprout_description'])
if not self.args['capture']:
self.args['pytest'] += ' --capture=no'
if self.args['dev_pr']:
repo, branch = self.get_dev_branch(self.args['dev_pr'])
- self.args['pytest'] += ' --dev-branch {} --dev-repo {}'.format(branch, repo)
+ self.args['pytest'] += f' --dev-branch {branch} --dev-repo {repo}'
print(" PYTEST Command: {}".format(self.args['pytest']))
def enc_key(self):
@@ -496,7 +496,7 @@ def create_log_path(self):
os.mkdir(log_path)
except OSError:
pass
- print(" LOG_ID: {}".format(self.pytest_name))
+ print(f" LOG_ID: {self.pytest_name}")
return log_path
def create_pytest_bindings(self):
diff --git a/cfme/utils/dockerbot/pytestbase/verify_commit.py b/cfme/utils/dockerbot/pytestbase/verify_commit.py
index 506d647182..64ce4d0dc5 100755
--- a/cfme/utils/dockerbot/pytestbase/verify_commit.py
+++ b/cfme/utils/dockerbot/pytestbase/verify_commit.py
@@ -17,10 +17,10 @@ def main():
if re.findall('^gpg: Good signature', output, re.M):
gpg = re.findall('fingerprint: ([A-F0-9 ]+)', output)[0].replace(' ', '')
if gpg in key_list:
- print("Good sig and match for {}".format(gpg))
+ print(f"Good sig and match for {gpg}")
sys.exit(0)
print("ERROR: Bad signature. Please sign your commits!")
- print("git output: {}".format(output))
+ print(f"git output: {output}")
sys.exit(127)
diff --git a/cfme/utils/dockerbot/sel_container.py b/cfme/utils/dockerbot/sel_container.py
index 66655bddc0..5cd761c0d6 100755
--- a/cfme/utils/dockerbot/sel_container.py
+++ b/cfme/utils/dockerbot/sel_container.py
@@ -16,7 +16,7 @@ def vnc_ready(addr, port):
"""Checks if VNC port is open and ready"""
try:
soc = socket.create_connection((addr, int(port)), timeout=2)
- except socket.error:
+ except OSError:
return False
# docker-proxy opens the port immediately after container is started.
# Receive data from the socket to check if VNC session is really running.
@@ -68,12 +68,12 @@ def main(watch, vnc, webdriver, image, vncviewer, random_ports):
viewer = viewer.replace('%I', ip).replace('%P', str(vnc))
ipport = None
else:
- ipport = '{}:{}'.format(ip, vnc)
+ ipport = f'{ip}:{vnc}'
cmd = viewer.split()
if ipport:
cmd.append(ipport)
else:
- cmd = ['xdg-open', 'vnc://{}:{}'.format(ip, vnc)]
+ cmd = ['xdg-open', f'vnc://{ip}:{vnc}']
subprocess.Popen(cmd)
print(" Hit Ctrl+C to end container")
diff --git a/cfme/utils/events.py b/cfme/utils/events.py
index 5eece4f68b..a56e6a7998 100644
--- a/cfme/utils/events.py
+++ b/cfme/utils/events.py
@@ -12,7 +12,7 @@
logger = create_sublogger('events')
-class EventAttr(object):
+class EventAttr:
""" EventAttr helps to compare event attributes with specific method.
Contains one event attribute and the method for comparing it.
@@ -42,7 +42,7 @@ def __repr__(self):
val=self.value, cmp=self.cmp_func)
-class Event(object):
+class Event:
""" Event represents either event received by REST API or an expected event.
:var TARGET_TYPES: Mapping of object types to REST API collections.
@@ -62,13 +62,13 @@ def __init__(self, appliance, *args):
if isinstance(arg, EventAttr):
self.add_attrs(arg)
else:
- logger.warning("arg {} doesn't belong to EventAttr. ignoring it".format(arg))
+ logger.warning(f"arg {arg} doesn't belong to EventAttr. ignoring it")
def __repr__(self):
- params = ", ".join(["{}={}".format(attr.name, attr.value)
+ params = ", ".join([f"{attr.name}={attr.value}"
for attr in
self.event_attrs.values()])
- return "BaseEvent({})".format(params)
+ return f"BaseEvent({params})"
def process_id(self):
""" Resolves target_id by target_type and target name."""
@@ -80,14 +80,14 @@ def process_id(self):
# Target type should be present in TARGET_TYPES
if target_type not in self.TARGET_TYPES:
raise TypeError(
- 'Type {} is not specified in the TARGET_TYPES.'.format(target_type))
+ f'Type {target_type} is not specified in the TARGET_TYPES.')
target_rest = self.TARGET_TYPES[target_type]
target_collection = getattr(self._appliance.rest_api.collections, target_rest)
o = target_collection.filter(Q('name', '=', target_name))
if not o.resources:
- raise ValueError('{} with name {} not found.'.format(target_type, target_name))
+ raise ValueError(f'{target_type} with name {target_name} not found.')
# Set target_id if target object was found
self.event_attrs['target_id'] = EventAttr(**{'target_id': o[0].id})
@@ -127,7 +127,7 @@ class RestEventListener(Thread):
FILTER_ATTRS = ['event_type', 'target_type', 'target_id', 'source']
def __init__(self, appliance):
- super(RestEventListener, self).__init__()
+ super().__init__()
self._appliance = appliance
self._events_to_listen = []
self._last_processed_id = 0 # this is used to filter out old or processed events
@@ -183,14 +183,14 @@ def listen_to(self, *evts, **kwargs):
'matched_events': [],
'first_event': first_event}
self._events_to_listen.append(exp_event)
- logger.info("event {} is added to listening queue.".format(evt))
+ logger.info(f"event {evt} is added to listening queue.")
else:
raise ValueError("one of events doesn't belong to Event class")
def start(self):
self._last_processed_id = self.get_max_record_id()
self._stop_event.clear()
- super(RestEventListener, self).start()
+ super().start()
logger.info('Event Listener has been started')
def stop(self):
@@ -199,7 +199,7 @@ def stop(self):
@property
def started(self):
- return super(RestEventListener, self).is_alive()
+ return super().is_alive()
def run(self):
""" Overrides ThreadEvent run to continuously process events"""
@@ -287,5 +287,5 @@ def __call__(self, *args, **kwargs):
else:
first_event = True
evt = self.new_event(*args, **kwargs)
- logger.info("registering event: {}".format(evt))
+ logger.info(f"registering event: {evt}")
self.listen_to(evt, callback=None, first_event=first_event)
diff --git a/cfme/utils/events_db.py b/cfme/utils/events_db.py
index 3a7024b9ca..65b40339b2 100644
--- a/cfme/utils/events_db.py
+++ b/cfme/utils/events_db.py
@@ -16,7 +16,7 @@
logger = create_sublogger('events')
-class EventTool(object):
+class EventTool:
"""EventTool serves as a wrapper to getting the events from the database.
:var OBJECT_TABLE: Mapping of object types to tables and column names.
"""
@@ -83,7 +83,7 @@ def process_id(self, target_type, target_name):
o = self.appliance.db.client.session.query(id_column).filter(
name_column == target_name).first()
if not o:
- raise ValueError('{} with name {} not found.'.format(target_type, target_name))
+ raise ValueError(f'{target_type} with name {target_name} not found.')
return o[0]
def query_miq_events(self, target_type=None, target_id=None, event_type=None, since=None,
@@ -144,10 +144,10 @@ def ensure_event_happens(self, target_type, target_id, event_type):
events = self.query_miq_events(target_type, target_id, event_type, time_started, time_ended)
if len(events) == 0:
raise AssertionError(
- 'Event {}/{}/{} did not happen.'.format(event_type, target_type, target_id))
+ f'Event {event_type}/{target_type}/{target_id} did not happen.')
-class EventAttr(object):
+class EventAttr:
"""
contains one event attribute and the method for comparing it.
"""
@@ -179,7 +179,7 @@ def __repr__(self):
# fixme: would it be better to create event prototype and just clone it ?
-class Event(object):
+class Event:
"""
represents either db event received by CFME and stored in event_streams or an expected event
"""
@@ -196,13 +196,13 @@ def __init__(self, event_tool, *args):
if isinstance(arg, EventAttr):
self.add_attrs(arg)
else:
- logger.warning("arg {} doesn't belong to EventAttr. ignoring it".format(arg))
+ logger.warning(f"arg {arg} doesn't belong to EventAttr. ignoring it")
def __repr__(self):
- params = ", ".join(["{}={}".format(attr.name, attr.value)
+ params = ", ".join([f"{attr.name}={attr.value}"
for attr in
self.event_attrs.values()])
- return "BaseEvent({})".format(params)
+ return f"BaseEvent({params})"
def _populate_defaults(self):
for attr_name, attr_type in self._tool.event_streams_attributes:
@@ -265,7 +265,7 @@ def add_attrs(self, *attrs):
logger.warning('The attribute {} type {} is absent in DB '
'or type mismatch.'.format(attr.name, attr.type))
else:
- raise ValueError("incorrect parameters are passed {}".format(attrs))
+ raise ValueError(f"incorrect parameters are passed {attrs}")
return self
def build_from_raw_event(self, evt):
@@ -284,7 +284,7 @@ class DbEventListener(Thread):
events. Runs callback function if expected events have it.
"""
def __init__(self, appliance):
- super(DbEventListener, self).__init__()
+ super().__init__()
self._appliance = appliance
self._tool = EventTool(self._appliance)
@@ -352,7 +352,7 @@ def listen_to(self, *evts, **kwargs):
if isinstance(evts, Iterable):
for evt in evts:
if isinstance(evt, Event):
- logger.info("event {} is added to listening queue".format(evt))
+ logger.info(f"event {evt} is added to listening queue")
self._events_to_listen.append({'event': evt,
'callback': callback,
'matched_events': [],
@@ -366,7 +366,7 @@ def start(self):
logger.info('Event Listener has been started')
self.set_last_record()
self._stop_event.clear()
- super(DbEventListener, self).start()
+ super().start()
def stop(self):
logger.info('Event Listener has been stopped')
@@ -377,7 +377,7 @@ def run(self):
@property
def started(self):
- return super(DbEventListener, self).is_alive()
+ return super().is_alive()
def process_events(self):
"""
@@ -390,7 +390,7 @@ def process_events(self):
sleep(0.2)
continue
for got_event in events:
- logger.debug("processing event id {}".format(got_event.id))
+ logger.debug(f"processing event id {got_event.id}")
got_event = Event(event_tool=self._tool).build_from_raw_event(got_event)
for exp_event in self._events_to_listen:
if exp_event['first_event'] and len(exp_event['matched_events']) > 0:
@@ -440,5 +440,5 @@ def __call__(self, *args, **kwargs):
else:
first_event = True
evt = self.new_event(*args, **kwargs)
- logger.info("registering event: {}".format(evt))
+ logger.info(f"registering event: {evt}")
self.listen_to(evt, callback=None, first_event=first_event)
diff --git a/cfme/utils/ftp.py b/cfme/utils/ftp.py
index 3626d74bbb..2e5dbcf7b4 100644
--- a/cfme/utils/ftp.py
+++ b/cfme/utils/ftp.py
@@ -27,7 +27,7 @@ class FTPException(Exception):
pass
-class FTPDirectory(object):
+class FTPDirectory:
""" FTP FS Directory encapsulation
This class represents one directory.
@@ -71,7 +71,7 @@ def path(self):
return os.path.join(self.parent_dir.path if self.parent_dir else "", self.name)
def __repr__(self):
- return "".format(self.path)
+ return f""
def cd(self, path):
""" Change to a directory
@@ -108,7 +108,7 @@ def cd(self, path):
return item.cd("/".join(remainder))
else:
return item
- raise FTPException("Directory {}{} does not exist!".format(self.path, enter))
+ raise FTPException(f"Directory {self.path}{enter} does not exist!")
def search(self, by, files=True, directories=True):
""" Recursive search by string or regexp.
@@ -146,7 +146,7 @@ def _scan(what, in_what):
return results
-class FTPFile(object):
+class FTPFile:
""" FTP FS File encapsulation
This class represents one file in the FS hierarchy.
@@ -189,7 +189,7 @@ def local_time(self):
return self.client.dt + self.time
def __repr__(self):
- return "".format(self.path)
+ return f""
def retr(self, callback):
""" Retrieve file
@@ -210,11 +210,11 @@ def retr(self, callback):
dirs = dirs.lstrip("/").split("/")
# Dive in
for d in dirs:
- assert self.client.cwd(d), "Could not change into the directory {}!".format(d)
+ assert self.client.cwd(d), f"Could not change into the directory {d}!"
self.client.retrbinary(f, callback)
# Dive out
for d in dirs:
- assert self.client.cdup(), "Could not get out of directory {}!".format(d)
+ assert self.client.cdup(), f"Could not get out of directory {d}!"
def download(self, target=None):
""" Download file into this machine
@@ -231,7 +231,7 @@ def download(self, target=None):
self.retr(output.write)
-class FTPClient(object):
+class FTPClient:
""" FTP Client encapsulation
This class provides basic encapsulation around ftplib's FTP class.
@@ -306,7 +306,7 @@ def update_time_difference(self):
void_file = BytesIO(b'random_example')
self.cwd(self.upload_dir)
assert "Transfer complete" in self.storbinary(TIMECHECK_FILE_NAME, void_file),\
- "Could not upload a file for time checking with name {}!".format(TIMECHECK_FILE_NAME)
+ f"Could not upload a file for time checking with name {TIMECHECK_FILE_NAME}!"
void_file.close()
now = datetime.now()
for d, name, time in self.ls():
@@ -376,7 +376,7 @@ def mkd(self, d):
"""
try:
- return self.ftp.sendcmd("MKD {}".format(d)).startswith("250")
+ return self.ftp.sendcmd(f"MKD {d}").startswith("250")
except ftplib.error_perm:
return False
@@ -391,7 +391,7 @@ def rmd(self, d):
"""
try:
- return self.ftp.sendcmd("RMD {}".format(d)).startswith("250")
+ return self.ftp.sendcmd(f"RMD {d}").startswith("250")
except ftplib.error_perm:
return False
@@ -406,7 +406,7 @@ def dele(self, f):
"""
try:
- return self.ftp.sendcmd("DELE {}".format(f)).startswith("250")
+ return self.ftp.sendcmd(f"DELE {f}").startswith("250")
except ftplib.error_perm:
return False
@@ -421,7 +421,7 @@ def cwd(self, d):
"""
try:
- return self.ftp.sendcmd("CWD {}".format(d)).startswith("250")
+ return self.ftp.sendcmd(f"CWD {d}").startswith("250")
except ftplib.error_perm:
return False
@@ -443,7 +443,7 @@ def retrbinary(self, f, callback):
f: Requested file name
callback: Callable with one parameter accepting the data
"""
- return self.ftp.retrbinary("RETR {}".format(f), callback)
+ return self.ftp.retrbinary(f"RETR {f}", callback)
def storbinary(self, f, file_obj):
""" Store file
@@ -454,7 +454,7 @@ def storbinary(self, f, file_obj):
f: Requested file name
file_obj: File object to be stored
"""
- return self.ftp.storbinary("STOR {}".format(f), file_obj)
+ return self.ftp.storbinary(f"STOR {f}", file_obj)
def recursively_delete(self, d=None):
""" Recursively deletes content of pwd
@@ -470,19 +470,19 @@ def recursively_delete(self, d=None):
"""
# Enter the directory
if d:
- assert self.cwd(d), "Could not enter directory {}".format(d)
+ assert self.cwd(d), f"Could not enter directory {d}"
# Work in it
for isdir, name, time in self.ls():
if isdir:
self.recursively_delete(name)
else:
- assert self.dele(name), "Could not delete {}!".format(name)
+ assert self.dele(name), f"Could not delete {name}!"
# Go out of it
if d:
# Go to parent directory
- assert self.cdup(), "Could not go to parent directory of {}!".format(d)
+ assert self.cdup(), f"Could not go to parent directory of {d}!"
# And delete it
- assert self.rmd(d), "Could not remove directory {}!".format(d)
+ assert self.rmd(d), f"Could not remove directory {d}!"
def tree(self, d=None):
""" Walks the tree recursively and creates a tree
@@ -507,7 +507,7 @@ def tree(self, d=None):
# Enter the directory
items = []
if d:
- assert self.cwd(d), "Could not enter directory {}".format(d)
+ assert self.cwd(d), f"Could not enter directory {d}"
# Work in it
for isdir, name, time in self.ls():
if isdir:
@@ -517,7 +517,7 @@ def tree(self, d=None):
# Go out of it
if d:
# Go to parent directory
- assert self.cdup(), "Could not go to parent directory of {}!".format(d)
+ assert self.cdup(), f"Could not go to parent directory of {d}!"
return items
@property
@@ -586,7 +586,7 @@ def __init__(self, entity_path=None, entrypoint=None, host=None, login=None, pas
self.entrypoint = entrypoint or ftp_data.entrypoint
self.entity_path = entity_path
- super(FTPClientWrapper, self).__init__(
+ super().__init__(
host=host, login=login, password=password, time_diff=False
)
@@ -609,7 +609,7 @@ def get_file(self, name):
if name in self.file_names:
return FTPFileWrapper(self, name=name, parent_dir=self.pwd())
else:
- raise FTPException("{} not found".format(name))
+ raise FTPException(f"{name} not found")
def files(self):
"""List of FTP file objects"""
diff --git a/cfme/utils/grafana.py b/cfme/utils/grafana.py
index 7c8d9a732b..3ee231254f 100644
--- a/cfme/utils/grafana.py
+++ b/cfme/utils/grafana.py
@@ -22,7 +22,7 @@ def get_scenario_dashboard_urls(scenario, from_ts, to_ts, output_to_log=True):
stub.format(g_ip, g_port, dashboard_name, from_ts, to_ts,
scenario['replication_master']['appliance_name'])
if output_to_log:
- logger.info('Grafana URLs: {}'.format(grafana_urls))
+ logger.info(f'Grafana URLs: {grafana_urls}')
return grafana_urls
else:
logger.warning('Grafana integration is not enabled')
diff --git a/cfme/utils/ipmi.py b/cfme/utils/ipmi.py
index 2e9cbfd854..78da14e695 100644
--- a/cfme/utils/ipmi.py
+++ b/cfme/utils/ipmi.py
@@ -49,7 +49,7 @@ def is_power_on(self):
elif "Chassis Power is off" in output:
return False
else:
- raise IPMIException("Unexpected command output: {}".format(output))
+ raise IPMIException(f"Unexpected command output: {output}")
def power_off(self):
""" Turns the power off.
@@ -84,7 +84,7 @@ def power_reset(self):
if "Reset" in output:
return True
else:
- raise Exception("Unexpected command output: {}".format(output))
+ raise Exception(f"Unexpected command output: {output}")
def _change_power_state(self, power_on=True):
""" Changes the power state of a machine.
@@ -106,7 +106,7 @@ def _change_power_state(self, power_on=True):
elif "Chassis Power Control: Down/Off" in output and not power_on:
return True
else:
- raise Exception("Unexpected command output: {}".format(output))
+ raise Exception(f"Unexpected command output: {output}")
def _run_command(self, command):
""" Builds the command arguments from the command string.
diff --git a/cfme/utils/log.py b/cfme/utils/log.py
index 92c7ebec11..02ba124513 100644
--- a/cfme/utils/log.py
+++ b/cfme/utils/log.py
@@ -159,7 +159,7 @@
logging.addLevelName(logging.TRACE, 'TRACE')
-class logger_wrap(object):
+class logger_wrap:
""" Sets up the logger by default, used as a decorator in utils.appliance
If the logger doesn't exist, sets up a sensible alternative
@@ -209,14 +209,14 @@ def __init__(self, prefix=None):
def filter(self, record):
if self.prefix:
- record.msg = "{0}{1}".format(safe_string(self.prefix), safe_string(record.msg))
+ record.msg = "{}{}".format(safe_string(self.prefix), safe_string(record.msg))
return True
class NamedLoggerAdapter(TraceLoggerAdapter):
"""An adapter that injects a name into log messages"""
def process(self, message, kwargs):
- return '({}) {}'.format(self.extra, message), kwargs
+ return f'({self.extra}) {message}', kwargs
def _load_conf(logger_name=None):
@@ -263,7 +263,7 @@ def filter(self, record):
return True
-class WarningsDeduplicationFilter(object):
+class WarningsDeduplicationFilter:
"""
this filter is needed since something in the codebase causes the warnings
once filter to be reset, so we need to deduplicate on our own
@@ -283,7 +283,7 @@ def filter(self, record):
return True
-class Perflog(object):
+class Perflog:
"""Performance logger, useful for timing arbitrary events by name
Logged events will be written to ``log/perf.log`` by default, unless
@@ -412,7 +412,7 @@ def format_marker(mstring, mark="-"):
"""
if len(mstring) <= MARKER_LEN - 2:
# Pad with spaces
- mstring = ' {} '.format(mstring)
+ mstring = f' {mstring} '
# Format centered, surrounded the leader_mark
format_spec = '{{:{leader_mark}^{marker_len}}}'\
.format(leader_mark=mark, marker_len=MARKER_LEN)
@@ -523,9 +523,9 @@ def setup_for_worker(workername, loggers=('cfme', 'py.warnings', 'wrapanapi')):
if isinstance(x, logging.FileHandler))
handler.close()
base, name = os.path.split(handler.baseFilename)
- add_prefix.prefix = "({})".format(workername)
+ add_prefix.prefix = f"({workername})"
handler.baseFilename = os.path.join(
- base, "{worker}-{name}".format(worker=workername, name=name))
+ base, f"{workername}-{name}")
log.debug("worker log started") # directly reopens the file
diff --git a/cfme/utils/log_validator.py b/cfme/utils/log_validator.py
index b5cd7bc158..fcb3cee58d 100644
--- a/cfme/utils/log_validator.py
+++ b/cfme/utils/log_validator.py
@@ -15,10 +15,10 @@ def __init__(self, pattern, message, line):
self.line = line
def __str__(self):
- return repr("Pattern '{p}': {m}".format(p=self.pattern, m=self.message))
+ return repr(f"Pattern '{self.pattern}': {self.message}")
-class LogValidator(object):
+class LogValidator:
"""
Log content validator class provides methods
to monitor the log content before test is started,
@@ -118,7 +118,7 @@ def matches(self):
self._check_fail_logs(line)
self._check_match_logs(line)
- logger.info("Matches found: {}".format(self._matches))
+ logger.info(f"Matches found: {self._matches}")
return self._matches
def validate(self, wait=None, message="waiting for log validation", **kwargs):
diff --git a/cfme/utils/net.py b/cfme/utils/net.py
index 176d88969e..acc01bc2a9 100644
--- a/cfme/utils/net.py
+++ b/cfme/utils/net.py
@@ -72,7 +72,7 @@ def net_check(port, addr=None, force=False, timeout=10):
# Then try to connect to the port
try:
socket.create_connection((addr, port), timeout=timeout).close() # immediately close
- except socket.error:
+ except OSError:
_ports[addr][port] = False
else:
_ports[addr][port] = True
@@ -126,7 +126,7 @@ def resolve_ips(host_iterable, force_dns=False):
to be converted to an IP. If that succeeds, it is appended to the set together with original
hostname. If it can't be resolved, just the original hostname is appended.
"""
- result = set([])
+ result = set()
for host in map(str, host_iterable):
result.add(host) # It is already an IP address
if ip_address.match(host) is None:
@@ -145,7 +145,7 @@ def is_pingable(ip_addr):
"""
try:
logger.info('Pinging address: %s', ip_addr)
- status = os.system("ping -c1 -w2 {} >/dev/null".format(ip_addr))
+ status = os.system(f"ping -c1 -w2 {ip_addr} >/dev/null")
if status == 0:
logger.info('IP: %s is RESPONDING !', ip_addr)
return True
@@ -240,10 +240,10 @@ def is_ipv4(ip_addr):
except AttributeError:
try:
socket.inet_aton(ip_addr)
- except socket.error:
+ except OSError:
return False
return ip_addr.count('.') == 3
- except socket.error:
+ except OSError:
return False
return True
@@ -258,7 +258,7 @@ def is_ipv6(ip_addr):
"""
try:
socket.inet_pton(socket.AF_INET6, ip_addr)
- except socket.error:
+ except OSError:
return False
return True
diff --git a/cfme/utils/ocp_cli.py b/cfme/utils/ocp_cli.py
index 86890e9d54..6a125bfc5b 100644
--- a/cfme/utils/ocp_cli.py
+++ b/cfme/utils/ocp_cli.py
@@ -3,7 +3,7 @@
from cfme.utils.ssh import SSHClient
-class OcpCli(object):
+class OcpCli:
"""This class provides CLI functionality for Openshift provider.
"""
def __init__(self, provider):
diff --git a/cfme/utils/perf.py b/cfme/utils/perf.py
index 2300ca58a9..afacfdae4f 100644
--- a/cfme/utils/perf.py
+++ b/cfme/utils/perf.py
@@ -13,34 +13,34 @@ def collect_log(ssh_client, log_prefix, local_file_name, strip_whitespace=False)
"""
log_dir = '/var/www/miq/vmdb/log/'
- log_file = '{}{}.log'.format(log_dir, log_prefix)
- dest_file = '{}{}.perf.log'.format(log_dir, log_prefix)
- dest_file_gz = '{}{}.perf.log.gz'.format(log_dir, log_prefix)
+ log_file = f'{log_dir}{log_prefix}.log'
+ dest_file = f'{log_dir}{log_prefix}.perf.log'
+ dest_file_gz = f'{log_dir}{log_prefix}.perf.log.gz'
- ssh_client.run_command('rm -f {}'.format(dest_file_gz))
+ ssh_client.run_command(f'rm -f {dest_file_gz}')
- result = ssh_client.run_command('ls -1 {}-*'.format(log_file))
+ result = ssh_client.run_command(f'ls -1 {log_file}-*')
if result.success:
files = result.output.strip().split('\n')
for lfile in sorted(files):
- ssh_client.run_command('cp {} {}-2.gz'.format(lfile, lfile))
- ssh_client.run_command('gunzip {}-2.gz'.format(lfile))
+ ssh_client.run_command(f'cp {lfile} {lfile}-2.gz')
+ ssh_client.run_command(f'gunzip {lfile}-2.gz')
if strip_whitespace:
ssh_client.run_command(r'sed -i \'s/^ *//; s/ *$//; /^$/d; /^\s*$/d\' {}-2'
.format(lfile))
- ssh_client.run_command('cat {}-2 >> {}'.format(lfile, dest_file))
- ssh_client.run_command('rm {}-2'.format(lfile))
+ ssh_client.run_command(f'cat {lfile}-2 >> {dest_file}')
+ ssh_client.run_command(f'rm {lfile}-2')
- ssh_client.run_command('cp {} {}-2'.format(log_file, log_file))
+ ssh_client.run_command(f'cp {log_file} {log_file}-2')
if strip_whitespace:
ssh_client.run_command(r'sed -i \'s/^ *//; s/ *$//; /^$/d; /^\s*$/d\' {}-2'
.format(log_file))
- ssh_client.run_command('cat {}-2 >> {}'.format(log_file, dest_file))
- ssh_client.run_command('rm {}-2'.format(log_file))
- ssh_client.run_command('gzip {}{}.perf.log'.format(log_dir, log_prefix))
+ ssh_client.run_command(f'cat {log_file}-2 >> {dest_file}')
+ ssh_client.run_command(f'rm {log_file}-2')
+ ssh_client.run_command(f'gzip {log_dir}{log_prefix}.perf.log')
ssh_client.get_file(dest_file_gz, local_file_name)
- ssh_client.run_command('rm -f {}'.format(dest_file_gz))
+ ssh_client.run_command(f'rm -f {dest_file_gz}')
def convert_top_mem_to_mib(top_mem):
@@ -89,7 +89,7 @@ def get_worker_pid(worker_type):
)
worker_pid = str(result.output).strip()
if result.output:
- logger.info('Obtained {} PID: {}'.format(worker_type, worker_pid))
+ logger.info(f'Obtained {worker_type} PID: {worker_pid}')
else:
logger.error('Could not obtain {} PID, check evmserverd running or if specific role is'
' enabled...'.format(worker_type))
@@ -101,7 +101,7 @@ def set_rails_loglevel(level, validate_against_worker='MiqUiWorker'):
"""Sets the logging level for level_rails and detects when change occured."""
ui_worker_pid = '#{}'.format(get_worker_pid(validate_against_worker))
- logger.info('Setting log level_rails on appliance to {}'.format(level))
+ logger.info(f'Setting log level_rails on appliance to {level}')
yaml = store.current_appliance.advanced_settings
if not str(yaml['log']['level_rails']).lower() == level.lower():
logger.info('Opening /var/www/miq/vmdb/log/evm.log for tail')
@@ -115,7 +115,7 @@ def set_rails_loglevel(level, validate_against_worker='MiqUiWorker'):
attempts = 0
detected = False
while (not detected and attempts < 60):
- logger.debug('Attempting to detect log level_rails change: {}'.format(attempts))
+ logger.debug(f'Attempting to detect log level_rails change: {attempts}')
for line in evm_tail:
if ui_worker_pid in line:
if 'Log level for production.log has been changed to' in line:
@@ -131,4 +131,4 @@ def set_rails_loglevel(level, validate_against_worker='MiqUiWorker'):
logger.error('Could not detect log level_rails change.')
evm_tail.close()
else:
- logger.info('Log level_rails already set to {}'.format(level))
+ logger.info(f'Log level_rails already set to {level}')
diff --git a/cfme/utils/perf_message_stats.py b/cfme/utils/perf_message_stats.py
index 4c65be1939..854f5a224a 100644
--- a/cfme/utils/perf_message_stats.py
+++ b/cfme/utils/perf_message_stats.py
@@ -332,21 +332,21 @@ def generate_hourly_charts_and_csvs(hourly_buckets, charts_dir):
lines['Get ' + cmd] = cmd_get
line_chart_render(cmd + ' Command Put/Get Count', 'Hour during ' + dt,
'# Count of Commands', linechartxaxis, lines,
- charts_dir.join('/{}-{}-cmdcnt.svg'.format(cmd, dt)))
+ charts_dir.join(f'/{cmd}-{dt}-cmdcnt.svg'))
lines = {}
lines['Average Dequeue Timing'] = avgdeqtimings
lines['Min Dequeue Timing'] = mindeqtimings
lines['Max Dequeue Timing'] = maxdeqtimings
line_chart_render(cmd + ' Dequeue Timings', 'Hour during ' + dt, 'Time (s)',
- linechartxaxis, lines, charts_dir.join('/{}-{}-dequeue.svg'.format(cmd, dt)))
+ linechartxaxis, lines, charts_dir.join(f'/{cmd}-{dt}-dequeue.svg'))
lines = {}
lines['Average Deliver Timing'] = avgdeltimings
lines['Min Deliver Timing'] = mindeltimings
lines['Max Deliver Timing'] = maxdeltimings
line_chart_render(cmd + ' Deliver Timings', 'Hour during ' + dt, 'Time (s)',
- linechartxaxis, lines, charts_dir.join('/{}-{}-deliver.svg'.format(cmd, dt)))
+ linechartxaxis, lines, charts_dir.join(f'/{cmd}-{dt}-deliver.svg'))
output_file.close()
@@ -374,7 +374,7 @@ def generate_total_time_charts(msg_cmds, charts_dir):
lines['Queue'] = msg_cmds[cmd]['queue']
lines['Execute'] = msg_cmds[cmd]['execute']
line_chart_render(cmd + ' Total Time', 'Message #', 'Time (s)', [], lines,
- charts_dir.join('/{}-total.svg'.format(cmd)))
+ charts_dir.join(f'/{cmd}-total.svg'))
def generate_worker_charts(workers, top_workers, charts_dir):
@@ -389,12 +389,12 @@ def generate_worker_charts(workers, top_workers, charts_dir):
lines['Shared Mem'] = top_workers[worker]['share']
line_chart_render(worker_name, 'Date Time', 'Memory in MiB',
top_workers[worker]['datetimes'], lines,
- charts_dir.join('/{}-Memory.svg'.format(worker_name)))
+ charts_dir.join(f'/{worker_name}-Memory.svg'))
lines = {}
lines['CPU %'] = top_workers[worker]['cpu_per']
line_chart_render(worker_name, 'Date Time', 'CPU Usage', top_workers[worker]['datetimes'],
- lines, charts_dir.join('/{}-CPU.svg'.format(worker_name)))
+ lines, charts_dir.join(f'/{worker_name}-CPU.svg'))
def get_first_miqtop(top_log_file):
@@ -563,7 +563,7 @@ def messages_to_statistics_csv(messages, statistics_file_name):
headers = ['cmd', 'puts', 'gets']
for measurement in measurements:
for metric in metrics:
- headers.append('{}_{}'.format(measurement, metric))
+ headers.append(f'{measurement}_{metric}')
csvfile.writerow(headers)
@@ -638,7 +638,7 @@ def top_to_appliance(top_file):
top_keys = ['datetimes', 'cpuus', 'cpusy', 'cpuni', 'cpuid', 'cpuwa', 'cpuhi', 'cpusi', 'cpust',
'memtot', 'memuse', 'memfre', 'buffer', 'swatot', 'swause', 'swafre', 'cached']
- top_app = dict((key, []) for key in top_keys)
+ top_app = {key: [] for key in top_keys}
cur_time = None
miqtop_ahead = True
@@ -721,7 +721,7 @@ def top_to_workers(workers, top_file):
grep_pids = ''
for wkr in workers:
grep_pids = r'{}^{}\s\\|'.format(grep_pids, workers[wkr].pid)
- grep_pattern = r'{}^top\s\-\s\\|^miqtop\:'.format(grep_pids)
+ grep_pattern = fr'{grep_pids}^top\s\-\s\\|^miqtop\:'
# Use grep to reduce # of lines to sort through
p = subprocess.Popen(['grep', grep_pattern, top_file], stdout=subprocess.PIPE)
greppedtop, err = p.communicate()
@@ -928,19 +928,19 @@ def perf_process_evm(evm_file, top_file):
cpu_mem_charts[1]))
html_menu.write('Worker CPU/Memory
')
- html_menu.write('Parsed {} lines for messages
'.format(msg_lc))
- html_menu.write('Start Time: {}
'.format(test_start))
- html_menu.write('End Time: {}
'.format(test_end))
+ html_menu.write(f'Parsed {msg_lc} lines for messages
')
+ html_menu.write(f'Start Time: {test_start}
')
+ html_menu.write(f'End Time: {test_end}
')
html_menu.write('Message Count: {}
'.format(len(messages)))
html_menu.write('Command Count: {}
'.format(len(msg_cmds)))
- html_menu.write('Parsed {} lines for workers
'.format(wkr_lc))
+ html_menu.write(f'Parsed {wkr_lc} lines for workers
')
html_menu.write('Total Workers: {}
'.format(len(workers)))
- html_menu.write('Workers Memory Exceeded: {}
'.format(wkr_mem_exc))
- html_menu.write('Workers Uptime Exceeded: {}
'.format(wkr_upt_exc))
- html_menu.write('Workers Exited: {}
'.format(wkr_ext))
- html_menu.write('Workers Stopped: {}
'.format(wkr_stp))
- html_menu.write('Workers Interrupted: {}
'.format(wkr_int))
+ html_menu.write(f'Workers Memory Exceeded: {wkr_mem_exc}
')
+ html_menu.write(f'Workers Uptime Exceeded: {wkr_upt_exc}
')
+ html_menu.write(f'Workers Exited: {wkr_ext}
')
+ html_menu.write(f'Workers Stopped: {wkr_stp}
')
+ html_menu.write(f'Workers Interrupted: {wkr_int}
')
html_menu.write('messages-rawdata.csv
')
html_menu.write('messages-statistics.csv
')
@@ -956,7 +956,7 @@ def perf_process_evm(evm_file, top_file):
if dt == '':
html_menu.write('Queued: ')
else:
- html_menu.write('{}: '.format(dt))
+ html_menu.write(f'{dt}: ')
html_menu.write(''
'cnt | '.format(cmd, dt))
html_menu.write(''
@@ -980,19 +980,19 @@ def perf_process_evm(evm_file, top_file):
cpu_mem_charts[1]))
html_wkr_menu.write('Message Latencies
')
- html_wkr_menu.write('Parsed {} lines for messages
'.format(msg_lc))
- html_wkr_menu.write('Start Time: {}
'.format(test_start))
- html_wkr_menu.write('End Time: {}
'.format(test_end))
+ html_wkr_menu.write(f'Parsed {msg_lc} lines for messages
')
+ html_wkr_menu.write(f'Start Time: {test_start}
')
+ html_wkr_menu.write(f'End Time: {test_end}
')
html_wkr_menu.write('Message Count: {}
'.format(len(messages)))
html_wkr_menu.write('Command Count: {}
'.format(len(msg_cmds)))
- html_wkr_menu.write('Parsed {} lines for workers
'.format(wkr_lc))
+ html_wkr_menu.write(f'Parsed {wkr_lc} lines for workers
')
html_wkr_menu.write('Total Workers: {}
'.format(len(workers)))
- html_wkr_menu.write('Workers Memory Exceeded: {}
'.format(wkr_mem_exc))
- html_wkr_menu.write('Workers Uptime Exceeded: {}
'.format(wkr_upt_exc))
- html_wkr_menu.write('Workers Exited: {}
'.format(wkr_ext))
- html_wkr_menu.write('Workers Stopped: {}
'.format(wkr_stp))
- html_wkr_menu.write('Workers Interrupted: {}
'.format(wkr_int))
+ html_wkr_menu.write(f'Workers Memory Exceeded: {wkr_mem_exc}
')
+ html_wkr_menu.write(f'Workers Uptime Exceeded: {wkr_upt_exc}
')
+ html_wkr_menu.write(f'Workers Exited: {wkr_ext}
')
+ html_wkr_menu.write(f'Workers Stopped: {wkr_stp}
')
+ html_wkr_menu.write(f'Workers Interrupted: {wkr_int}
')
html_wkr_menu.write('messages-rawdata.csv
')
html_wkr_menu.write(''
@@ -1005,9 +1005,9 @@ def perf_process_evm(evm_file, top_file):
if workers[worker_id].terminated == '':
if not w_type == workers[worker_id].worker_type:
w_type = workers[worker_id].worker_type
- html_wkr_menu.write('{}
'.format(w_type))
+ html_wkr_menu.write(f'{w_type}
')
worker_name = '{}-{}'.format(worker_id, workers[worker_id].worker_type)
- html_wkr_menu.write('{} - '.format(worker_id))
+ html_wkr_menu.write(f'{worker_id} - ')
html_wkr_menu.write('CPU'
' | '.format(worker_name))
html_wkr_menu.write('Memory
'
@@ -1019,9 +1019,9 @@ def perf_process_evm(evm_file, top_file):
if not workers[worker_id].terminated == '':
if not w_type == workers[worker_id].worker_type:
w_type = workers[worker_id].worker_type
- html_wkr_menu.write('
{}
'.format(w_type))
+ html_wkr_menu.write(f'
{w_type}
')
worker_name = '{}-{}'.format(worker_id, workers[worker_id].worker_type)
- html_wkr_menu.write('{} - '.format(worker_id))
+ html_wkr_menu.write(f'{worker_id} - ')
html_wkr_menu.write('CPU'
' | '.format(worker_name))
html_wkr_menu.write('Memory
'
@@ -1036,7 +1036,7 @@ def perf_process_evm(evm_file, top_file):
logger.info('Total time processing evm log file and generating report: %s', timediff)
-class MiqMsgStat(object):
+class MiqMsgStat:
def __init__(self):
self.headers = ['msg_id', 'msg_cmd', 'msg_args', 'pid_put', 'pid_get', 'puttime', 'gettime',
@@ -1062,7 +1062,7 @@ def __str__(self):
str(self.del_time) + ' : ' + str(self.total_time)
-class MiqMsgLists(object):
+class MiqMsgLists:
def __init__(self):
self.cmd = ''
@@ -1073,7 +1073,7 @@ def __init__(self):
self.totaltimes = []
-class MiqMsgBucket(object):
+class MiqMsgBucket:
def __init__(self):
self.headers = ['date', 'hour', 'total_put', 'total_get', 'sum_deq', 'min_deq', 'max_deq',
'avg_deq', 'sum_del', 'min_del', 'max_del', 'avg_del']
@@ -1101,7 +1101,7 @@ def __str__(self):
+ ' : ' + str(self.min_del) + ' : ' + str(self.max_del) + ' : ' + str(self.avg_del)
-class MiqWorker(object):
+class MiqWorker:
def __init__(self):
self.headers = ['worker_id', 'worker_type', 'pid', 'start_ts', 'end_ts', 'terminated']
diff --git a/cfme/utils/ports.py b/cfme/utils/ports.py
index f4fac4295d..cea560e872 100644
--- a/cfme/utils/ports.py
+++ b/cfme/utils/ports.py
@@ -5,7 +5,7 @@
from cfme.utils.log import logger
-class Ports(object):
+class Ports:
SSH = 22
DB = 5432
diff --git a/cfme/utils/pretty.py b/cfme/utils/pretty.py
index 4eb53b19ac..0b68f57b4a 100644
--- a/cfme/utils/pretty.py
+++ b/cfme/utils/pretty.py
@@ -24,7 +24,7 @@ def x(o):
return x
-class Pretty(object):
+class Pretty:
"""A mixin that prints repr as . The
fields that will be printed should be stored in the class's
pretty_attrs attribute (none by default).
diff --git a/cfme/utils/providers.py b/cfme/utils/providers.py
index b6bed4e5e2..091d565b88 100644
--- a/cfme/utils/providers.py
+++ b/cfme/utils/providers.py
@@ -39,10 +39,10 @@ def load_setuptools_entrypoints():
continue
except VersionConflict as e:
raise Exception(
- "Plugin {} could not be loaded: {}!".format(ep.name, e))
+ f"Plugin {ep.name} could not be loaded: {e}!")
-class ProviderFilter(object):
+class ProviderFilter:
""" Filter used to obtain only providers matching given requirements
Args:
@@ -165,7 +165,7 @@ def _filter_restricted_version(self, provider):
version_restrictions = []
since_version = provider.data.get('since_version')
if since_version:
- version_restrictions.append('>= {}'.format(since_version))
+ version_restrictions.append(f'>= {since_version}')
restricted_version = provider.data.get('restricted_version')
if restricted_version:
version_restrictions.append(restricted_version)
@@ -184,7 +184,7 @@ def _filter_restricted_version(self, provider):
return False
break
else:
- raise Exception('Operator not found in {}'.format(restriction))
+ raise Exception(f'Operator not found in {restriction}')
return None
def __call__(self, provider):
@@ -308,7 +308,7 @@ def get_class_from_type(prov_type):
try:
return all_types()[prov_type]
except KeyError:
- raise UnknownProviderType("Unknown provider type: {}!".format(prov_type))
+ raise UnknownProviderType(f"Unknown provider type: {prov_type}!")
def get_crud(provider_key, appliance=None):
@@ -339,7 +339,7 @@ def get_crud_by_name(provider_name):
for provider_key, provider_data in providers_data.items():
if provider_data.get("name") == provider_name:
return get_crud(provider_key)
- raise NameError("Could not find provider {}".format(provider_name))
+ raise NameError(f"Could not find provider {provider_name}")
def get_mgmt(provider_key, providers=None, credentials=None):
@@ -401,8 +401,8 @@ def get_mgmt(provider_key, providers=None, credentials=None):
class UnknownProvider(Exception):
def __init__(self, provider_key, *args, **kwargs):
- super(UnknownProvider, self).__init__(provider_key, *args, **kwargs)
+ super().__init__(provider_key, *args, **kwargs)
self.provider_key = provider_key
def __str__(self):
- return 'Unknown provider: "{}"'.format(self.provider_key)
+ return f'Unknown provider: "{self.provider_key}"'
diff --git a/cfme/utils/rest.py b/cfme/utils/rest.py
index 91b95cc1a7..9bed01c997 100644
--- a/cfme/utils/rest.py
+++ b/cfme/utils/rest.py
@@ -62,7 +62,7 @@ def assert_response(
last_response.status_code, http_status)
else:
# No specific status_code specified, simply check if response was a success
- assert last_response, 'The request failed with {}'.format(last_response.status_code)
+ assert last_response, f'The request failed with {last_response.status_code}'
try:
content = last_response.json()
@@ -98,7 +98,7 @@ def _check_result(result):
)
task_message = getattr(task, 'message', '')
assert task.status.lower() == 'ok', (
- 'Task failed with status "{}", message "{}"'.format(task.status, task_message))
+ f'Task failed with status "{task.status}", message "{task_message}"')
if 'results' in content:
results = content['results']
@@ -132,7 +132,7 @@ def create_resource(rest_api, col_name, col_data, col_action='create', substr_se
action = getattr(collection.action, col_action)
except AttributeError:
raise OptionNotAvailable(
- "Action `{}` for {} is not implemented in this version".format(col_action, col_name))
+ f"Action `{col_action}` for {col_name} is not implemented in this version")
entities = action(*col_data)
action_response = rest_api.response
@@ -217,7 +217,7 @@ def query_resource_attributes(resource, soft_assert=None):
for attr in attrs_to_query:
try:
- response = rest_api.get('{}?attributes={}'.format(service_href, attr))
+ response = rest_api.get(f'{service_href}?attributes={attr}')
assert rest_api.response, 'Failed response'
except Exception as err:
failed.append(FailedRecord(attr, 'attribute', err, rest_api.response))
@@ -244,7 +244,7 @@ def query_resource_attributes(resource, soft_assert=None):
if soft_assert:
for failure in outcome.failed:
- soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format(
+ soft_assert(False, '{} "{}": status: {}, error: `{}`'.format(
failure.type, failure.name, failure.response.status_code, failure.error))
return outcome
diff --git a/cfme/utils/smem_memory_monitor.py b/cfme/utils/smem_memory_monitor.py
index 379b44b973..fc271b85e8 100644
--- a/cfme/utils/smem_memory_monitor.py
+++ b/cfme/utils/smem_memory_monitor.py
@@ -136,7 +136,7 @@
class SmemMemoryMonitor(Thread):
def __init__(self, ssh_client, scenario_data):
- super(SmemMemoryMonitor, self).__init__()
+ super().__init__()
self.ssh_client = ssh_client
self.scenario_data = scenario_data
self.grafana_urls = {}
@@ -165,7 +165,7 @@ def create_process_result(self, process_results, starttime, process_pid, process
process_results[process_name][process_pid][starttime]['swap'] = swap_mem
del memory_by_pid[process_pid]
else:
- logger.warning('Process {} PID, not found: {}'.format(process_name, process_pid))
+ logger.warning(f'Process {process_name} PID, not found: {process_pid}')
def get_appliance_memory(self, appliance_results, plottime):
# 5.5/5.6 - RHEL 7 / Centos 7
@@ -212,7 +212,7 @@ def get_evm_workers(self):
if len(pid_worker) == 2:
workers[pid_worker[0].strip()] = pid_worker[1].strip()
else:
- logger.error('Unexpected output from psql: {}'.format(worker))
+ logger.error(f'Unexpected output from psql: {worker}')
return workers
else:
return {}
@@ -264,9 +264,9 @@ def get_pids_memory(self):
memory_by_pid[pid]['name'] = values[6]
memory_by_pid[pid]['cmd'] = ' '.join(values[7:])
except Exception as e:
- logger.error('Processing smem output error: {}'.format(e.__class__.__name__, e))
- logger.error('Issue with pid: {} line: {}'.format(pid, line))
- logger.error('Complete smem output: {}'.format(result.output))
+ logger.error(f'Processing smem output error: {e.__class__.__name__}')
+ logger.error(f'Issue with pid: {pid} line: {line}')
+ logger.error(f'Complete smem output: {result.output}')
return memory_by_pid
def _real_run(self):
@@ -338,7 +338,7 @@ def _real_run(self):
self.create_process_result(process_results, plottime, pid,
'evm:dbsync:replicate', memory_by_pid)
else:
- logger.debug('Unaccounted for ruby pid: {}'.format(pid))
+ logger.debug(f'Unaccounted for ruby pid: {pid}')
timediff = time.time() - starttime
logger.debug('Monitoring sampled in {}s'.format(round(timediff, 4)))
@@ -356,7 +356,7 @@ def run(self):
try:
self._real_run()
except Exception as e:
- logger.error('Error in Monitoring Thread: {}'.format(e))
+ logger.error(f'Error in Monitoring Thread: {e}')
logger.error('{}'.format(traceback.format_exc()))
@@ -386,10 +386,10 @@ def create_report(scenario_data, appliance_results, process_results, use_slab, g
scenario_path = workload_path.join(scenario_data['scenario']['name'])
if os.path.exists(str(scenario_path)):
- logger.warning('Duplicate Workload-Scenario Name: {}'.format(scenario_path))
+ logger.warning(f'Duplicate Workload-Scenario Name: {scenario_path}')
scenario_path = workload_path.join('{}-{}'.format(time.strftime('%Y%m%d%H%M%S'),
scenario_data['scenario']['name']))
- logger.warning('Using: {}'.format(scenario_path))
+ logger.warning(f'Using: {scenario_path}')
os.mkdir(str(scenario_path))
mem_graphs_path = scenario_path.join('graphs')
@@ -409,7 +409,7 @@ def create_report(scenario_data, appliance_results, process_results, use_slab, g
with open(str(scenario_path.join('scenario.yml')), 'w') as scenario_file:
yaml.safe_dump(dict(scenario_data['scenario']), scenario_file, default_flow_style=False)
- generate_summary_csv(scenario_path.join('{}-summary.csv'.format(ver)), appliance_results,
+ generate_summary_csv(scenario_path.join(f'{ver}-summary.csv'), appliance_results,
process_results, provider_names, ver)
generate_raw_data_csv(mem_rawdata_path, appliance_results, process_results)
generate_summary_html(scenario_path, ver, appliance_results, process_results, scenario_data,
@@ -456,7 +456,7 @@ def generate_raw_data_csv(directory, appliance_results, process_results):
appliance_results[ts]['swap_total'], appliance_results[ts]['swap_free']))
for process_name in process_results:
for process_pid in process_results[process_name]:
- file_name = str(directory.join('{}-{}.csv'.format(process_pid, process_name)))
+ file_name = str(directory.join(f'{process_pid}-{process_name}.csv'))
with open(file_name, 'w') as csv_file:
csv_file.write('TimeStamp,RSS,PSS,USS,VSS,SWAP\n')
for ts in process_results[process_name][process_pid]:
@@ -467,14 +467,14 @@ def generate_raw_data_csv(directory, appliance_results, process_results):
process_results[process_name][process_pid][ts]['vss'],
process_results[process_name][process_pid][ts]['swap']))
timediff = time.time() - starttime
- logger.info('Generated Raw Data CSVs in: {}'.format(timediff))
+ logger.info(f'Generated Raw Data CSVs in: {timediff}')
def generate_summary_csv(file_name, appliance_results, process_results, provider_names,
version_string):
starttime = time.time()
with open(str(file_name), 'w') as csv_file:
- csv_file.write('Version: {}, Provider(s): {}\n'.format(version_string, provider_names))
+ csv_file.write(f'Version: {version_string}, Provider(s): {provider_names}\n')
csv_file.write('Measurement,Start of test,End of test\n')
start = list(appliance_results.keys())[0]
end = list(appliance_results.keys())[-1]
@@ -507,7 +507,7 @@ def generate_summary_csv(file_name, appliance_results, process_results, provider
summary_csv_measurement_dump(csv_file, process_results, 'swap')
timediff = time.time() - starttime
- logger.info('Generated Summary CSV in: {}'.format(timediff))
+ logger.info(f'Generated Summary CSV in: {timediff}')
def generate_summary_html(directory, version_string, appliance_results, process_results,
@@ -524,7 +524,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
scenario_data['test_name'].title()))
html_file.write('Appliance Roles: {}
\n'.format(
scenario_data['appliance_roles'].replace(',', ', ')))
- html_file.write('Provider(s): {}
\n'.format(provider_names))
+ html_file.write(f'Provider(s): {provider_names}
\n')
html_file.write('{}\n'.format(
scenario_data['appliance_ip'], scenario_data['appliance_name']))
if grafana_urls:
@@ -533,7 +533,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
' : {}'.format(grafana_urls[g_name],
g_name))
html_file.write('
\n')
- html_file.write('Summary CSV'.format(version_string))
+ html_file.write(f'Summary CSV')
html_file.write(' : Workload Info')
html_file.write(' : Graphs directory\n')
html_file.write(' : CSVs directory
\n')
@@ -574,7 +574,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('{} | \n'.format(round(appliance_results[end]['used'], 2)))
html_file.write('{} | \n'.format(round(growth, 2)))
html_file.write('{} | \n'.format(round(max_used_memory, 2)))
- html_file.write('{} | \n'.format(total_proc_count))
+ html_file.write(f'{total_proc_count} | \n')
html_file.write('\n')
# CFME/Miq Worker Results
@@ -595,8 +595,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('\n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -631,8 +631,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('ruby | \n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -653,8 +653,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('memcached | \n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -675,8 +675,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('postgres | \n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -697,8 +697,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('httpd | \n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -719,8 +719,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('collectd | \n')
html_file.write('{} | \n'.format(a_pids + r_pids))
- html_file.write('{} | \n'.format(a_pids))
- html_file.write('{} | \n'.format(r_pids))
+ html_file.write(f'{a_pids} | \n')
+ html_file.write(f'{r_pids} | \n')
html_file.write('{} | \n'.format(round(t_rss, 2)))
html_file.write('{} | \n'.format(round(t_pss, 2)))
html_file.write('{} | \n'.format(round(t_uss, 2)))
@@ -731,8 +731,8 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('
\n')
html_file.write('total | \n')
html_file.write('{} | \n'.format(t_a_pids + t_r_pids))
- html_file.write('{} | \n'.format(t_a_pids))
- html_file.write('{} | \n'.format(t_r_pids))
+ html_file.write(f'{t_a_pids} | \n')
+ html_file.write(f'{t_r_pids} | \n')
html_file.write('{} | \n'.format(round(tt_rss, 2)))
html_file.write('{} | \n'.format(round(tt_pss, 2)))
html_file.write('{} | \n'.format(round(tt_uss, 2)))
@@ -743,9 +743,9 @@ def generate_summary_html(directory, version_string, appliance_results, process_
# Appliance Graph
html_file.write('
\n')
- file_name = '{}-appliance_memory.png'.format(version_string)
- html_file.write('\n'.format(file_name))
- file_name = '{}-appliance_swap.png'.format(version_string)
+ file_name = f'{version_string}-appliance_memory.png'
+ html_file.write(f'\n')
+ file_name = f'{version_string}-appliance_swap.png'
# Check for swap usage through out time frame:
max_swap_used = 0
for ts in appliance_results:
@@ -753,10 +753,10 @@ def generate_summary_html(directory, version_string, appliance_results, process_
if swap_used > max_swap_used:
max_swap_used = swap_used
if max_swap_used < 10: # Less than 10MiB Max, then hide graph
- html_file.write(' Swap Graph '.format(file_name))
+ html_file.write(f' Swap Graph ')
html_file.write('(Hidden, max_swap_used < 10 MiB)\n')
else:
- html_file.write('\n'.format(file_name))
+ html_file.write(f'\n')
html_file.write(' |
\n')
# Per Process Results
html_file.write('\n')
@@ -787,7 +787,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('{} | \n'.format(
ordered_name, pid, pid))
else:
- html_file.write('{} | \n'.format(ordered_name))
+ html_file.write(f'{ordered_name} | \n')
html_file.write('{} | \n'.format(
ordered_name, pid, pid))
html_file.write('{} | \n'.format(start.replace(microsecond=0)))
@@ -811,7 +811,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
pid, ordered_name))
html_file.write(' \n')
else:
- logger.debug('Process/Worker not part of test: {}'.format(ordered_name))
+ logger.debug(f'Process/Worker not part of test: {ordered_name}')
html_file.write(' \n')
@@ -822,12 +822,12 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('Process name: {} \n'.format(
ordered_name, ordered_name))
if len(process_results[ordered_name]) > 1:
- file_name = '{}-all.png'.format(ordered_name)
+ file_name = f'{ordered_name}-all.png'
html_file.write(' \n'.format(file_name,
file_name))
else:
for pid in sorted(process_results[ordered_name]):
- file_name = '{}-{}.png'.format(ordered_name, pid)
+ file_name = f'{ordered_name}-{pid}.png'
html_file.write(' \n'.format(
file_name, file_name))
html_file.write(' |
\n')
@@ -836,7 +836,7 @@ def generate_summary_html(directory, version_string, appliance_results, process_
html_file.write('