From a5c90ee635d02c2e13b9dda03c92b1948348a0cf Mon Sep 17 00:00:00 2001 From: N3N Date: Sun, 8 Dec 2024 09:15:55 -0800 Subject: [PATCH] refactor: ruff format src and tests --- src/whispr/utils/io.py | 2 ++ src/whispr/utils/process.py | 7 +++---- tests/test_factory.py | 4 +++- tests/test_gcp.py | 4 +--- tests/test_io_utils.py | 10 +++++++--- tests/test_process_utils.py | 20 +++++++++++++++----- tests/test_vault_utils.py | 24 +++++++++++++++++------- 7 files changed, 48 insertions(+), 23 deletions(-) diff --git a/src/whispr/utils/io.py b/src/whispr/utils/io.py index 90c46c4..4dd9d34 100644 --- a/src/whispr/utils/io.py +++ b/src/whispr/utils/io.py @@ -4,6 +4,7 @@ from whispr.logging import logger + def write_to_yaml_file(config: dict, file_path: str): """Writes a given config object to a file in YAML format""" if not os.path.exists(file_path): @@ -11,6 +12,7 @@ def write_to_yaml_file(config: dict, file_path: str): yaml.dump(config, file) logger.info(f"{file_path} has been created.") + def load_config(file_path: str) -> dict: """Loads a given config file""" try: diff --git a/src/whispr/utils/process.py b/src/whispr/utils/process.py index 501f8bd..9bbb8d9 100644 --- a/src/whispr/utils/process.py +++ b/src/whispr/utils/process.py @@ -4,9 +4,10 @@ from whispr.logging import logger + def execute_command(command: tuple, no_env: bool, secrets: dict): """Executes a Unix/Windows command. - Arg: `no_env` decides whether secrets are passed vai environment or K:V pairs in command arguments. + Arg: `no_env` decides whether secrets are passed vai environment or K:V pairs in command arguments. """ if not secrets: secrets = {} @@ -16,9 +17,7 @@ def execute_command(command: tuple, no_env: bool, secrets: dict): if no_env: # Pass as --env K=V format (secure) - usr_command.extend([ - f"{k}={v}" for k,v in secrets.items() - ]) + usr_command.extend([f"{k}={v}" for k, v in secrets.items()]) else: # Pass via environment (slightly insecure) os.environ.update(secrets) diff --git a/tests/test_factory.py b/tests/test_factory.py index 1594373..bf27c99 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -83,7 +83,8 @@ def test_get_azure_vault_client_no_url(self): with self.assertRaises(ValueError): VaultFactory.get_vault(**config) - def test_get_gcp_vault_client(self): + @patch("google.cloud.secretmanager.SecretManagerServiceClient") + def test_get_gcp_vault_client(self, mock_client): """Test GCPVault client""" config = { "vault": "gcp", @@ -94,6 +95,7 @@ def test_get_gcp_vault_client(self): } vault_instance = VaultFactory.get_vault(**config) self.assertIsInstance(vault_instance, GCPVault) + mock_client.assert_called_once() def test_get_gcp_vault_client_no_project_id(self): """Test GCPVault raises exception when project_id is not defined in config""" diff --git a/tests/test_gcp.py b/tests/test_gcp.py index 71c70c0..e1c2d91 100644 --- a/tests/test_gcp.py +++ b/tests/test_gcp.py @@ -1,12 +1,10 @@ """Tests for GCP module""" import unittest -from unittest.mock import Mock, patch, MagicMock +from unittest.mock import MagicMock import google.api_core.exceptions -import structlog -from whispr.vault import SimpleVault from whispr.gcp import GCPVault diff --git a/tests/test_io_utils.py b/tests/test_io_utils.py index ee9e619..0b02c0f 100644 --- a/tests/test_io_utils.py +++ b/tests/test_io_utils.py @@ -1,4 +1,3 @@ - import os import yaml import unittest @@ -6,6 +5,7 @@ from unittest.mock import MagicMock, patch, mock_open from whispr.utils.io import write_to_yaml_file, load_config + class IOUtilsTestCase(unittest.TestCase): """Unit tests for the file utilities: write_to_yaml_file and load_config.""" @@ -18,7 +18,9 @@ def setUp(self): @patch("whispr.utils.io.logger", new_callable=lambda: MagicMock()) @patch("builtins.open", new_callable=mock_open) @patch("os.path.exists", return_value=False) - def test_write_to_yaml_file_creates_file(self, mock_exists, mock_open_file, mock_logger): + def test_write_to_yaml_file_creates_file( + self, mock_exists, mock_open_file, mock_logger + ): """Test that write_to_yaml_file creates a new file and writes config data as YAML.""" write_to_yaml_file(self.config, self.file_path) @@ -29,7 +31,9 @@ def test_write_to_yaml_file_creates_file(self, mock_exists, mock_open_file, mock @patch("whispr.utils.io.logger", new_callable=lambda: MagicMock()) @patch("builtins.open", new_callable=mock_open) @patch("os.path.exists", return_value=True) - def test_write_to_yaml_file_does_not_overwrite_existing_file(self, mock_exists, mock_open_file, mock_logger): + def test_write_to_yaml_file_does_not_overwrite_existing_file( + self, mock_exists, mock_open_file, mock_logger + ): """Test that write_to_yaml_file does not overwrite an existing file.""" write_to_yaml_file(self.config, self.file_path) diff --git a/tests/test_process_utils.py b/tests/test_process_utils.py index b0861c6..ac01dad 100644 --- a/tests/test_process_utils.py +++ b/tests/test_process_utils.py @@ -23,22 +23,30 @@ def test_execute_command_with_no_env(self, mock_subprocess_run, mock_logger): execute_command(self.command, self.no_env, self.secrets) expected_command = ["echo", "Hello", "API_KEY=123456"] - mock_subprocess_run.assert_called_once_with(expected_command, env=os.environ, shell=False, check=True) + mock_subprocess_run.assert_called_once_with( + expected_command, env=os.environ, shell=False, check=True + ) @patch("whispr.utils.process.logger", new_callable=lambda: MagicMock()) @patch("subprocess.run") @patch("os.environ.update") - def test_execute_command_with_env(self, mock_env_update, mock_subprocess_run, mock_logger): + def test_execute_command_with_env( + self, mock_env_update, mock_subprocess_run, mock_logger + ): """Test execute_command with `no_env=False`, passing secrets via environment variables.""" execute_command(self.command, no_env=False, secrets=self.secrets) mock_env_update.assert_called_once_with(self.secrets) expected_command = ["echo", "Hello"] - mock_subprocess_run.assert_called_once_with(expected_command, env=os.environ, shell=False, check=True) + mock_subprocess_run.assert_called_once_with( + expected_command, env=os.environ, shell=False, check=True + ) @patch("whispr.utils.process.logger", new_callable=lambda: MagicMock()) @patch("subprocess.run", side_effect=subprocess.CalledProcessError(1, "test")) - def test_execute_command_called_process_error(self, mock_subprocess_run, mock_logger): + def test_execute_command_called_process_error( + self, mock_subprocess_run, mock_logger + ): """Test execute_command handles CalledProcessError and logs an error message.""" with self.assertRaises(subprocess.CalledProcessError): execute_command(self.command, no_env=True, secrets=self.secrets) @@ -54,5 +62,7 @@ def test_execute_command_without_secrets(self, mock_subprocess_run, mock_logger) execute_command(self.command, no_env=True, secrets={}) expected_command = ["echo", "Hello"] - mock_subprocess_run.assert_called_once_with(expected_command, env=os.environ, shell=False, check=True) + mock_subprocess_run.assert_called_once_with( + expected_command, env=os.environ, shell=False, check=True + ) mock_logger.error.assert_not_called() diff --git a/tests/test_vault_utils.py b/tests/test_vault_utils.py index bd74bbe..fe066f7 100644 --- a/tests/test_vault_utils.py +++ b/tests/test_vault_utils.py @@ -43,18 +43,28 @@ def test_fetch_secrets_missing_config(self, mock_logger): ) @patch("whispr.utils.vault.logger", new_callable=lambda: MagicMock()) - @patch("whispr.utils.vault.VaultFactory.get_vault", side_effect=ValueError("Invalid vault type")) + @patch( + "whispr.utils.vault.VaultFactory.get_vault", + side_effect=ValueError("Invalid vault type"), + ) def test_fetch_secrets_invalid_vault(self, mock_get_vault, mock_logger): """Test fetch_secrets logs an error if the vault factory raises a ValueError.""" - result = fetch_secrets({ - "vault": "UNKOWN", - "secret_name": "test_secret", - }) + result = fetch_secrets( + { + "vault": "UNKOWN", + "secret_name": "test_secret", + } + ) self.assertEqual(result, {}) - mock_logger.error.assert_called_once_with("Error creating vault instance: Invalid vault type") + mock_logger.error.assert_called_once_with( + "Error creating vault instance: Invalid vault type" + ) - @patch("whispr.utils.vault.dotenv_values", return_value={"API_KEY": "", "OTHER_KEY": ""}) + @patch( + "whispr.utils.vault.dotenv_values", + return_value={"API_KEY": "", "OTHER_KEY": ""}, + ) @patch("whispr.utils.vault.logger", new_callable=lambda: MagicMock()) def test_get_filled_secrets_partial_match(self, mock_logger, mock_dotenv_values): """Test get_filled_secrets fills only matching secrets from vault_secrets."""