diff --git a/tests/unit/plugins/modules/gitlab.py b/tests/unit/plugins/modules/gitlab.py index 2bd4cd46bc..d5eeebfcd1 100644 --- a/tests/unit/plugins/modules/gitlab.py +++ b/tests/unit/plugins/modules/gitlab.py @@ -55,7 +55,7 @@ def python_gitlab_version_match_requirement(): # Skip unittest test case if python version don't match requirement def unitest_python_version_check_requirement(unittest_testcase): 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") ''' diff --git a/tests/unit/plugins/modules/hpe_test_utils.py b/tests/unit/plugins/modules/hpe_test_utils.py index fa54ee2988..90a17382f7 100644 --- a/tests/unit/plugins/modules/hpe_test_utils.py +++ b/tests/unit/plugins/modules/hpe_test_utils.py @@ -18,7 +18,7 @@ class OneViewBaseTest(object): @pytest.fixture(autouse=True) def setUp(self, mock_ansible_module, mock_ov_client, request): 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_ansible_module = mock_ansible_module @@ -27,7 +27,7 @@ class OneViewBaseTest(object): resource_name = type(self).__name__.replace('Test', '') 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 = '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') oneview_module = ansible_collections.community.general.plugins.modules @@ -40,7 +40,7 @@ class OneViewBaseTest(object): EXAMPLES = yaml.safe_load(testing_module.EXAMPLES) 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) return testing_module @@ -114,7 +114,7 @@ class OneViewBaseTestCase(object): self.mock_ov_client = self.mock_ov_client_from_json_file.return_value # 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) mock_ansible_module = patcher_ansible.start() self.mock_ansible_module = Mock() @@ -142,7 +142,7 @@ class OneViewBaseTestCase(object): self.EXAMPLES = yaml.safe_load(self.testing_module.EXAMPLES) 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) diff --git a/tests/unit/plugins/modules/interfaces_file/test_interfaces_file.py b/tests/unit/plugins/modules/interfaces_file/test_interfaces_file.py index d4c6707a2c..5f91df758c 100644 --- a/tests/unit/plugins/modules/interfaces_file/test_interfaces_file.py +++ b/tests/unit/plugins/modules/interfaces_file/test_interfaces_file.py @@ -29,7 +29,7 @@ class ModuleMocked: move(src, dst) 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) return backupp @@ -68,12 +68,12 @@ class TestInterfacesFileModule(unittest.TestCase): def compareInterfacesLinesToFile(self, interfaces_lines, path, testname=None): 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) def compareInterfacesToFile(self, ifaces, path, testname=None): 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) 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'], options['value'], options['state']) except AnsibleFailJson as e: - fail_json_iterations.append("[%d] fail_json message: %s\noptions:\n%s" % - (i, str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) - self.compareStringWithFile("\n=====\n".join(fail_json_iterations), "%s_%s.exceptions.txt" % (testfile, testname)) + fail_json_iterations.append( + 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), f"{testfile}_{testname}.exceptions.txt") - self.compareInterfacesLinesToFile(lines, testfile, "%s_%s" % (testfile, testname)) - self.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) + self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}") + self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json") def test_revert(self): testcases = { @@ -229,14 +229,14 @@ class TestInterfacesFileModule(unittest.TestCase): dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'], options['value'], options['state']) except AnsibleFailJson as e: - fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % - (str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) + fail_json_iterations.append( + 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) - 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.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) + self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}") + self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json") if testfile not in ["no_leading_spaces"]: # skip if eth0 has MTU value self.compareFileToBackup(path, backupp) @@ -270,17 +270,16 @@ class TestInterfacesFileModule(unittest.TestCase): changed_again, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'], options['value'], options['state']) self.assertFalse(changed_again, - msg='Second request for change should return false for {0} running on {1}'.format(testname, - testfile)) + msg=f'Second request for change should return false for {testname} running on {testfile}') except AnsibleFailJson as e: - fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % - (str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) + fail_json_iterations.append( + 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) - 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.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) + self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}") + self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json") # Restore backup move(backupp, path) @@ -544,13 +543,13 @@ class TestInterfacesFileModule(unittest.TestCase): dummy, lines = interfaces_file.set_interface_option(module, lines, options['iface'], options['option'], options['value'], options['state'], options['address_family']) except AnsibleFailJson as e: - fail_json_iterations.append("fail_json message: %s\noptions:\n%s" % - (str(e), json.dumps(options, sort_keys=True, indent=4, separators=(',', ': ')))) + fail_json_iterations.append( + 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) - 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.compareInterfacesToFile(ifaces, testfile, "%s_%s.json" % (testfile, testname)) + self.compareInterfacesLinesToFile(lines, testfile, f"{testfile}_{testname}") + self.compareInterfacesToFile(ifaces, testfile, f"{testfile}_{testname}.json") # Restore backup move(backupp, path) diff --git a/tests/unit/plugins/modules/oneview_conftest.py b/tests/unit/plugins/modules/oneview_conftest.py index c1d863108b..85e8eedaec 100644 --- a/tests/unit/plugins/modules/oneview_conftest.py +++ b/tests/unit/plugins/modules/oneview_conftest.py @@ -20,7 +20,7 @@ def mock_ov_client(): @pytest.fixture 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() ansible_module = Mock() patcher_ansible.return_value = ansible_module diff --git a/tests/unit/plugins/modules/test_apk.py b/tests/unit/plugins/modules/test_apk.py index 89bc166bb6..25ba0fce22 100644 --- a/tests/unit/plugins/modules/test_apk.py +++ b/tests/unit/plugins/modules/test_apk.py @@ -22,7 +22,7 @@ class TestApkQueryLatest(unittest.TestCase): def test_not_latest(self, mock_module): apk.APK_PATH = [""] 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) command_result = apk.query_latest(mock_module, module_name) self.assertFalse(command_result) @@ -31,7 +31,7 @@ class TestApkQueryLatest(unittest.TestCase): def test_latest(self, mock_module): apk.APK_PATH = [""] 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) command_result = apk.query_latest(mock_module, module_name) self.assertTrue(command_result) diff --git a/tests/unit/plugins/modules/test_github_repo.py b/tests/unit/plugins/modules/test_github_repo.py index d74d486599..28e973251a 100644 --- a/tests/unit/plugins/modules/test_github_repo.py +++ b/tests/unit/plugins/modules/test_github_repo.py @@ -29,7 +29,7 @@ def get_orgs_mock(url, request): headers = {'content-type': 'application/json'} content = { "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") return response(200, content, headers, None, 5, request) @@ -63,8 +63,8 @@ def get_repo_mock(url, request): headers = {'content-type': 'application/json'} content = { "name": repo, - "full_name": "{0}/{1}".format(org, repo), - "url": "https://api.github.com/repos/{0}/{1}".format(org, repo), + "full_name": f"{org}/{repo}", + "url": f"https://api.github.com/repos/{org}/{repo}", "private": False, "description": "This your first repo!", "default_branch": "master", @@ -85,8 +85,8 @@ def get_private_repo_mock(url, request): headers = {'content-type': 'application/json'} content = { "name": repo, - "full_name": "{0}/{1}".format(org, repo), - "url": "https://api.github.com/repos/{0}/{1}".format(org, repo), + "full_name": f"{org}/{repo}", + "url": f"https://api.github.com/repos/{org}/{repo}", "private": True, "description": "This your first repo!", "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 content = { "name": repo['name'], - "full_name": "{0}/{1}".format(org, repo['name']), + "full_name": f"{org}/{repo['name']}", "private": repo.get('private', False), "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 content = { "name": repo['name'], - "full_name": "{0}/{1}".format("octocat", repo['name']), + "full_name": f"octocat/{repo['name']}", "private": repo.get('private', False), "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 content = { "name": repo, - "full_name": "{0}/{1}".format(org, repo), - "url": "https://api.github.com/repos/{0}/{1}".format(org, repo), + "full_name": f"{org}/{repo}", + "url": f"https://api.github.com/repos/{org}/{repo}", "private": body.get('private', False), "description": body.get('description'), "default_branch": "master", diff --git a/tests/unit/plugins/modules/test_gitlab_group_access_token.py b/tests/unit/plugins/modules/test_gitlab_group_access_token.py index a7b2ffafc0..24417f9200 100644 --- a/tests/unit/plugins/modules/test_gitlab_group_access_token.py +++ b/tests/unit/plugins/modules/test_gitlab_group_access_token.py @@ -56,7 +56,7 @@ class TestGitlabGroupAccessToken(GitlabModuleTestCase): def setUp(self): super(TestGitlabGroupAccessToken, self).setUp() 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) diff --git a/tests/unit/plugins/modules/test_gitlab_project_access_token.py b/tests/unit/plugins/modules/test_gitlab_project_access_token.py index acf43205d8..5077fa81bf 100644 --- a/tests/unit/plugins/modules/test_gitlab_project_access_token.py +++ b/tests/unit/plugins/modules/test_gitlab_project_access_token.py @@ -56,7 +56,7 @@ class TestGitlabProjectAccessToken(GitlabModuleTestCase): def setUp(self): super(TestGitlabProjectAccessToken, self).setUp() 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) diff --git a/tests/unit/plugins/modules/test_ipa_getkeytab.py b/tests/unit/plugins/modules/test_ipa_getkeytab.py index 86f6e8cb35..f9bed6e5f8 100644 --- a/tests/unit/plugins/modules/test_ipa_getkeytab.py +++ b/tests/unit/plugins/modules/test_ipa_getkeytab.py @@ -16,9 +16,9 @@ class IPAKeytabModuleTestCase(ModuleTestCase): def setUp(self): super(IPAKeytabModuleTestCase, self).setUp() 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.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.return_value = '/testbin/ipa_getkeytab' diff --git a/tests/unit/plugins/modules/test_jenkins_build.py b/tests/unit/plugins/modules/test_jenkins_build.py index 210f5b5f1e..e741e5558c 100644 --- a/tests/unit/plugins/modules/test_jenkins_build.py +++ b/tests/unit/plugins/modules/test_jenkins_build.py @@ -37,7 +37,7 @@ class JenkinsBuildMock(): response["result"] = "ABSENT" return response 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(): @@ -49,7 +49,7 @@ class JenkinsMock(): def get_build_info(self, name, build_number): 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": return { "building": True, @@ -87,7 +87,7 @@ class JenkinsMockIdempotent(): return None 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): return None diff --git a/tests/unit/plugins/modules/test_jenkins_build_info.py b/tests/unit/plugins/modules/test_jenkins_build_info.py index a43dfdec2b..333ca620d7 100644 --- a/tests/unit/plugins/modules/test_jenkins_build_info.py +++ b/tests/unit/plugins/modules/test_jenkins_build_info.py @@ -38,7 +38,7 @@ class JenkinsBuildMock(): response["result"] = "ABSENT" return response 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(): diff --git a/tests/unit/plugins/modules/test_jenkins_credential.py b/tests/unit/plugins/modules/test_jenkins_credential.py index fe4e2f3919..fbf04f8c04 100644 --- a/tests/unit/plugins/modules/test_jenkins_credential.py +++ b/tests/unit/plugins/modules/test_jenkins_credential.py @@ -143,7 +143,7 @@ def test_clean_data_removes_extraneous_fields(): } expected = {"id": "cred1", "description": "test"} result = jenkins_credential.clean_data(data) - assert result == expected, "Expected {}, got {}".format(expected, result) + assert result == expected, f"Expected {expected}, got {result}" @patch( diff --git a/tests/unit/plugins/modules/test_jenkins_node.py b/tests/unit/plugins/modules/test_jenkins_node.py index 88f9058050..90456b4e8e 100644 --- a/tests/unit/plugins/modules/test_jenkins_node.py +++ b/tests/unit/plugins/modules/test_jenkins_node.py @@ -62,7 +62,7 @@ def assert_xml_equal(x, y): if not isinstance(y, str): y = et.tostring(y) - raise AssertionError("{} != {}".format(x, y)) + raise AssertionError(f"{x} != {y}") @fixture(autouse=True) diff --git a/tests/unit/plugins/modules/test_jenkins_plugin.py b/tests/unit/plugins/modules/test_jenkins_plugin.py index 39c087bbdd..f756547288 100644 --- a/tests/unit/plugins/modules/test_jenkins_plugin.py +++ b/tests/unit/plugins/modules/test_jenkins_plugin.py @@ -155,7 +155,7 @@ def test__get_json_data(mocker): jenkins_plugin = JenkinsPlugin(module) json_data = jenkins_plugin._get_json_data( - "{url}".format(url=GITHUB_DATA['url']), + f"{GITHUB_DATA['url']}", 'CSRF') assert isinstance(json_data, Mapping) @@ -191,7 +191,7 @@ def test__new_fallback_urls(mocker): def isInList(l, i): - print("checking if %s in %s" % (i, l)) + print(f"checking if {i} in {l}") for item in l: if item == i: return True diff --git a/tests/unit/plugins/modules/test_linode_v4.py b/tests/unit/plugins/modules/test_linode_v4.py index 2a7b13ba3c..6f0601814f 100644 --- a/tests/unit/plugins/modules/test_linode_v4.py +++ b/tests/unit/plugins/modules/test_linode_v4.py @@ -369,5 +369,5 @@ def test_user_agent_created_properly(): except ImportError: 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') diff --git a/tests/unit/plugins/modules/test_lvg_rename.py b/tests/unit/plugins/modules/test_lvg_rename.py index e6d4d6eda2..1ad650f322 100644 --- a/tests/unit/plugins/modules/test_lvg_rename.py +++ b/tests/unit/plugins/modules/test_lvg_rename.py @@ -27,12 +27,12 @@ class TestLvgRename(ModuleTestCase): 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.return_value = '/mocpath' 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.addCleanup(patched_module_run_command.stop) diff --git a/tests/unit/plugins/modules/test_monit.py b/tests/unit/plugins/modules/test_monit.py index 1c26983235..8a03c2a098 100644 --- a/tests/unit/plugins/modules/test_monit.py +++ b/tests/unit/plugins/modules/test_monit.py @@ -103,8 +103,8 @@ class MonitTest(unittest.TestCase): def test_status_value(status_name): value = getattr(monit.StatusValue, status_name.upper()) status = monit.StatusValue(value) - assert getattr(status, 'is_%s' % status_name) - assert not all(getattr(status, 'is_%s' % name) for name in monit.StatusValue.ALL_STATUS if name != status_name) + assert getattr(status, f'is_{status_name}') + assert not all(getattr(status, f'is_{name}') for name in monit.StatusValue.ALL_STATUS if name != status_name) BASIC_OUTPUT_CASES = [ diff --git a/tests/unit/plugins/modules/test_npm.py b/tests/unit/plugins/modules/test_npm.py index 2d763ec619..7a2eec1019 100644 --- a/tests/unit/plugins/modules/test_npm.py +++ b/tests/unit/plugins/modules/test_npm.py @@ -17,9 +17,9 @@ class NPMModuleTestCase(ModuleTestCase): def setUp(self): super(NPMModuleTestCase, self).setUp() 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.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.return_value = '/testbin/npm' diff --git a/tests/unit/plugins/modules/test_ocapi_command.py b/tests/unit/plugins/modules/test_ocapi_command.py index bbab1fc33c..91f32b8bf2 100644 --- a/tests/unit/plugins/modules/test_ocapi_command.py +++ b/tests/unit/plugins/modules/test_ocapi_command.py @@ -101,63 +101,63 @@ def is_changed(ansible_exit_json): def mock_get_request(*args, **kwargs): """Mock for get_request.""" 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 elif url == "mock_location": 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): """Mock for get_request.""" 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 - 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 - 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): 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 - 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 - 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): 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 - 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 - 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): """Mock put_request.""" url = args[1] - if url == 'https://' + MOCK_BASE_URI: + if url == f"https://{MOCK_BASE_URI}": 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): """Mock delete request.""" 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 - raise RuntimeError("Illegal DELETE call to: " + args[1]) + raise RuntimeError(f"Illegal DELETE call to: {args[1]}") def mock_post_request(*args, **kwargs): """Mock post_request.""" 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 - raise RuntimeError("Illegal POST call to: " + args[1]) + raise RuntimeError(f"Illegal POST call to: {args[1]}") 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): """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): diff --git a/tests/unit/plugins/modules/test_ocapi_info.py b/tests/unit/plugins/modules/test_ocapi_info.py index 06f3dfc5ab..eb5ce7dfcb 100644 --- a/tests/unit/plugins/modules/test_ocapi_info.py +++ b/tests/unit/plugins/modules/test_ocapi_info.py @@ -88,31 +88,31 @@ def get_exception_message(ansible_exit_json): def mock_get_request(*args, **kwargs): """Mock for get_request.""" url = args[1] - if url == "https://" + MOCK_BASE_URI: + if url == f"https://{MOCK_BASE_URI}": 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 - 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 - 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 else: - raise RuntimeError("Illegal GET call to: " + args[1]) + raise RuntimeError(f"Illegal GET call to: {args[1]}") def mock_put_request(*args, **kwargs): """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): """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): """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): diff --git a/tests/unit/plugins/modules/test_oneview_network_set.py b/tests/unit/plugins/modules/test_oneview_network_set.py index 5607eb5426..4aeb960751 100644 --- a/tests/unit/plugins/modules/test_oneview_network_set.py +++ b/tests/unit/plugins/modules/test_oneview_network_set.py @@ -29,7 +29,7 @@ PARAMS_WITH_CHANGES = dict( config='config.json', state='present', 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']) ) @@ -80,7 +80,7 @@ class NetworkSetModuleSpec(unittest.TestCase, ) 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', '/rest/ethernet-networks/ddd-eee-fff'] ) @@ -109,7 +109,7 @@ class NetworkSetModuleSpec(unittest.TestCase, self.mock_ansible_module.fail_json.assert_called_once_with( 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): diff --git a/tests/unit/plugins/modules/test_pkgin.py b/tests/unit/plugins/modules/test_pkgin.py index 6de9a2e4b6..e4378eb828 100644 --- a/tests/unit/plugins/modules/test_pkgin.py +++ b/tests/unit/plugins/modules/test_pkgin.py @@ -22,7 +22,7 @@ class TestPkginQueryPackage(unittest.TestCase): parseable_flag_not_supported = 1 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), - (0, "%s-1.21.0 = C/C++ package manager" % package, None), + (0, f"{package}-1.21.0 = C/C++ package manager", None), ] # when @@ -38,7 +38,7 @@ class TestPkginQueryPackage(unittest.TestCase): parseable_flag_not_supported = 1 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), - (0, "%s = C/C++ package manager" % package, None), + (0, f"{package} = C/C++ package manager", None), ] # when @@ -102,7 +102,7 @@ class TestPkginQueryPackage(unittest.TestCase): parseable_flag_not_supported = 1 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), - (1, None, "No results found for %s" % package), + (1, None, f"No results found for {package}"), ] # when @@ -118,7 +118,7 @@ class TestPkginQueryPackage(unittest.TestCase): parseable_flag_supported = 0 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), - (0, "%s-1.21.0;=;C/C++ package manager" % package, None), + (0, f"{package}-1.21.0;=;C/C++ package manager", None), ] # when @@ -134,7 +134,7 @@ class TestPkginQueryPackage(unittest.TestCase): parseable_flag_not_supported = 1 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), - (0, "%s-1.21.0 = C/C++ package manager" % package, None), + (0, f"{package}-1.21.0 = C/C++ package manager", None), ] # when diff --git a/tests/unit/plugins/modules/test_rpm_ostree_pkg.py b/tests/unit/plugins/modules/test_rpm_ostree_pkg.py index 6b7e3aaebf..70a23f0a20 100644 --- a/tests/unit/plugins/modules/test_rpm_ostree_pkg.py +++ b/tests/unit/plugins/modules/test_rpm_ostree_pkg.py @@ -17,9 +17,9 @@ class RpmOSTreeModuleTestCase(ModuleTestCase): def setUp(self): super(RpmOSTreeModuleTestCase, self).setUp() 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.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.return_value = '/testbin/rpm-ostree' diff --git a/tests/unit/plugins/modules/test_rundeck_acl_policy.py b/tests/unit/plugins/modules/test_rundeck_acl_policy.py index 2597d97dc9..597b569b71 100644 --- a/tests/unit/plugins/modules/test_rundeck_acl_policy.py +++ b/tests/unit/plugins/modules/test_rundeck_acl_policy.py @@ -62,7 +62,7 @@ def test_acl_create(api_request_mock, project, prefix): # should have done GET → POST → GET assert api_request_mock.call_count == 3 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' @@ -91,7 +91,7 @@ def test_acl_unchanged(api_request_mock, project, prefix): # only a single GET assert api_request_mock.call_count == 1 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 assert kwargs.get('method', 'GET') == 'GET' @@ -123,7 +123,7 @@ def test_acl_remove(api_request_mock, project, prefix): # GET → DELETE assert api_request_mock.call_count == 2 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' @@ -151,5 +151,5 @@ def test_acl_remove_nonexistent(api_request_mock, project, prefix): # only the initial GET assert api_request_mock.call_count == 1 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' diff --git a/tests/unit/plugins/modules/test_scaleway_compute_private_network.py b/tests/unit/plugins/modules/test_scaleway_compute_private_network.py index 0f048ceec3..15d0a69412 100644 --- a/tests/unit/plugins/modules/test_scaleway_compute_private_network.py +++ b/tests/unit/plugins/modules/test_scaleway_compute_private_network.py @@ -74,7 +74,7 @@ def test_scaleway_add_nic(capfd): os.environ['SCW_API_TOKEN'] = 'notrealtoken' pnid = 'b589b4cd-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({ "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", @@ -103,7 +103,7 @@ def test_scaleway_add_existing_nic(capfd): os.environ['SCW_API_TOKEN'] = 'notrealtoken' pnid = 'b589b4cd-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({ "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", @@ -130,8 +130,8 @@ def test_scaleway_remove_existing_nic(capfd): pnid = 'b589b4cd-ef5g-678h-90i1-jk2345678l90' cid = 'c004b4cd-ef5g-678h-90i1-jk2345678l90' nicid = 'c123b4cd-ef5g-678h-90i1-jk2345678l90' - url = 'servers/' + cid + '/private_nics' - urlremove = 'servers/' + cid + '/private_nics/' + nicid + url = f"servers/{cid}/private_nics" + urlremove = f"servers/{cid}/private_nics/{nicid}" with set_module_args({ "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", @@ -161,7 +161,7 @@ def test_scaleway_remove_absent_nic(capfd): os.environ['SCW_API_TOKEN'] = 'notrealtoken' pnid = 'b589b4cd-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({ "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", diff --git a/tests/unit/plugins/modules/test_solaris_zone.py b/tests/unit/plugins/modules/test_solaris_zone.py index 67f79b20a1..5c4dcc7075 100644 --- a/tests/unit/plugins/modules/test_solaris_zone.py +++ b/tests/unit/plugins/modules/test_solaris_zone.py @@ -103,7 +103,7 @@ def test_zone_create_invalid_names(mocked_zone_create, capfd): { "name": invalid_name, "state": "installed", - "path": "/zones/" + invalid_name, + "path": f"/zones/{invalid_name}", "_ansible_check_mode": False, } ): diff --git a/tests/unit/plugins/modules/test_ss_3par_cpg.py b/tests/unit/plugins/modules/test_ss_3par_cpg.py index 1510347fb1..64c0eab7e6 100644 --- a/tests/unit/plugins/modules/test_ss_3par_cpg.py +++ b/tests/unit/plugins/modules/test_ss_3par_cpg.py @@ -197,7 +197,7 @@ def test_create_cpg(mock_client): 8, 'MAG', 'FC' - ) == (True, True, "Created CPG %s successfully." % 'test_cpg') + ) == (True, True, "Created CPG test_cpg successfully.") mock_client.HPE3ParClient.cpgExists.return_value = True 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, 'test_cpg' - ) == (True, True, "Deleted CPG %s successfully." % 'test_cpg') + ) == (True, True, "Deleted CPG test_cpg successfully.") mock_client.HPE3ParClient.cpgExists.return_value = False diff --git a/tests/unit/plugins/modules/test_ufw.py b/tests/unit/plugins/modules/test_ufw.py index 9c796adb1a..9131dc7f96 100644 --- a/tests/unit/plugins/modules/test_ufw.py +++ b/tests/unit/plugins/modules/test_ufw.py @@ -30,10 +30,8 @@ To Action From -- ------ ----""" -ufw_status_verbose_with_port_7000 = ufw_verbose_header + """ -7000/tcp ALLOW IN Anywhere -7000/tcp (v6) ALLOW IN Anywhere (v6) -""" +ufw_status_verbose_with_port_7000 = ( + f"{ufw_verbose_header}\n7000/tcp ALLOW IN Anywhere\n7000/tcp (v6) ALLOW IN Anywhere (v6)\n") 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 @@ -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 """ -ufw_status_verbose_with_ipv6 = ufw_verbose_header + """ -5353/udp ALLOW IN 224.0.0.251 -5353/udp ALLOW IN ff02::fb -""" +ufw_status_verbose_with_ipv6 = ( + f"{ufw_verbose_header}\n5353/udp ALLOW IN 224.0.0.251\n5353/udp ALLOW IN ff02::fb\n") ufw_status_verbose_nothing = ufw_verbose_header diff --git a/tests/unit/plugins/modules/test_usb_facts.py b/tests/unit/plugins/modules/test_usb_facts.py index bb44103e97..f5cc91827e 100644 --- a/tests/unit/plugins/modules/test_usb_facts.py +++ b/tests/unit/plugins/modules/test_usb_facts.py @@ -17,7 +17,7 @@ def get_bin_path(self, arg, required=False): return '/usr/bin/lsusb' else: if required: - fail_json(msg='%r not found !' % arg) + fail_json(msg=f'{arg!r} not found !') class TestUsbFacts(unittest.TestCase): @@ -61,7 +61,7 @@ class TestUsbFacts(unittest.TestCase): def test_parsing_multiple_lines(self): input = "" 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: mock_run_command.return_value = 0, input, None with self.assertRaises(AnsibleExitJson) as result: diff --git a/tests/unit/plugins/modules/test_wdc_redfish_command.py b/tests/unit/plugins/modules/test_wdc_redfish_command.py index 02b9c1ca35..ab397cc0cb 100644 --- a/tests/unit/plugins/modules/test_wdc_redfish_command.py +++ b/tests/unit/plugins/modules/test_wdc_redfish_command.py @@ -222,7 +222,7 @@ def mock_get_request_enclosure_single_tenant(*args, **kwargs): elif args[1].endswith("/UpdateService"): return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_AND_FW_ACTIVATE 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): @@ -240,7 +240,7 @@ def mock_get_request_enclosure_multi_tenant(*args, **kwargs): elif args[1].endswith("/IOModuleBFRU"): return MOCK_GET_IOM_B_MULTI_TENANAT 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): @@ -252,7 +252,7 @@ def mock_get_request(*args, **kwargs): elif args[1].endswith("Chassis/Enclosure"): return MOCK_SUCCESSFUL_RESPONSE_CHASSIS_ENCLOSURE 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): @@ -268,7 +268,7 @@ def mock_post_request(*args, **kwargs): "ret": True, "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): @@ -570,10 +570,7 @@ class TestWdcRedfishCommand(unittest.TestCase): """Test Update and Activate when target is not in the correct state.""" mock_status_code = 999 mock_status_description = "mock status description" - expected_error_message = "Target is not ready for FW update. Current status: {0} ({1})".format( - mock_status_code, - mock_status_description - ) + expected_error_message = f"Target is not ready for FW update. Current status: {mock_status_code} ({mock_status_description})" with set_module_args({ 'category': 'Update', '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.close() 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. """ - 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") - 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) with open(package_filename_path, "w"): pass diff --git a/tests/unit/plugins/modules/test_wdc_redfish_info.py b/tests/unit/plugins/modules/test_wdc_redfish_info.py index 82cf9103b7..7dcfa7ba43 100644 --- a/tests/unit/plugins/modules/test_wdc_redfish_info.py +++ b/tests/unit/plugins/modules/test_wdc_redfish_info.py @@ -205,7 +205,7 @@ class TestWdcRedfishInfo(unittest.TestCase): elif uri.endswith("/UpdateService"): return MOCK_SUCCESSFUL_RESPONSE_WITH_SIMPLE_UPDATE_BUT_NO_FW_ACTIVATE 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: mock_get_request.side_effect = mock_get_request_function diff --git a/tests/unit/plugins/modules/uthelper.py b/tests/unit/plugins/modules/uthelper.py index ee930744ec..7c420af0b7 100644 --- a/tests/unit/plugins/modules/uthelper.py +++ b/tests/unit/plugins/modules/uthelper.py @@ -37,7 +37,7 @@ class UTHelper(object): with open(test_spec_filename, "r") as test_spec_filehandle: 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): 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) 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 {} @@ -125,22 +125,11 @@ class ModuleTestCase: self._fixtures = {} def __str__(self): - return "".format( - id=self.id, - input="input " if self.input else "", - output="output " if self.output else "", - mocks="({0})".format(", ".join(self.mocks.keys())), - flags=self.flags - ) + return (f"") def __repr__(self): - return "ModuleTestCase(id={id}, input={input}, output={output}, mocks={mocks}, flags={flags})".format( - id=self.id, - input=self.input, - output=self.output, - mocks=repr(self.mocks), - flags=self.flags - ) + return f"ModuleTestCase(id={self.id}, input={self.input}, output={self.output}, mocks={self.mocks!r}, flags={self.flags})" @staticmethod def make_test_case(test_case_spec, test_module, mocks_map): @@ -159,7 +148,7 @@ class ModuleTestCase: try: mock_class = mocks_map[mock_name] 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._fixtures.update(self.mocks[mock_name].fixtures()) @@ -184,14 +173,14 @@ class ModuleTestCase: mock.setup(mocker) def check_testcase(self, results): - print("testcase =\n%s" % repr(self)) - print("results =\n%s" % results) + print(f"testcase =\n{self!r}") + print(f"results =\n{results}") if 'exception' in results: - print("exception = \n%s" % results["exception"]) + print(f"exception = \n{results['exception']}") for test_result in self.output: 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): for mock in self.mocks.values(): @@ -229,7 +218,7 @@ class RunCommandMock(TestCaseMock): @pytest.fixture def patch_bin(mocker): 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) return {"patch_bin": patch_bin} @@ -245,7 +234,7 @@ class RunCommandMock(TestCaseMock): def side_effect(self_, **kwargs): result = next(results) 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 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): 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] - print("call args list =\n%s" % call_args_list) - print("expected args list =\n%s" % expected_call_args_list) + print(f"call args list =\n{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: assert call_args_list == expected_call_args_list diff --git a/tests/unit/plugins/modules/xenserver_common.py b/tests/unit/plugins/modules/xenserver_common.py index 49320ce84e..097e718651 100644 --- a/tests/unit/plugins/modules/xenserver_common.py +++ b/tests/unit/plugins/modules/xenserver_common.py @@ -7,4 +7,4 @@ from __future__ import annotations def fake_xenapi_ref(xenapi_class): - return "OpaqueRef:fake-xenapi-%s-ref" % xenapi_class + return f"OpaqueRef:fake-xenapi-{xenapi_class}-ref"