unit tests (modules): use f-strings (#10992)

* unit tests (modules): use f-strings

* Apply suggestions from code review
This commit is contained in:
Alexei Znamensky
2025-10-27 11:08:33 +13:00
committed by GitHub
parent f6781f654e
commit e177d1e61a
33 changed files with 140 additions and 159 deletions

View File

@@ -55,7 +55,7 @@ def python_gitlab_version_match_requirement():
# Skip unittest test case if python version don't match requirement # Skip unittest test case if python version don't match requirement
def unitest_python_version_check_requirement(unittest_testcase): def unitest_python_version_check_requirement(unittest_testcase):
if not python_version_match_requirement(): if not python_version_match_requirement():
unittest_testcase.skipTest("Python %s+ is needed for python-gitlab" % ",".join(map(str, GITLAB_MINIMUM_PYTHON_VERSION))) unittest_testcase.skipTest(f"Python {'.'.join(map(str, GITLAB_MINIMUM_PYTHON_VERSION))}+ is needed for python-gitlab")
''' '''

View File

@@ -18,7 +18,7 @@ class OneViewBaseTest(object):
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setUp(self, mock_ansible_module, mock_ov_client, request): def setUp(self, mock_ansible_module, mock_ov_client, request):
marker = request.node.get_marker('resource') marker = request.node.get_marker('resource')
self.resource = getattr(mock_ov_client, "%s" % (marker.args)) self.resource = getattr(mock_ov_client, f"{marker.args}")
self.mock_ov_client = mock_ov_client self.mock_ov_client = mock_ov_client
self.mock_ansible_module = mock_ansible_module self.mock_ansible_module = mock_ansible_module
@@ -27,7 +27,7 @@ class OneViewBaseTest(object):
resource_name = type(self).__name__.replace('Test', '') resource_name = type(self).__name__.replace('Test', '')
resource_module_path_name = resource_name.replace('Module', '') resource_module_path_name = resource_name.replace('Module', '')
resource_module_path_name = re.findall('[A-Z][^A-Z]*', resource_module_path_name) resource_module_path_name = re.findall('[A-Z][^A-Z]*', resource_module_path_name)
resource_module_path_name = 'oneview_' + str.join('_', resource_module_path_name).lower() resource_module_path_name = f"oneview_{str.join('_', resource_module_path_name).lower()}"
ansible_collections = __import__('ansible_collections') ansible_collections = __import__('ansible_collections')
oneview_module = ansible_collections.community.general.plugins.modules oneview_module = ansible_collections.community.general.plugins.modules
@@ -40,7 +40,7 @@ class OneViewBaseTest(object):
EXAMPLES = yaml.safe_load(testing_module.EXAMPLES) EXAMPLES = yaml.safe_load(testing_module.EXAMPLES)
except yaml.scanner.ScannerError: except yaml.scanner.ScannerError:
message = "Something went wrong while parsing yaml from {0}.EXAMPLES".format(self.testing_class.__module__) message = f"Something went wrong while parsing yaml from {self.testing_class.__module__}.EXAMPLES"
raise Exception(message) raise Exception(message)
return testing_module return testing_module
@@ -114,7 +114,7 @@ class OneViewBaseTestCase(object):
self.mock_ov_client = self.mock_ov_client_from_json_file.return_value self.mock_ov_client = self.mock_ov_client_from_json_file.return_value
# Define Ansible Module Mock # Define Ansible Module Mock
patcher_ansible = patch(ONEVIEW_MODULE_UTILS_PATH + '.AnsibleModule') patcher_ansible = patch(f"{ONEVIEW_MODULE_UTILS_PATH}.AnsibleModule")
test_case.addCleanup(patcher_ansible.stop) test_case.addCleanup(patcher_ansible.stop)
mock_ansible_module = patcher_ansible.start() mock_ansible_module = patcher_ansible.start()
self.mock_ansible_module = Mock() self.mock_ansible_module = Mock()
@@ -142,7 +142,7 @@ class OneViewBaseTestCase(object):
self.EXAMPLES = yaml.safe_load(self.testing_module.EXAMPLES) self.EXAMPLES = yaml.safe_load(self.testing_module.EXAMPLES)
except yaml.scanner.ScannerError: except yaml.scanner.ScannerError:
message = "Something went wrong while parsing yaml from {0}.EXAMPLES".format(self.testing_class.__module__) message = f"Something went wrong while parsing yaml from {self.testing_class.__module__}.EXAMPLES"
raise Exception(message) raise Exception(message)

View File

@@ -29,7 +29,7 @@ class ModuleMocked:
move(src, dst) move(src, dst)
def backup_local(self, path): def backup_local(self, path):
backupp = os.path.join("/tmp", os.path.basename(path) + ".bak") backupp = os.path.join("/tmp", f"{os.path.basename(path)}.bak")
copyfile(path, backupp) copyfile(path, backupp)
return backupp return backupp
@@ -68,12 +68,12 @@ class TestInterfacesFileModule(unittest.TestCase):
def compareInterfacesLinesToFile(self, interfaces_lines, path, testname=None): def compareInterfacesLinesToFile(self, interfaces_lines, path, testname=None):
if not testname: if not testname:
testname = "%s.%s" % (path, inspect.stack()[1][3]) testname = f"{path}.{inspect.stack()[1][3]}"
self.compareStringWithFile("".join([d['line'] for d in interfaces_lines if 'line' in d]), testname) self.compareStringWithFile("".join([d['line'] for d in interfaces_lines if 'line' in d]), testname)
def compareInterfacesToFile(self, ifaces, path, testname=None): def compareInterfacesToFile(self, ifaces, path, testname=None):
if not testname: if not testname:
testname = "%s.%s.json" % (path, inspect.stack()[1][3]) testname = f"{path}.{inspect.stack()[1][3]}.json"
testfilepath = os.path.join(golden_output_path, testname) testfilepath = os.path.join(golden_output_path, testname)
string = json.dumps(ifaces, sort_keys=True, indent=4, separators=(',', ': ')) string = json.dumps(ifaces, sort_keys=True, indent=4, separators=(',', ': '))
@@ -196,12 +196,12 @@ class TestInterfacesFileModule(unittest.TestCase):
dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'], dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'],
options['value'], options['state']) options['value'], options['state'])
except AnsibleFailJson as e: except AnsibleFailJson as e:
fail_json_iterations.append("[%d] fail_json message: %s\noptions:\n%s" % fail_json_iterations.append(
(i, str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) f"[{i}] fail_json message: {e!s}\noptions:\n{json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))}")
self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname)) self.compareStringWithFile("\n=====\n".join(fail_json_iterations), f"{testfile}_{testname}.exceptions.txt")
self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname)) self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}")
self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json")
def test_revert(self): def test_revert(self):
testcases = { testcases = {
@@ -229,14 +229,14 @@ class TestInterfacesFileModule(unittest.TestCase):
dummy, lines = interfaces_file.set_interface_option(module, lines, dummy, lines = interfaces_file.set_interface_option(module, lines,
options['iface'], options['option'], options['value'], options['state']) options['iface'], options['option'], options['value'], options['state'])
except AnsibleFailJson as e: except AnsibleFailJson as e:
fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % fail_json_iterations.append(
(str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) f"fail_json message: {e!s}\noptions:\n{json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))}")
interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path) interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path)
self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname)) self.compareStringWithFile("\n=====\n".join(fail_json_iterations), f"{testfile}_{testname}.exceptions.txt")
self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname)) self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}")
self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json")
if testfile not in ["no_leading_spaces"]: if testfile not in ["no_leading_spaces"]:
# skip if eth0 has MTU value # skip if eth0 has MTU value
self.compareFileToBackup(path, backupp) self.compareFileToBackup(path, backupp)
@@ -270,17 +270,16 @@ class TestInterfacesFileModule(unittest.TestCase):
changed_again, lines = interfaces_file.set_interface_option(module, lines, options['iface'], changed_again, lines = interfaces_file.set_interface_option(module, lines, options['iface'],
options['option'], options['value'], options['state']) options['option'], options['value'], options['state'])
self.assertFalse(changed_again, self.assertFalse(changed_again,
msg='Second request for change should return false for {0} running on {1}'.format(testname, msg=f'Second request for change should return false for {testname} running on {testfile}')
testfile))
except AnsibleFailJson as e: except AnsibleFailJson as e:
fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % fail_json_iterations.append(
(str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) f"fail_json message: {e!s}\noptions:\n{json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))}")
interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path) interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path)
self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname)) self.compareStringWithFile("\n=====\n".join(fail_json_iterations), f"{testfile}_{testname}.exceptions.txt")
self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname)) self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}")
self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json")
# Restore backup # Restore backup
move(backupp, path) move(backupp, path)
@@ -544,13 +543,13 @@ class TestInterfacesFileModule(unittest.TestCase):
dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'], dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'],
options['value'], options['state'], options['address_family']) options['value'], options['state'], options['address_family'])
except AnsibleFailJson as e: except AnsibleFailJson as e:
fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % fail_json_iterations.append(
(str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) f"fail_json message: {e!s}\noptions:\n{json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))}")
interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path) interfaces_file.write_changes(module, [d['line'] for d in lines if 'line' in d], path)
self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname)) self.compareStringWithFile("\n=====\n".join(fail_json_iterations), f"{testfile}_{testname}.exceptions.txt")
self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname)) self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}")
self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json")
# Restore backup # Restore backup
move(backupp, path) move(backupp, path)

View File

@@ -20,7 +20,7 @@ def mock_ov_client():
@pytest.fixture @pytest.fixture
def mock_ansible_module(): def mock_ansible_module():
patcher_ansible = patch(ONEVIEW_MODULE_UTILS_PATH + '.AnsibleModule') patcher_ansible = patch(f"{ONEVIEW_MODULE_UTILS_PATH}.AnsibleModule")
patcher_ansible = patcher_ansible.start() patcher_ansible = patcher_ansible.start()
ansible_module = Mock() ansible_module = Mock()
patcher_ansible.return_value = ansible_module patcher_ansible.return_value = ansible_module

View File

@@ -22,7 +22,7 @@ class TestApkQueryLatest(unittest.TestCase):
def test_not_latest(self, mock_module): def test_not_latest(self, mock_module):
apk.APK_PATH = [""] apk.APK_PATH = [""]
for module_name in self.module_names: for module_name in self.module_names:
command_output = module_name + '-2.0.0-r1 < 3.0.0-r2 ' command_output = f"{module_name}-2.0.0-r1 < 3.0.0-r2 "
mock_module.run_command.return_value = (0, command_output, None) mock_module.run_command.return_value = (0, command_output, None)
command_result = apk.query_latest(mock_module, module_name) command_result = apk.query_latest(mock_module, module_name)
self.assertFalse(command_result) self.assertFalse(command_result)
@@ -31,7 +31,7 @@ class TestApkQueryLatest(unittest.TestCase):
def test_latest(self, mock_module): def test_latest(self, mock_module):
apk.APK_PATH = [""] apk.APK_PATH = [""]
for module_name in self.module_names: for module_name in self.module_names:
command_output = module_name + '-2.0.0-r1 = 2.0.0-r1 ' command_output = f"{module_name}-2.0.0-r1 = 2.0.0-r1 "
mock_module.run_command.return_value = (0, command_output, None) mock_module.run_command.return_value = (0, command_output, None)
command_result = apk.query_latest(mock_module, module_name) command_result = apk.query_latest(mock_module, module_name)
self.assertTrue(command_result) self.assertTrue(command_result)

View File

@@ -29,7 +29,7 @@ def get_orgs_mock(url, request):
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
content = { content = {
"login": org, "login": org,
"url": "https://api.github.com/orgs/{0}".format(org) "url": f"https://api.github.com/orgs/{org}"
} }
content = json.dumps(content).encode("utf-8") content = json.dumps(content).encode("utf-8")
return response(200, content, headers, None, 5, request) return response(200, content, headers, None, 5, request)
@@ -63,8 +63,8 @@ def get_repo_mock(url, request):
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
content = { content = {
"name": repo, "name": repo,
"full_name": "{0}/{1}".format(org, repo), "full_name": f"{org}/{repo}",
"url": "https://api.github.com/repos/{0}/{1}".format(org, repo), "url": f"https://api.github.com/repos/{org}/{repo}",
"private": False, "private": False,
"description": "This your first repo!", "description": "This your first repo!",
"default_branch": "master", "default_branch": "master",
@@ -85,8 +85,8 @@ def get_private_repo_mock(url, request):
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
content = { content = {
"name": repo, "name": repo,
"full_name": "{0}/{1}".format(org, repo), "full_name": f"{org}/{repo}",
"url": "https://api.github.com/repos/{0}/{1}".format(org, repo), "url": f"https://api.github.com/repos/{org}/{repo}",
"private": True, "private": True,
"description": "This your first repo!", "description": "This your first repo!",
"default_branch": "master", "default_branch": "master",
@@ -107,7 +107,7 @@ def create_new_org_repo_mock(url, request):
# https://docs.github.com/en/rest/reference/repos#create-an-organization-repository # https://docs.github.com/en/rest/reference/repos#create-an-organization-repository
content = { content = {
"name": repo['name'], "name": repo['name'],
"full_name": "{0}/{1}".format(org, repo['name']), "full_name": f"{org}/{repo['name']}",
"private": repo.get('private', False), "private": repo.get('private', False),
"description": repo.get('description') "description": repo.get('description')
} }
@@ -123,7 +123,7 @@ def create_new_user_repo_mock(url, request):
# https://docs.github.com/en/rest/reference/repos#create-a-repository-for-the-authenticated-user # https://docs.github.com/en/rest/reference/repos#create-a-repository-for-the-authenticated-user
content = { content = {
"name": repo['name'], "name": repo['name'],
"full_name": "{0}/{1}".format("octocat", repo['name']), "full_name": f"octocat/{repo['name']}",
"private": repo.get('private', False), "private": repo.get('private', False),
"description": repo.get('description') "description": repo.get('description')
} }
@@ -143,8 +143,8 @@ def patch_repo_mock(url, request):
# https://docs.github.com/en/rest/reference/repos#update-a-repository # https://docs.github.com/en/rest/reference/repos#update-a-repository
content = { content = {
"name": repo, "name": repo,
"full_name": "{0}/{1}".format(org, repo), "full_name": f"{org}/{repo}",
"url": "https://api.github.com/repos/{0}/{1}".format(org, repo), "url": f"https://api.github.com/repos/{org}/{repo}",
"private": body.get('private', False), "private": body.get('private', False),
"description": body.get('description'), "description": body.get('description'),
"default_branch": "master", "default_branch": "master",

View File

@@ -56,7 +56,7 @@ class TestGitlabGroupAccessToken(GitlabModuleTestCase):
def setUp(self): def setUp(self):
super(TestGitlabGroupAccessToken, self).setUp() super(TestGitlabGroupAccessToken, self).setUp()
if not python_gitlab_version_match_requirement(): if not python_gitlab_version_match_requirement():
self.skipTest("python-gitlab %s+ is needed for gitlab_group_access_token" % ",".join(map(str, PYTHON_GITLAB_MINIMAL_VERSION))) self.skipTest(f"python-gitlab {'.'.join(map(str, PYTHON_GITLAB_MINIMAL_VERSION))}+ is needed for gitlab_group_access_token")
self.moduleUtil = GitLabGroupAccessToken(module=self.mock_module, gitlab_instance=self.gitlab_instance) self.moduleUtil = GitLabGroupAccessToken(module=self.mock_module, gitlab_instance=self.gitlab_instance)

View File

@@ -56,7 +56,7 @@ class TestGitlabProjectAccessToken(GitlabModuleTestCase):
def setUp(self): def setUp(self):
super(TestGitlabProjectAccessToken, self).setUp() super(TestGitlabProjectAccessToken, self).setUp()
if not python_gitlab_version_match_requirement(): if not python_gitlab_version_match_requirement():
self.skipTest("python-gitlab %s+ is needed for gitlab_project_access_token" % ",".join(map(str, PYTHON_GITLAB_MINIMAL_VERSION))) self.skipTest(f"python-gitlab {'.'.join(map(str, PYTHON_GITLAB_MINIMAL_VERSION))}+ is needed for gitlab_project_access_token")
self.moduleUtil = GitLabProjectAccessToken(module=self.mock_module, gitlab_instance=self.gitlab_instance) self.moduleUtil = GitLabProjectAccessToken(module=self.mock_module, gitlab_instance=self.gitlab_instance)

View File

@@ -16,9 +16,9 @@ class IPAKeytabModuleTestCase(ModuleTestCase):
def setUp(self): def setUp(self):
super(IPAKeytabModuleTestCase, self).setUp() super(IPAKeytabModuleTestCase, self).setUp()
ansible_module_path = "ansible_collections.community.general.plugins.modules.ipa_getkeytab.AnsibleModule" ansible_module_path = "ansible_collections.community.general.plugins.modules.ipa_getkeytab.AnsibleModule"
self.mock_run_command = patch('%s.run_command' % ansible_module_path) self.mock_run_command = patch(f'{ansible_module_path}.run_command')
self.module_main_command = self.mock_run_command.start() self.module_main_command = self.mock_run_command.start()
self.mock_get_bin_path = patch('%s.get_bin_path' % ansible_module_path) self.mock_get_bin_path = patch(f'{ansible_module_path}.get_bin_path')
self.get_bin_path = self.mock_get_bin_path.start() self.get_bin_path = self.mock_get_bin_path.start()
self.get_bin_path.return_value = '/testbin/ipa_getkeytab' self.get_bin_path.return_value = '/testbin/ipa_getkeytab'

View File

@@ -37,7 +37,7 @@ class JenkinsBuildMock():
response["result"] = "ABSENT" response["result"] = "ABSENT"
return response return response
except Exception as e: except Exception as e:
fail_json(msg='Unable to fetch build information, {0}'.format(e)) fail_json(msg=f'Unable to fetch build information, {e}')
class JenkinsMock(): class JenkinsMock():
@@ -49,7 +49,7 @@ class JenkinsMock():
def get_build_info(self, name, build_number): def get_build_info(self, name, build_number):
if name == "host-delete": if name == "host-delete":
raise jenkins.JenkinsException("job {0} number {1} does not exist".format(name, build_number)) raise jenkins.JenkinsException(f"job {name} number {build_number} does not exist")
elif name == "create-detached": elif name == "create-detached":
return { return {
"building": True, "building": True,
@@ -87,7 +87,7 @@ class JenkinsMockIdempotent():
return None return None
def delete_build(self, name, build_number): def delete_build(self, name, build_number):
raise jenkins.NotFoundException("job {0} number {1} does not exist".format(name, build_number)) raise jenkins.NotFoundException(f"job {name} number {build_number} does not exist")
def stop_build(self, name, build_number): def stop_build(self, name, build_number):
return None return None

View File

@@ -38,7 +38,7 @@ class JenkinsBuildMock():
response["result"] = "ABSENT" response["result"] = "ABSENT"
return response return response
except Exception as e: except Exception as e:
fail_json(msg='Unable to fetch build information, {0}'.format(e)) fail_json(msg=f'Unable to fetch build information, {e}')
class JenkinsMock(): class JenkinsMock():

View File

@@ -143,7 +143,7 @@ def test_clean_data_removes_extraneous_fields():
} }
expected = {"id": "cred1", "description": "test"} expected = {"id": "cred1", "description": "test"}
result = jenkins_credential.clean_data(data) result = jenkins_credential.clean_data(data)
assert result == expected, "Expected {}, got {}".format(expected, result) assert result == expected, f"Expected {expected}, got {result}"
@patch( @patch(

View File

@@ -62,7 +62,7 @@ def assert_xml_equal(x, y):
if not isinstance(y, str): if not isinstance(y, str):
y = et.tostring(y) y = et.tostring(y)
raise AssertionError("{} != {}".format(x, y)) raise AssertionError(f"{x} != {y}")
@fixture(autouse=True) @fixture(autouse=True)

View File

@@ -155,7 +155,7 @@ def test__get_json_data(mocker):
jenkins_plugin = JenkinsPlugin(module) jenkins_plugin = JenkinsPlugin(module)
json_data = jenkins_plugin._get_json_data( json_data = jenkins_plugin._get_json_data(
"{url}".format(url=GITHUB_DATA['url']), f"{GITHUB_DATA['url']}",
'CSRF') 'CSRF')
assert isinstance(json_data, Mapping) assert isinstance(json_data, Mapping)
@@ -191,7 +191,7 @@ def test__new_fallback_urls(mocker):
def isInList(l, i): def isInList(l, i):
print("checking if %s in %s" % (i, l)) print(f"checking if {i} in {l}")
for item in l: for item in l:
if item == i: if item == i:
return True return True

View File

@@ -369,5 +369,5 @@ def test_user_agent_created_properly():
except ImportError: except ImportError:
ansible_version = 'unknown' ansible_version = 'unknown'
expected_user_agent = 'Ansible-linode_v4_module/%s' % ansible_version expected_user_agent = f'Ansible-linode_v4_module/{ansible_version}'
assert expected_user_agent == get_user_agent('linode_v4_module') assert expected_user_agent == get_user_agent('linode_v4_module')

View File

@@ -27,12 +27,12 @@ class TestLvgRename(ModuleTestCase):
self.mock_run_responses = {} self.mock_run_responses = {}
patched_module_get_bin_path = patch('%s.AnsibleModule.get_bin_path' % (self.module_path)) patched_module_get_bin_path = patch(f'{self.module_path}.AnsibleModule.get_bin_path')
self.mock_module_get_bin_path = patched_module_get_bin_path.start() self.mock_module_get_bin_path = patched_module_get_bin_path.start()
self.mock_module_get_bin_path.return_value = '/mocpath' self.mock_module_get_bin_path.return_value = '/mocpath'
self.addCleanup(patched_module_get_bin_path.stop) self.addCleanup(patched_module_get_bin_path.stop)
patched_module_run_command = patch('%s.AnsibleModule.run_command' % (self.module_path)) patched_module_run_command = patch(f'{self.module_path}.AnsibleModule.run_command')
self.mock_module_run_command = patched_module_run_command.start() self.mock_module_run_command = patched_module_run_command.start()
self.addCleanup(patched_module_run_command.stop) self.addCleanup(patched_module_run_command.stop)

View File

@@ -103,8 +103,8 @@ class MonitTest(unittest.TestCase):
def test_status_value(status_name): def test_status_value(status_name):
value = getattr(monit.StatusValue, status_name.upper()) value = getattr(monit.StatusValue, status_name.upper())
status = monit.StatusValue(value) status = monit.StatusValue(value)
assert getattr(status, 'is_%s' % status_name) assert getattr(status, f'is_{status_name}')
assert not all(getattr(status, 'is_%s' % name) for name in monit.StatusValue.ALL_STATUS if name != status_name) assert not all(getattr(status, f'is_{name}') for name in monit.StatusValue.ALL_STATUS if name != status_name)
BASIC_OUTPUT_CASES = [ BASIC_OUTPUT_CASES = [

View File

@@ -17,9 +17,9 @@ class NPMModuleTestCase(ModuleTestCase):
def setUp(self): def setUp(self):
super(NPMModuleTestCase, self).setUp() super(NPMModuleTestCase, self).setUp()
ansible_module_path = "ansible_collections.community.general.plugins.modules.npm.AnsibleModule" ansible_module_path = "ansible_collections.community.general.plugins.modules.npm.AnsibleModule"
self.mock_run_command = patch('%s.run_command' % ansible_module_path) self.mock_run_command = patch(f'{ansible_module_path}.run_command')
self.module_main_command = self.mock_run_command.start() self.module_main_command = self.mock_run_command.start()
self.mock_get_bin_path = patch('%s.get_bin_path' % ansible_module_path) self.mock_get_bin_path = patch(f'{ansible_module_path}.get_bin_path')
self.get_bin_path = self.mock_get_bin_path.start() self.get_bin_path = self.mock_get_bin_path.start()
self.get_bin_path.return_value = '/testbin/npm' self.get_bin_path.return_value = '/testbin/npm'

View File

@@ -101,63 +101,63 @@ def is_changed(ansible_exit_json):
def mock_get_request(*args, **kwargs): def mock_get_request(*args, **kwargs):
"""Mock for get_request.""" """Mock for get_request."""
url = args[1] url = args[1]
if url == 'https://' + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG
elif url == "mock_location": elif url == "mock_location":
return MOCK_SUCCESSFUL_HTTP_RESPONSE return MOCK_SUCCESSFUL_HTTP_RESPONSE
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_get_request_job_does_not_exist(*args, **kwargs): def mock_get_request_job_does_not_exist(*args, **kwargs):
"""Mock for get_request.""" """Mock for get_request."""
url = args[1] url = args[1]
if url == 'https://' + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG
elif url == urljoin('https://' + MOCK_BASE_URI, "Jobs/" + MOCK_JOB_NAME): elif url == urljoin(f"https://{MOCK_BASE_URI}", f"Jobs/{MOCK_JOB_NAME}"):
return MOCK_404_RESPONSE return MOCK_404_RESPONSE
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_get_request_job_in_progress(*args, **kwargs): def mock_get_request_job_in_progress(*args, **kwargs):
url = args[1] url = args[1]
if url == 'https://' + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG
elif url == urljoin('https://' + MOCK_BASE_URI, "Jobs/" + MOCK_JOB_NAME): elif url == urljoin(f"https://{MOCK_BASE_URI}", f"Jobs/{MOCK_JOB_NAME}"):
return MOCK_HTTP_RESPONSE_JOB_IN_PROGRESS return MOCK_HTTP_RESPONSE_JOB_IN_PROGRESS
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_get_request_job_complete(*args, **kwargs): def mock_get_request_job_complete(*args, **kwargs):
url = args[1] url = args[1]
if url == 'https://' + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG return MOCK_SUCCESSFUL_HTTP_RESPONSE_LED_INDICATOR_OFF_WITH_ETAG
elif url == urljoin('https://' + MOCK_BASE_URI, "Jobs/" + MOCK_JOB_NAME): elif url == urljoin(f"https://{MOCK_BASE_URI}", f"Jobs/{MOCK_JOB_NAME}"):
return MOCK_HTTP_RESPONSE_JOB_COMPLETE return MOCK_HTTP_RESPONSE_JOB_COMPLETE
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_put_request(*args, **kwargs): def mock_put_request(*args, **kwargs):
"""Mock put_request.""" """Mock put_request."""
url = args[1] url = args[1]
if url == 'https://' + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE_WITH_LOCATION_HEADER return MOCK_SUCCESSFUL_HTTP_RESPONSE_WITH_LOCATION_HEADER
raise RuntimeError("Illegal PUT call to: " + args[1]) raise RuntimeError(f"Illegal PUT call to: {args[1]}")
def mock_delete_request(*args, **kwargs): def mock_delete_request(*args, **kwargs):
"""Mock delete request.""" """Mock delete request."""
url = args[1] url = args[1]
if url == urljoin('https://' + MOCK_BASE_URI, 'Jobs/' + MOCK_JOB_NAME): if url == urljoin(f"https://{MOCK_BASE_URI}", f"Jobs/{MOCK_JOB_NAME}"):
return MOCK_SUCCESSFUL_HTTP_RESPONSE return MOCK_SUCCESSFUL_HTTP_RESPONSE
raise RuntimeError("Illegal DELETE call to: " + args[1]) raise RuntimeError(f"Illegal DELETE call to: {args[1]}")
def mock_post_request(*args, **kwargs): def mock_post_request(*args, **kwargs):
"""Mock post_request.""" """Mock post_request."""
url = args[1] url = args[1]
if url == urljoin('https://' + MOCK_BASE_URI, OPERATING_SYSTEM_URI): if url == urljoin(f"https://{MOCK_BASE_URI}", OPERATING_SYSTEM_URI):
return MOCK_SUCCESSFUL_HTTP_RESPONSE return MOCK_SUCCESSFUL_HTTP_RESPONSE
raise RuntimeError("Illegal POST call to: " + args[1]) raise RuntimeError(f"Illegal POST call to: {args[1]}")
def mock_http_request_conflict(*args, **kwargs): def mock_http_request_conflict(*args, **kwargs):
@@ -167,7 +167,7 @@ def mock_http_request_conflict(*args, **kwargs):
def mock_invalid_http_request(*args, **kwargs): def mock_invalid_http_request(*args, **kwargs):
"""Mock to make an HTTP request invalid. Raises an exception.""" """Mock to make an HTTP request invalid. Raises an exception."""
raise RuntimeError("Illegal HTTP call to " + args[1]) raise RuntimeError(f"Illegal HTTP call to {args[1]}")
class TestOcapiCommand(unittest.TestCase): class TestOcapiCommand(unittest.TestCase):

View File

@@ -88,31 +88,31 @@ def get_exception_message(ansible_exit_json):
def mock_get_request(*args, **kwargs): def mock_get_request(*args, **kwargs):
"""Mock for get_request.""" """Mock for get_request."""
url = args[1] url = args[1]
if url == "https://" + MOCK_BASE_URI: if url == f"https://{MOCK_BASE_URI}":
return MOCK_SUCCESSFUL_HTTP_RESPONSE return MOCK_SUCCESSFUL_HTTP_RESPONSE
elif url == "https://" + MOCK_BASE_URI + '/Jobs/' + MOCK_JOB_NAME_IN_PROGRESS: elif url == f"https://{MOCK_BASE_URI}/Jobs/{MOCK_JOB_NAME_IN_PROGRESS}":
return MOCK_HTTP_RESPONSE_JOB_IN_PROGRESS return MOCK_HTTP_RESPONSE_JOB_IN_PROGRESS
elif url == "https://" + MOCK_BASE_URI + '/Jobs/' + MOCK_JOB_NAME_COMPLETE: elif url == f"https://{MOCK_BASE_URI}/Jobs/{MOCK_JOB_NAME_COMPLETE}":
return MOCK_HTTP_RESPONSE_JOB_COMPLETE return MOCK_HTTP_RESPONSE_JOB_COMPLETE
elif url == "https://" + MOCK_BASE_URI + '/Jobs/' + MOCK_JOB_NAME_DOES_NOT_EXIST: elif url == f"https://{MOCK_BASE_URI}/Jobs/{MOCK_JOB_NAME_DOES_NOT_EXIST}":
return MOCK_404_RESPONSE return MOCK_404_RESPONSE
else: else:
raise RuntimeError("Illegal GET call to: " + args[1]) raise RuntimeError(f"Illegal GET call to: {args[1]}")
def mock_put_request(*args, **kwargs): def mock_put_request(*args, **kwargs):
"""Mock put_request. PUT should never happen so it will raise an error.""" """Mock put_request. PUT should never happen so it will raise an error."""
raise RuntimeError("Illegal PUT call to: " + args[1]) raise RuntimeError(f"Illegal PUT call to: {args[1]}")
def mock_delete_request(*args, **kwargs): def mock_delete_request(*args, **kwargs):
"""Mock delete request. DELETE should never happen so it will raise an error.""" """Mock delete request. DELETE should never happen so it will raise an error."""
raise RuntimeError("Illegal DELETE call to: " + args[1]) raise RuntimeError(f"Illegal DELETE call to: {args[1]}")
def mock_post_request(*args, **kwargs): def mock_post_request(*args, **kwargs):
"""Mock post_request. POST should never happen so it will raise an error.""" """Mock post_request. POST should never happen so it will raise an error."""
raise RuntimeError("Illegal POST call to: " + args[1]) raise RuntimeError(f"Illegal POST call to: {args[1]}")
class TestOcapiInfo(unittest.TestCase): class TestOcapiInfo(unittest.TestCase):

View File

@@ -29,7 +29,7 @@ PARAMS_WITH_CHANGES = dict(
config='config.json', config='config.json',
state='present', state='present',
data=dict(name=NETWORK_SET['name'], data=dict(name=NETWORK_SET['name'],
newName=NETWORK_SET['name'] + " - Renamed", newName=f"{NETWORK_SET['name']} - Renamed",
networkUris=['/rest/ethernet-networks/aaa-bbb-ccc', 'Name of a Network']) networkUris=['/rest/ethernet-networks/aaa-bbb-ccc', 'Name of a Network'])
) )
@@ -80,7 +80,7 @@ class NetworkSetModuleSpec(unittest.TestCase,
) )
def test_update_when_data_has_modified_attributes(self): def test_update_when_data_has_modified_attributes(self):
data_merged = dict(name=NETWORK_SET['name'] + " - Renamed", data_merged = dict(name=f"{NETWORK_SET['name']} - Renamed",
networkUris=['/rest/ethernet-networks/aaa-bbb-ccc', networkUris=['/rest/ethernet-networks/aaa-bbb-ccc',
'/rest/ethernet-networks/ddd-eee-fff'] '/rest/ethernet-networks/ddd-eee-fff']
) )
@@ -109,7 +109,7 @@ class NetworkSetModuleSpec(unittest.TestCase,
self.mock_ansible_module.fail_json.assert_called_once_with( self.mock_ansible_module.fail_json.assert_called_once_with(
exception=mock.ANY, exception=mock.ANY,
msg=NetworkSetModule.MSG_ETHERNET_NETWORK_NOT_FOUND + "Name of a Network" msg=f"{NetworkSetModule.MSG_ETHERNET_NETWORK_NOT_FOUND}Name of a Network"
) )
def test_should_remove_network(self): def test_should_remove_network(self):

View File

@@ -22,7 +22,7 @@ class TestPkginQueryPackage(unittest.TestCase):
parseable_flag_not_supported = 1 parseable_flag_not_supported = 1
mock_module.run_command.side_effect = [ mock_module.run_command.side_effect = [
(parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None), (parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None),
(0, "%s-1.21.0 = C/C++ package manager" % package, None), (0, f"{package}-1.21.0 = C/C++ package manager", None),
] ]
# when # when
@@ -38,7 +38,7 @@ class TestPkginQueryPackage(unittest.TestCase):
parseable_flag_not_supported = 1 parseable_flag_not_supported = 1
mock_module.run_command.side_effect = [ mock_module.run_command.side_effect = [
(parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None), (parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None),
(0, "%s = C/C++ package manager" % package, None), (0, f"{package} = C/C++ package manager", None),
] ]
# when # when
@@ -102,7 +102,7 @@ class TestPkginQueryPackage(unittest.TestCase):
parseable_flag_not_supported = 1 parseable_flag_not_supported = 1
mock_module.run_command.side_effect = [ mock_module.run_command.side_effect = [
(parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None), (parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None),
(1, None, "No results found for %s" % package), (1, None, f"No results found for {package}"),
] ]
# when # when
@@ -118,7 +118,7 @@ class TestPkginQueryPackage(unittest.TestCase):
parseable_flag_supported = 0 parseable_flag_supported = 0
mock_module.run_command.side_effect = [ mock_module.run_command.side_effect = [
(parseable_flag_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None), (parseable_flag_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None),
(0, "%s-1.21.0;=;C/C++ package manager" % package, None), (0, f"{package}-1.21.0;=;C/C++ package manager", None),
] ]
# when # when
@@ -134,7 +134,7 @@ class TestPkginQueryPackage(unittest.TestCase):
parseable_flag_not_supported = 1 parseable_flag_not_supported = 1
mock_module.run_command.side_effect = [ mock_module.run_command.side_effect = [
(parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None), (parseable_flag_not_supported, "pkgin 0.11.7 for Darwin-18.6.0 x86_64 (using SQLite 3.27.2)", None),
(0, "%s-1.21.0 = C/C++ package manager" % package, None), (0, f"{package}-1.21.0 = C/C++ package manager", None),
] ]
# when # when

View File

@@ -17,9 +17,9 @@ class RpmOSTreeModuleTestCase(ModuleTestCase):
def setUp(self): def setUp(self):
super(RpmOSTreeModuleTestCase, self).setUp() super(RpmOSTreeModuleTestCase, self).setUp()
ansible_module_path = "ansible_collections.community.general.plugins.modules.rpm_ostree_pkg.AnsibleModule" ansible_module_path = "ansible_collections.community.general.plugins.modules.rpm_ostree_pkg.AnsibleModule"
self.mock_run_command = patch('%s.run_command' % ansible_module_path) self.mock_run_command = patch(f'{ansible_module_path}.run_command')
self.module_main_command = self.mock_run_command.start() self.module_main_command = self.mock_run_command.start()
self.mock_get_bin_path = patch('%s.get_bin_path' % ansible_module_path) self.mock_get_bin_path = patch(f'{ansible_module_path}.get_bin_path')
self.get_bin_path = self.mock_get_bin_path.start() self.get_bin_path = self.mock_get_bin_path.start()
self.get_bin_path.return_value = '/testbin/rpm-ostree' self.get_bin_path.return_value = '/testbin/rpm-ostree'

View File

@@ -62,7 +62,7 @@ def test_acl_create(api_request_mock, project, prefix):
# should have done GET → POST → GET # should have done GET → POST → GET
assert api_request_mock.call_count == 3 assert api_request_mock.call_count == 3
args, kwargs = api_request_mock.call_args_list[1] args, kwargs = api_request_mock.call_args_list[1]
assert kwargs['endpoint'] == "%s/%s.aclpolicy" % (prefix, name) assert kwargs['endpoint'] == f"{prefix}/{name}.aclpolicy"
assert kwargs['method'] == 'POST' assert kwargs['method'] == 'POST'
@@ -91,7 +91,7 @@ def test_acl_unchanged(api_request_mock, project, prefix):
# only a single GET # only a single GET
assert api_request_mock.call_count == 1 assert api_request_mock.call_count == 1
args, kwargs = api_request_mock.call_args args, kwargs = api_request_mock.call_args
assert kwargs['endpoint'] == "%s/%s.aclpolicy" % (prefix, name) assert kwargs['endpoint'] == f"{prefix}/{name}.aclpolicy"
# default method is GET # default method is GET
assert kwargs.get('method', 'GET') == 'GET' assert kwargs.get('method', 'GET') == 'GET'
@@ -123,7 +123,7 @@ def test_acl_remove(api_request_mock, project, prefix):
# GET → DELETE # GET → DELETE
assert api_request_mock.call_count == 2 assert api_request_mock.call_count == 2
args, kwargs = api_request_mock.call_args_list[1] args, kwargs = api_request_mock.call_args_list[1]
assert kwargs['endpoint'] == "%s/%s.aclpolicy" % (prefix, name) assert kwargs['endpoint'] == f"{prefix}/{name}.aclpolicy"
assert kwargs['method'] == 'DELETE' assert kwargs['method'] == 'DELETE'
@@ -151,5 +151,5 @@ def test_acl_remove_nonexistent(api_request_mock, project, prefix):
# only the initial GET # only the initial GET
assert api_request_mock.call_count == 1 assert api_request_mock.call_count == 1
args, kwargs = api_request_mock.call_args args, kwargs = api_request_mock.call_args
assert kwargs['endpoint'] == "%s/%s.aclpolicy" % (prefix, name) assert kwargs['endpoint'] == f"{prefix}/{name}.aclpolicy"
assert kwargs.get('method', 'GET') == 'GET' assert kwargs.get('method', 'GET') == 'GET'

View File

@@ -74,7 +74,7 @@ def test_scaleway_add_nic(capfd):
os.environ['SCW_API_TOKEN'] = 'notrealtoken' os.environ['SCW_API_TOKEN'] = 'notrealtoken'
pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90' pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90'
cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90' cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90'
url = 'servers/' + cid + '/private_nics' url = f"servers/{cid}/private_nics"
with set_module_args({ with set_module_args({
"project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90",
@@ -103,7 +103,7 @@ def test_scaleway_add_existing_nic(capfd):
os.environ['SCW_API_TOKEN'] = 'notrealtoken' os.environ['SCW_API_TOKEN'] = 'notrealtoken'
pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90' pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90'
cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90' cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90'
url = 'servers/' + cid + '/private_nics' url = f"servers/{cid}/private_nics"
with set_module_args({ with set_module_args({
"project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90",
@@ -130,8 +130,8 @@ def test_scaleway_remove_existing_nic(capfd):
pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90' pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90'
cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90' cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90'
nicid = 'c123b4cd-ef5g-678h-90i1-jk2345678l90' nicid = 'c123b4cd-ef5g-678h-90i1-jk2345678l90'
url = 'servers/' + cid + '/private_nics' url = f"servers/{cid}/private_nics"
urlremove = 'servers/' + cid + '/private_nics/' + nicid urlremove = f"servers/{cid}/private_nics/{nicid}"
with set_module_args({ with set_module_args({
"project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90",
@@ -161,7 +161,7 @@ def test_scaleway_remove_absent_nic(capfd):
os.environ['SCW_API_TOKEN'] = 'notrealtoken' os.environ['SCW_API_TOKEN'] = 'notrealtoken'
pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90' pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90'
cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90' cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90'
url = 'servers/' + cid + '/private_nics' url = f"servers/{cid}/private_nics"
with set_module_args({ with set_module_args({
"project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90",

View File

@@ -103,7 +103,7 @@ def test_zone_create_invalid_names(mocked_zone_create, capfd):
{ {
"name": invalid_name, "name": invalid_name,
"state": "installed", "state": "installed",
"path": "/zones/" + invalid_name, "path": f"/zones/{invalid_name}",
"_ansible_check_mode": False, "_ansible_check_mode": False,
} }
): ):

View File

@@ -197,7 +197,7 @@ def test_create_cpg(mock_client):
8, 8,
'MAG', 'MAG',
'FC' 'FC'
) == (True, True, "Created CPG %s successfully." % 'test_cpg') ) == (True, True, "Created CPG test_cpg successfully.")
mock_client.HPE3ParClient.cpgExists.return_value = True mock_client.HPE3ParClient.cpgExists.return_value = True
assert ss_3par_cpg.create_cpg(mock_client.HPE3ParClient, assert ss_3par_cpg.create_cpg(mock_client.HPE3ParClient,
@@ -235,7 +235,7 @@ def test_delete_cpg(mock_client):
assert ss_3par_cpg.delete_cpg(mock_client.HPE3ParClient, assert ss_3par_cpg.delete_cpg(mock_client.HPE3ParClient,
'test_cpg' 'test_cpg'
) == (True, True, "Deleted CPG %s successfully." % 'test_cpg') ) == (True, True, "Deleted CPG test_cpg successfully.")
mock_client.HPE3ParClient.cpgExists.return_value = False mock_client.HPE3ParClient.cpgExists.return_value = False

View File

@@ -30,10 +30,8 @@ To Action From
-- ------ ----""" -- ------ ----"""
ufw_status_verbose_with_port_7000 = ufw_verbose_header + """ ufw_status_verbose_with_port_7000 = (
7000/tcp ALLOW IN Anywhere f"{ufw_verbose_header}\n7000/tcp ALLOW IN Anywhere\n7000/tcp (v6) ALLOW IN Anywhere (v6)\n")
7000/tcp (v6) ALLOW IN Anywhere (v6)
"""
user_rules_with_port_7000 = """### tuple ### allow tcp 7000 0.0.0.0/0 any 0.0.0.0/0 in user_rules_with_port_7000 = """### tuple ### allow tcp 7000 0.0.0.0/0 any 0.0.0.0/0 in
### tuple ### allow tcp 7000 ::/0 any ::/0 in ### tuple ### allow tcp 7000 ::/0 any ::/0 in
@@ -43,10 +41,8 @@ user_rules_with_ipv6 = """### tuple ### allow udp 5353 0.0.0.0/0 any 224.0.0.251
### tuple ### allow udp 5353 ::/0 any ff02::fb in ### tuple ### allow udp 5353 ::/0 any ff02::fb in
""" """
ufw_status_verbose_with_ipv6 = ufw_verbose_header + """ ufw_status_verbose_with_ipv6 = (
5353/udp ALLOW IN 224.0.0.251 f"{ufw_verbose_header}\n5353/udp ALLOW IN 224.0.0.251\n5353/udp ALLOW IN ff02::fb\n")
5353/udp ALLOW IN ff02::fb
"""
ufw_status_verbose_nothing = ufw_verbose_header ufw_status_verbose_nothing = ufw_verbose_header

View File

@@ -17,7 +17,7 @@ def get_bin_path(self, arg, required=False):
return '/usr/bin/lsusb' return '/usr/bin/lsusb'
else: else:
if required: if required:
fail_json(msg='%r not found !' % arg) fail_json(msg=f'{arg!r} not found !')
class TestUsbFacts(unittest.TestCase): class TestUsbFacts(unittest.TestCase):
@@ -61,7 +61,7 @@ class TestUsbFacts(unittest.TestCase):
def test_parsing_multiple_lines(self): def test_parsing_multiple_lines(self):
input = "" input = ""
for data in self.testing_data: for data in self.testing_data:
input += ("%s\n" % data["input"]) input += f"{data['input']}\n"
with mock.patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: with mock.patch.object(basic.AnsibleModule, 'run_command') as mock_run_command:
mock_run_command.return_value = 0, input, None mock_run_command.return_value = 0, input, None
with self.assertRaises(AnsibleExitJson) as result: with self.assertRaises(AnsibleExitJson) as result:

View File

@@ -222,7 +222,7 @@ def mock_get_request_enclosure_single_tenant(*args, **kwargs):
elif args[1].endswith("/UpdateService"): elif args[1].endswith("/UpdateService"):
return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_AND_FW_ACTIVATE return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_AND_FW_ACTIVATE
else: else:
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_get_request_enclosure_multi_tenant(*args, **kwargs): def mock_get_request_enclosure_multi_tenant(*args, **kwargs):
@@ -240,7 +240,7 @@ def mock_get_request_enclosure_multi_tenant(*args, **kwargs):
elif args[1].endswith("/IOModuleBFRU"): elif args[1].endswith("/IOModuleBFRU"):
return MOCK_GET_IOM_B_MULTI_TENANAT return MOCK_GET_IOM_B_MULTI_TENANAT
else: else:
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_get_request(*args, **kwargs): def mock_get_request(*args, **kwargs):
@@ -252,7 +252,7 @@ def mock_get_request(*args, **kwargs):
elif args[1].endswith("Chassis/Enclosure"): elif args[1].endswith("Chassis/Enclosure"):
return MOCK_SUCCESSFUL_RESPONSE_CHASSIS_ENCLOSURE return MOCK_SUCCESSFUL_RESPONSE_CHASSIS_ENCLOSURE
else: else:
raise RuntimeError("Illegal call to get_request in test: " + args[1]) raise RuntimeError(f"Illegal call to get_request in test: {args[1]}")
def mock_post_request(*args, **kwargs): def mock_post_request(*args, **kwargs):
@@ -268,7 +268,7 @@ def mock_post_request(*args, **kwargs):
"ret": True, "ret": True,
"data": ACTION_WAS_SUCCESSFUL_MESSAGE "data": ACTION_WAS_SUCCESSFUL_MESSAGE
} }
raise RuntimeError("Illegal POST call to: " + args[1]) raise RuntimeError(f"Illegal POST call to: {args[1]}")
def mock_get_firmware_inventory_version_1_2_3(*args, **kwargs): def mock_get_firmware_inventory_version_1_2_3(*args, **kwargs):
@@ -570,10 +570,7 @@ class TestWdcRedfishCommand(unittest.TestCase):
"""Test Update and Activate when target is not in the correct state.""" """Test Update and Activate when target is not in the correct state."""
mock_status_code = 999 mock_status_code = 999
mock_status_description = "mock status description" mock_status_description = "mock status description"
expected_error_message = "Target is not ready for FW update. Current status: {0} ({1})".format( expected_error_message = f"Target is not ready for FW update. Current status: {mock_status_code} ({mock_status_description})"
mock_status_code,
mock_status_description
)
with set_module_args({ with set_module_args({
'category': 'Update', 'category': 'Update',
'command': 'UpdateAndActivate', 'command': 'UpdateAndActivate',
@@ -646,7 +643,7 @@ class TestWdcRedfishCommand(unittest.TestCase):
} }
}): }):
tar_name = "empty_tarfile{0}.tar".format(uuid.uuid4()) tar_name = f"empty_tarfile{uuid.uuid4()}.tar"
empty_tarfile = tarfile.open(os.path.join(self.tempdir, tar_name), "w") empty_tarfile = tarfile.open(os.path.join(self.tempdir, tar_name), "w")
empty_tarfile.close() empty_tarfile.close()
with patch('ansible_collections.community.general.plugins.module_utils.wdc_redfish_utils.fetch_file') as mock_fetch_file: with patch('ansible_collections.community.general.plugins.module_utils.wdc_redfish_utils.fetch_file') as mock_fetch_file:
@@ -885,10 +882,10 @@ class TestWdcRedfishCommand(unittest.TestCase):
This can be used for a mock FW update. This can be used for a mock FW update.
""" """
tar_name = "tarfile{0}.tar".format(uuid.uuid4()) tar_name = f"tarfile{uuid.uuid4()}.tar"
bundle_tarfile = tarfile.open(os.path.join(self.tempdir, tar_name), "w") bundle_tarfile = tarfile.open(os.path.join(self.tempdir, tar_name), "w")
package_filename = "oobm-{0}.pkg".format(mock_firmware_version) package_filename = f"oobm-{mock_firmware_version}.pkg"
package_filename_path = os.path.join(self.tempdir, package_filename) package_filename_path = os.path.join(self.tempdir, package_filename)
with open(package_filename_path, "w"): with open(package_filename_path, "w"):
pass pass

View File

@@ -205,7 +205,7 @@ class TestWdcRedfishInfo(unittest.TestCase):
elif uri.endswith("/UpdateService"): elif uri.endswith("/UpdateService"):
return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_BUT_NO_FW_ACTIVATE return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_BUT_NO_FW_ACTIVATE
else: else:
raise RuntimeError("Illegal call to get_request in test: " + uri) raise RuntimeError(f"Illegal call to get_request in test: {uri}")
with patch("ansible_collections.community.general.plugins.module_utils.wdc_redfish_utils.WdcRedfishUtils.get_request") as mock_get_request: with patch("ansible_collections.community.general.plugins.module_utils.wdc_redfish_utils.WdcRedfishUtils.get_request") as mock_get_request:
mock_get_request.side_effect = mock_get_request_function mock_get_request.side_effect = mock_get_request_function

View File

@@ -37,7 +37,7 @@ class UTHelper(object):
with open(test_spec_filename, "r") as test_spec_filehandle: with open(test_spec_filename, "r") as test_spec_filehandle:
return UTHelper.from_file(ansible_module, test_module, test_spec_filehandle, mocks=mocks) return UTHelper.from_file(ansible_module, test_module, test_spec_filehandle, mocks=mocks)
raise Exception("Cannot find test case file for {0} with one of the extensions: {1}".format(test_module.__file__, extensions)) raise Exception(f"Cannot find test case file for {test_module.__file__} with one of the extensions: {extensions}")
def add_func_to_test_module(self, name, func): def add_func_to_test_module(self, name, func):
setattr(self.test_module, name, func) setattr(self.test_module, name, func)
@@ -50,7 +50,7 @@ class UTHelper(object):
spec_diff = set(test_spec.keys()) - set(self.TEST_SPEC_VALID_SECTIONS) spec_diff = set(test_spec.keys()) - set(self.TEST_SPEC_VALID_SECTIONS)
if spec_diff: if spec_diff:
raise ValueError("Test specification contain unknown keys: {0}".format(", ".join(spec_diff))) raise ValueError(f"Test specification contain unknown keys: {', '.join(spec_diff)}")
self.mocks_map = {m.name: m for m in mocks} if mocks else {} self.mocks_map = {m.name: m for m in mocks} if mocks else {}
@@ -125,22 +125,11 @@ class ModuleTestCase:
self._fixtures = {} self._fixtures = {}
def __str__(self): def __str__(self):
return "<ModuleTestCase: id={id} {input}{output}mocks={mocks} flags={flags}>".format( return (f"<ModuleTestCase: id={self.id} {'input ' if self.input else ''}{'output ' if self.output else ''}"
id=self.id, f"mocks=({', '.join(self.mocks.keys())}) flags={self.flags}>")
input="input " if self.input else "",
output="output " if self.output else "",
mocks="({0})".format(", ".join(self.mocks.keys())),
flags=self.flags
)
def __repr__(self): def __repr__(self):
return "ModuleTestCase(id={id}, input={input}, output={output}, mocks={mocks}, flags={flags})".format( return f"ModuleTestCase(id={self.id}, input={self.input}, output={self.output}, mocks={self.mocks!r}, flags={self.flags})"
id=self.id,
input=self.input,
output=self.output,
mocks=repr(self.mocks),
flags=self.flags
)
@staticmethod @staticmethod
def make_test_case(test_case_spec, test_module, mocks_map): def make_test_case(test_case_spec, test_module, mocks_map):
@@ -159,7 +148,7 @@ class ModuleTestCase:
try: try:
mock_class = mocks_map[mock_name] mock_class = mocks_map[mock_name]
except KeyError: except KeyError:
raise Exception("Cannot find TestCaseMock class for: {0}".format(mock_name)) raise Exception(f"Cannot find TestCaseMock class for: {mock_name}")
self.mocks[mock_name] = mock_class.build_mock(mock_spec) self.mocks[mock_name] = mock_class.build_mock(mock_spec)
self._fixtures.update(self.mocks[mock_name].fixtures()) self._fixtures.update(self.mocks[mock_name].fixtures())
@@ -184,14 +173,14 @@ class ModuleTestCase:
mock.setup(mocker) mock.setup(mocker)
def check_testcase(self, results): def check_testcase(self, results):
print("testcase =\n%s" % repr(self)) print(f"testcase =\n{self!r}")
print("results =\n%s" % results) print(f"results =\n{results}")
if 'exception' in results: if 'exception' in results:
print("exception = \n%s" % results["exception"]) print(f"exception = \n{results['exception']}")
for test_result in self.output: for test_result in self.output:
assert results[test_result] == self.output[test_result], \ assert results[test_result] == self.output[test_result], \
"'{0}': '{1}' != '{2}'".format(test_result, results[test_result], self.output[test_result]) f"'{test_result}': '{results[test_result]}' != '{self.output[test_result]}'"
def check_mocks(self, test_case, results): def check_mocks(self, test_case, results):
for mock in self.mocks.values(): for mock in self.mocks.values():
@@ -229,7 +218,7 @@ class RunCommandMock(TestCaseMock):
@pytest.fixture @pytest.fixture
def patch_bin(mocker): def patch_bin(mocker):
def mockie(self_, path, *args, **kwargs): def mockie(self_, path, *args, **kwargs):
return "/testbin/{0}".format(path) return f"/testbin/{path}"
mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path', mockie) mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path', mockie)
return {"patch_bin": patch_bin} return {"patch_bin": patch_bin}
@@ -245,7 +234,7 @@ class RunCommandMock(TestCaseMock):
def side_effect(self_, **kwargs): def side_effect(self_, **kwargs):
result = next(results) result = next(results)
if kwargs.get("check_rc", False) and result[0] != 0: if kwargs.get("check_rc", False) and result[0] != 0:
raise Exception("rc = {0}".format(result[0])) raise Exception(f"rc = {result[0]}")
return result return result
self.mock_run_cmd = mocker.patch('ansible.module_utils.basic.AnsibleModule.run_command', side_effect=side_effect) self.mock_run_cmd = mocker.patch('ansible.module_utils.basic.AnsibleModule.run_command', side_effect=side_effect)
@@ -253,9 +242,9 @@ class RunCommandMock(TestCaseMock):
def check(self, test_case, results): def check(self, test_case, results):
call_args_list = [(item[0][0], item[1]) for item in self.mock_run_cmd.call_args_list] call_args_list = [(item[0][0], item[1]) for item in self.mock_run_cmd.call_args_list]
expected_call_args_list = [(item['command'], item.get('environ', {})) for item in self.mock_specs] expected_call_args_list = [(item['command'], item.get('environ', {})) for item in self.mock_specs]
print("call args list =\n%s" % call_args_list) print(f"call args list =\n{call_args_list}")
print("expected args list =\n%s" % expected_call_args_list) print(f"expected args list =\n{expected_call_args_list}")
assert self.mock_run_cmd.call_count == len(self.mock_specs), "{0} != {1}".format(self.mock_run_cmd.call_count, len(self.mock_specs)) assert self.mock_run_cmd.call_count == len(self.mock_specs), f"{self.mock_run_cmd.call_count} != {len(self.mock_specs)}"
if self.mock_run_cmd.call_count: if self.mock_run_cmd.call_count:
assert call_args_list == expected_call_args_list assert call_args_list == expected_call_args_list

View File

@@ -7,4 +7,4 @@ from __future__ import annotations
def fake_xenapi_ref(xenapi_class): def fake_xenapi_ref(xenapi_class):
return "OpaqueRef:fake-xenapi-%s-ref" % xenapi_class return f"OpaqueRef:fake-xenapi-{xenapi_class}-ref"