diff --git a/penify_hook/api_client.py b/penify_hook/api_client.py index 6c527eb..e045750 100644 --- a/penify_hook/api_client.py +++ b/penify_hook/api_client.py @@ -63,9 +63,9 @@ def generate_commit_summary(self, git_diff, instruction: str = "", repo_details Args: git_diff (str): The git diff of the commit. - instruction (str??): Additional instruction for the commit. Defaults to "". - repo_details (dict??): Details of the git repository. Defaults to None. - jira_context (dict??): JIRA issue details to enhance the commit summary. Defaults to None. + instruction (str?): Additional instruction for the commit. Defaults to "". + repo_details (dict?): Details of the git repository. Defaults to None. + jira_context (dict?): JIRA issue details to enhance the commit summary. Defaults to None. Returns: dict: The response from the API if the request is successful, None otherwise. diff --git a/penify_hook/commands/auth_commands.py b/penify_hook/commands/auth_commands.py index b8b4a1c..61460bc 100644 --- a/penify_hook/commands/auth_commands.py +++ b/penify_hook/commands/auth_commands.py @@ -12,11 +12,15 @@ def save_credentials(api_key): """Save or update the API keys in the .penify file in the user's home directory. + This function reads the existing .penify file (if it exists), updates + the API key, and writes it back to the file. If the file does not exist, + it creates a new one with the provided API key. + Args: api_key (str): The new API key to be saved or updated. Returns: - bool: if the credentials were successfully saved, False otherwise. + bool: True if the credentials were successfully saved, False otherwise. """ home_dir = Path.home() penify_file = home_dir / '.penify' diff --git a/penify_hook/commands/commit_commands.py b/penify_hook/commands/commit_commands.py index a9d93f8..ab59899 100644 --- a/penify_hook/commands/commit_commands.py +++ b/penify_hook/commands/commit_commands.py @@ -8,22 +8,23 @@ def commit_code(api_url, token, message, open_terminal, generate_description, llm_model=None, llm_api_base=None, llm_api_key=None, jira_url=None, jira_user=None, jira_api_token=None): - """Enhance Git commits with AI-powered commit messages. + """Generate enhanced Git commits with AI-powered commit messages. - This function allows for the generation of enhanced commit messages - using natural language processing models and optionally integrates with - JIRA for additional context. It processes the current Git folder to find - relevant files and generates a detailed commit message based on the - provided parameters. + This function processes the current Git folder to find relevant files + and generates a detailed commit message using natural language + processing models. It optionally integrates with JIRA for additional + context based on provided parameters. The function requires + authentication tokens for both the API and potentially JIRA. Args: api_url (str): URL of the API endpoint. token (str): Authentication token for the API. message (str): Initial commit message provided by the user. open_terminal (bool): Whether to open the terminal after committing. - generate_description (bool): Whether to generate a detailed description in the commit message. - llm_model (str?): The language model to use for generating the commit message. Defaults to - None. + generate_description (bool): Whether to generate a detailed description + in the commit message. + llm_model (str?): The language model to use for generating the + commit message. Defaults to None. llm_api_base (str?): Base URL of the LLM API. Defaults to None. llm_api_key (str?): API key for accessing the LLM service. Defaults to None. jira_url (str?): URL of the JIRA instance. Defaults to None. diff --git a/penify_hook/commands/config_commands.py b/penify_hook/commands/config_commands.py index 518042a..07270e1 100644 --- a/penify_hook/commands/config_commands.py +++ b/penify_hook/commands/config_commands.py @@ -95,7 +95,8 @@ def save_jira_config(url, username, api_token): This function reads existing JIRA configuration from the .penify file, updates or adds new JIRA configuration details, and writes it back to - the file. + the file. If the .penify file does not exist or is invalid JSON, it will + be created or corrected. Args: url (str): The URL of the JIRA instance. @@ -157,11 +158,12 @@ def get_llm_config(): return {} def get_jira_config(): - """Get JIRA configuration from the .penify file. + """Retrieve JIRA configuration from a JSON file specified in the .penify + file. - This function reads the JIRA configuration from a JSON file specified in - the .penify file. If the .penify file exists and contains valid JSON - with a 'jira' key, it returns the corresponding configuration. + This function reads the JIRA configuration from a JSON file designated + in the .penify file. If the .penify file is present and contains valid + JSON with a 'jira' key, it returns the corresponding configuration. Otherwise, it returns an empty dictionary. Returns: @@ -184,7 +186,7 @@ def config_llm_web(): This function starts a temporary HTTP server that serves an HTML template for configuring Large Language Model (LLM) settings. It handles GET and POST requests to retrieve the current configuration, save new - configurations, and suppress log messages. The server runs on a random + configurations, and suppress log messages. The server runs on a random port between 30000 and 50000, and it is accessible via a URL like http://localhost:. The function opens this URL in the default web browser for configuration. Once configured, the server shuts @@ -328,8 +330,8 @@ def do_GET(self): This function processes GET requests based on the path requested. It serves an HTML template for the root path, returns a JSON configuration - for a specific endpoint, and handles any other paths by returning a 404 - error. + for a specific endpoint ("/get_config"), and handles any other paths by + returning a 404 error. """ if self.path == "/": @@ -437,7 +439,7 @@ def log_message(self, format, *args): print("Configuration completed.") def get_token(): - """Get the token based on priority from environment variables or + """Get the API token based on priority from environment variables or configuration files. Returns: diff --git a/penify_hook/commands/doc_commands.py b/penify_hook/commands/doc_commands.py index 5fb3273..a9bfda0 100644 --- a/penify_hook/commands/doc_commands.py +++ b/penify_hook/commands/doc_commands.py @@ -6,18 +6,17 @@ def generate_doc(api_url, token, location=None): """Generates documentation based on the given parameters. - This function initializes an API client using the provided API URL and - token. It then generates documentation by analyzing the specified - location, which can be a folder, a file, or the current working - directory if no location is provided. The function handles different - types of analysis based on the input location and reports any errors - encountered during the process. + Initializes an API client using the provided API URL and token. It then + generates documentation by analyzing the specified location (folder, + file, or current working directory if not provided), handling different + types of analysis, and reporting any errors encountered during the + process. Args: api_url (str): The URL of the API to connect to for documentation generation. token (str): The authentication token for accessing the API. - location (str?): The path to a specific file or folder to analyze. If not provided, the - current working directory is used. + location (str??): The path to a specific file or folder to analyze. If not provided, + the current working directory is used. """ import os @@ -90,6 +89,10 @@ def setup_docgen_parser(parser): Args: parser (argparse.ArgumentParser): The parser to configure. + + Returns: + None: This function does not return anything but configures the provided + parser. """ # We don't need to create a new docgen_parser since it's passed as a parameter diff --git a/penify_hook/commands/hook_commands.py b/penify_hook/commands/hook_commands.py index 1a49bfe..a7476c9 100644 --- a/penify_hook/commands/hook_commands.py +++ b/penify_hook/commands/hook_commands.py @@ -12,7 +12,11 @@ def install_git_hook(location, token): """Install a post-commit hook in the specified location that generates documentation - for changed files after each commit. + for changed files after each commit. This function creates a new file + named 'post-commit' in the '.git/hooks' directory of the specified Git + repository. The hook script will use the provided authentication token + to access and generate documentation for any changes made during + commits. Args: location (str): The path to the Git repository where the hook should be installed. diff --git a/penify_hook/commit_analyzer.py b/penify_hook/commit_analyzer.py index 31ab46b..5364e6a 100644 --- a/penify_hook/commit_analyzer.py +++ b/penify_hook/commit_analyzer.py @@ -113,6 +113,11 @@ def run(self, msg: Optional[str], edit_commit_message: bool, generate_descriptio def process_jira_integration(self, title: str, description: str, msg: str) -> tuple: """Process JIRA integration for the commit message. + This function processes the provided commit title, description, and user + message to look for JIRA issue keys. It extracts issue keys from the + message content, branch name, and adds comments to the corresponding + JIRA issues. + Args: title (str): Generated commit title. description (str): Generated commit description. diff --git a/penify_hook/file_analyzer.py b/penify_hook/file_analyzer.py index c161afc..5cb6182 100644 --- a/penify_hook/file_analyzer.py +++ b/penify_hook/file_analyzer.py @@ -103,10 +103,10 @@ def process_file(self, file_path, pbar): return False def print_processing(self, file_path): - """Print a processing message for a file. + """Print a processing message for a specified file. Args: - file_path (str): The path to the file being processed. + file_path (str): The path to the file that is being processed. """ formatted_path = format_file_path(file_path) print(f"\n{format_highlight(f'Processing file: {formatted_path}')}") diff --git a/penify_hook/folder_analyzer.py b/penify_hook/folder_analyzer.py index 15ec20f..093770b 100644 --- a/penify_hook/folder_analyzer.py +++ b/penify_hook/folder_analyzer.py @@ -14,10 +14,10 @@ def __init__(self, dir_path: str, api_client: APIClient): def list_all_files_in_dir(self, dir_path: str): """List all non-hidden files in a directory and its subdirectories. - This function recursively traverses the specified directory and its - subdirectories, collecting paths of all non-hidden files. It filters out - hidden directories and files (those starting with a dot) to ensure only - visible files are returned. + Recursively traverses the specified directory and its subdirectories, + collecting paths of all non-hidden files. Hidden directories and files + (those starting with a dot) are excluded to ensure only visible files + are returned. Args: dir_path (str): The path to the directory whose files and subdirectory files need to be @@ -25,7 +25,8 @@ def list_all_files_in_dir(self, dir_path: str): Returns: list: A list containing the full paths of all non-hidden files within the - specified directory and its subdirectories. + specified directory + and its subdirectories. """ files = [] diff --git a/penify_hook/git_analyzer.py b/penify_hook/git_analyzer.py index f9e7127..c3ae31d 100644 --- a/penify_hook/git_analyzer.py +++ b/penify_hook/git_analyzer.py @@ -92,13 +92,12 @@ def process_file(self, file_path): """Process a file by checking its type, reading its content, and sending it to an API. - This method constructs the absolute path of the specified file and - verifies if the file has a valid extension. If the file type is - supported, it reads the content of the file and retrieves the - differences from the last commit in the repository. If changes are - detected, it sends the file content along with the modified lines to an - API for further processing. If the API response indicates no changes, - the original file will not be overwritten. + This method constructs the absolute path of the specified file, verifies + if the file has a valid extension, reads the content of the file, + retrieves the differences from the last commit in the repository. If + changes are detected, it sends the file content along with the modified + lines to an API for further processing. If the API response indicates no + changes, the original file will not be overwritten. Args: file_path (str): The relative path to the file to be processed. @@ -160,6 +159,9 @@ def run(self): processing, printing an error message for each file that fails to process. If any modifications are made to the files, an auto-commit is created to save those changes. + + Args: + self (DocGenHook): An instance of the DocGenHook class. """ logger.info("Starting doc_gen_hook processing") print_info("Starting doc_gen_hook processing") diff --git a/penify_hook/jira_client.py b/penify_hook/jira_client.py index 56d2e22..d90dbc9 100644 --- a/penify_hook/jira_client.py +++ b/penify_hook/jira_client.py @@ -51,18 +51,17 @@ def is_connected(self) -> bool: and `False` otherwise. Returns: - bool: True if the JIRA client is connected, False otherwise + bool: True if the JIRA client is connected, False otherwise. """ return self.jira_client is not None def extract_issue_keys_from_branch(self, branch_name: str) -> List[str]: """Extracts JIRA issue keys from a branch name. - This function searches through a given git branch name to find and - return any JIRA issue keys that match the pattern. Common conventions - for JIRA issue keys in branch names include: - - feature/PROJECT-123-description - bugfix/PROJECT-123-fix-something - - hotfix/PROJECT-123/short-desc + Searches through a given git branch name to find and return any JIRA + issue keys that match the pattern. Common conventions for JIRA issue + keys in branch names include: - feature/PROJECT-123-description - + bugfix/PROJECT-123-fix-something - hotfix/PROJECT-123/short-desc Args: branch_name (str): The name of the git branch to search for JIRA issue keys. @@ -146,11 +145,11 @@ def add_comment(self, issue_key: str, comment: str) -> bool: """Add a comment to a JIRA issue. Args: - issue_key (str): JIRA issue key (e.g., "PROJECT-123") - comment (str): Comment text to add + issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). + comment (str): The text of the comment to be added. Returns: - bool: True if the comment was added successfully, False otherwise + bool: True if the comment was added successfully, False otherwise. """ if not self.is_connected(): logging.warning("JIRA client not connected") diff --git a/penify_hook/llm_client.py b/penify_hook/llm_client.py index e5fe2b2..a463895 100644 --- a/penify_hook/llm_client.py +++ b/penify_hook/llm_client.py @@ -26,7 +26,7 @@ def __init__(self, model: str = None, api_base: str = None, api_key: str = None) os.environ["OPENAI_API_KEY"] = api_key def generate_commit_summary(self, diff: str, message: str, generate_description: bool, repo_details: Dict, jira_context: Dict = None) -> Dict: - """Generate a commit summary using the LLM. + """Generates a commit summary using the LLM. This function generates a concise and descriptive commit summary based on the provided Git diff, user instructions, repository details, and @@ -46,7 +46,7 @@ def generate_commit_summary(self, diff: str, message: str, generate_description: Returns: Dict: A dictionary containing the title and description for the commit. If generate_description is False, - the 'description' key may be absent. + the 'description' key may be absent. Raises: ValueError: If the LLM model is not configured. diff --git a/penify_hook/login_command.py b/penify_hook/login_command.py index 2d97cc3..e61ea2a 100644 --- a/penify_hook/login_command.py +++ b/penify_hook/login_command.py @@ -13,8 +13,8 @@ def handle_login(args): args (argparse.Namespace): Parsed arguments containing necessary parameters for the login command. Returns: - None: This function does not return any value; it is expected to handle the - login process internally. + None: This function does not return any value; it is expected to handle + the login process internally. """ from penify_hook.constants import API_URL, DASHBOARD_URL diff --git a/penify_hook/main.py b/penify_hook/main.py index 2f4312f..9bd6821 100644 --- a/penify_hook/main.py +++ b/penify_hook/main.py @@ -7,11 +7,11 @@ def main(): """Main function to handle command-line interface (CLI) interactions with Penify services. - This tool provides a command-line interface for generating smart commit - messages, configuring local-LLM and JIRA, and generating code - documentation. It supports basic commands that do not require login and - advanced commands that require user authentication. The `--version` flag - can be used to display the version information. + This tool provides a comprehensive command-line interface for generating + smart commit messages, configuring local-LLM and JIRA, and generating + code documentation. It supports both basic commands that do not require + login and advanced commands that require user authentication. The + `--version` flag can be used to display the version information. Returns: int: Exit status of the program (0 for success, 1 for error). diff --git a/penify_hook/ui_utils.py b/penify_hook/ui_utils.py index 5fce269..b9929ff 100644 --- a/penify_hook/ui_utils.py +++ b/penify_hook/ui_utils.py @@ -82,6 +82,10 @@ def format_error(message): def format_highlight(message): """Format a highlighted message with appropriate color. + This function takes a message and wraps it in ANSI escape codes to apply + a highlight style. The highlighting is reset afterward using + Style.RESET_ALL. + Args: message (str): The message to be formatted and highlighted. @@ -188,7 +192,11 @@ def print_status(status, message): print(f" {PROCESSING_SYMBOL} {message}") def create_progress_bar(total, desc="Processing", unit="item"): - """Create a tqdm progress bar with consistent styling. + """Create a consistent tqdm progress bar. + + This function generates and returns a configured tqdm progress bar with + customizable total, description, and unit. The progress bar is formatted + with a fixed width and uses ASCII characters for rendering. Args: total (int): Total number of items to process. @@ -197,6 +205,13 @@ def create_progress_bar(total, desc="Processing", unit="item"): Returns: tqdm: A configured tqdm progress bar instance. + + Examples: + >>> from tqdm import tqdm + >>> pbar = create_progress_bar(100, desc="Downloading", unit="file") + >>> for i in range(100): + ... time.sleep(0.1) + ... pbar.update(1) """ return tqdm( total=total, @@ -210,9 +225,9 @@ def create_stage_progress_bar(stages, desc="Processing"): """Create a tqdm progress bar for processing stages with consistent styling. - This function initializes and returns a tqdm progress bar object for - tracking the progress through a series of stages. It also provides a - description for the progress bar to enhance its usability. + Initialize and returns a tqdm progress bar object to track the progress + through a series of stages. Optionally provide a description to enhance + its usability. Args: stages (list): A list of strings representing individual stages in the process. diff --git a/penify_hook/utils.py b/penify_hook/utils.py index d5a939b..bc25866 100644 --- a/penify_hook/utils.py +++ b/penify_hook/utils.py @@ -24,8 +24,8 @@ def get_repo_details(repo: Repo): Returns: dict: A dictionary containing keys for 'organization_name', 'repo_name', and - 'vendor' which represent the organization name, repository name, and - hosting service respectively. + 'vendor' which represent the + organization name, repository name, and hosting service respectively. """ remote_url = None hosting_service = "Unknown" @@ -75,15 +75,15 @@ def get_repo_details(repo: Repo): } def recursive_search_git_folder(folder_path): - """Recursively search for the .git folder in the specified directory and + """Recursively search for the `.git` folder in the specified directory and return its parent directory. Args: - folder_path (str): The path of the directory to search for the .git folder. + folder_path (str): The path of the directory to search for the `.git` folder. Returns: - str: The path of the directory containing the .git folder. If no .git folder - is found, returns None. + str: The path of the directory containing the `.git` folder. If no `.git` + folder is found, returns `None`. """ if os.path.isdir(folder_path): if '.git' in os.listdir(folder_path): @@ -110,8 +110,8 @@ def find_git_parent(path): str: The absolute path to the parent directory containing the `.git` folder. Raises: - GitRepoNotFoundError: If no Git repository is found in the specified path or any of its parent - directories. + GitRepoNotFoundError: If no Git repository is found in the specified path or any of its + parent directories. """ current_dir = os.path.abspath(path) diff --git a/tests/test_commit_commands.py b/tests/test_commit_commands.py index daf4b0f..84cb5f4 100644 --- a/tests/test_commit_commands.py +++ b/tests/test_commit_commands.py @@ -51,7 +51,7 @@ def mock_jira_client(self): This function yields a tuple containing a mock JIRA client instance and its `is_connected` method. The mock client is configured to simulate an - active connection. This is useful for unit tests that require + active connection, making it suitable for unit tests that require interaction with a JIRA client without making actual network calls. Yields: @@ -113,14 +113,13 @@ def mock_print_functions(self): purposes. This function uses Python's `unittest.mock.patch` to replace the actual - print functions (`print`, `print_warning`, and `print_error`) with mock - objects. These mock objects can be used in tests to capture calls made - to these print functions without actually printing anything. + print functions (`print_info`, `print_warning`, and `print_error`) with + mock objects. These mock objects can be used in tests to capture calls + made to these print functions without actually printing anything. Yields: tuple: A tuple containing three mock objects corresponding to `print_info`, - `print_warning`, - and `print_error`. + `print_warning`, and `print_error`. """ with patch('penify_hook.ui_utils.print_info', create=True) as mock_info, \ @@ -322,9 +321,9 @@ def test_commit_code_with_jira_connection_failure(self, mock_error, mock_warning @patch('builtins.print') def test_commit_code_error_handling(self, mock_print, mock_exit, mock_git_folder_search, mock_doc_gen, mock_api_client): - """Test the error handling in the test_commit_code function. + """Test the error handling in the commit_code function. - This function sets up mocks to simulate exceptions and test the error + This function sets up mocks to simulate exceptions and tests the error handling of the commit_code function. It verifies that the function correctly prints an error message and exits with a status code of 1 when an exception occurs during documentation generation. @@ -360,12 +359,12 @@ def test_setup_commit_parser(self): """Set up the argument parser for the commit command. This function configures an argument parser to handle various options - for committing changes. It adds three arguments: - '-m' or '--message': - An optional argument to specify a contextual commit message with a - default value of "N/A". - '-e' or '--terminal': A boolean flag to open - an edit terminal before committing. - '-d' or '--description': A boolean - flag that, when set to False, indicates the generation of a commit - message with title and description. + for committing changes. It adds three arguments: '-m' or '--message': An + optional argument to specify a contextual commit message with a default + value of "N/A". '-e' or '--terminal': A boolean flag to open an edit + terminal before committing. '-d' or '--description': A boolean flag + that, when set to False, indicates the generation of a commit message + with title and description. Args: parser (MagicMock): The argument parser to be configured. diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py index 995f5ae..b80f082 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -25,12 +25,6 @@ def test_get_penify_config_existing_dir(self, mock_file_open, mock_makedirs, moc It should not create a new directory and assert that all mocked functions were called correctly. - - Args: - mock_file_open (MagicMock): A MagicMock object simulating the open() function. - mock_makedirs (MagicMock): A MagicMock object simulating the os.makedirs() function. - mock_path (MagicMock): A MagicMock object simulating the Path class from pathlib module. - mock_git_folder (MagicMock): A MagicMock object simulating the git_folder_search() function. """ # Mock git folder search @@ -62,7 +56,7 @@ def test_get_penify_config_new_dir(self, mock_file_open, mock_makedirs, mock_pat not exist. This function mocks various system calls to simulate a scenario where - the .penify directory is not present. It then asserts that the + the `.penify` directory is not present. It then asserts that the appropriate actions are taken to create the directory and write an empty JSON file. @@ -187,12 +181,11 @@ def test_get_llm_config_invalid_json(self, mock_print, mock_file_open, mock_get_ @patch('builtins.open', new_callable=mock_open, read_data='{"jira": {"url": "https://jira.example.com", "username": "user", "api_token": "token"}}') def test_get_jira_config_exists(self, mock_file_open, mock_get_config): """Test that get_jira_config returns the correct JIRA configuration when - the configuration file exists. - - It sets up a mock for the configuration file to simulate its existence - and verifies that the function reads from the correct file and returns - the expected JIRA configuration dictionary. Additionally, it checks that - the mock file open is called with the appropriate arguments. + the configuration file exists. This function sets up a mock for the + configuration file to simulate its existence, calls the + `get_jira_config` function, and verifies that it reads from the correct + file and returns the expected JIRA configuration dictionary. It also + checks that the mock file open is called with the appropriate arguments. Args: mock_file_open (MagicMock): A mock for the `open` function. @@ -268,9 +261,8 @@ def test_save_llm_config_success(self, mock_print, mock_json_dump, mock_file_ope @patch('builtins.print') def test_save_llm_config_failure(self, mock_print, mock_file_open, mock_get_config): """Test function to verify that the save_llm_config function returns False - and prints an error message when it fails to save the LLM configuration - due to a permission error. - + and prints an error message + when it fails to save the LLM configuration due to a permission error. It sets up a mock configuration file that exists and calls the save_llm_config function with valid parameters. The function is expected to return False and print "Error saving LLM configuration: Permission @@ -378,16 +370,18 @@ def test_get_token_from_env(self, mock_file_open, mock_path, mock_getenv): def test_get_token_from_config(self, mock_file_open, mock_path, mock_getenv): """Test retrieving a token from the configuration. - This function sets up mocks for environment variables and configuration - files, calls the `get_token` function, and asserts its behavior. It - verifies that when the environment variable is not found, the function - reads a token from a configuration file located in the user's home - directory. + This function tests the behavior of the `get_token` function when the + environment variable is not found. It sets up mocks for the environment + variable and the configuration file, calls the function, and asserts + that it correctly reads a token from the user's home directory + configuration file. Args: - mock_file_open (MagicMock): A mock for the `open` function. - mock_path (MagicMock): A mock for the `pathlib.Path` class. - mock_getenv (MagicMock): A mock for the `os.getenv` function. + mock_file_open (MagicMock): A mock for the `open` function used to read the configuration file. + mock_path (MagicMock): A mock for the `pathlib.Path` class representing the home directory + path. + mock_getenv (MagicMock): A mock for the `os.getenv` function to simulate the absence of the + environment variable. """ # Setup mock for env var (not found) diff --git a/tests/test_doc_commands.py b/tests/test_doc_commands.py index a51ba53..2fa3181 100644 --- a/tests/test_doc_commands.py +++ b/tests/test_doc_commands.py @@ -101,10 +101,10 @@ def test_generate_doc_folder_location(mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): """Test the function to generate documentation for a folder location. - It sets up mock objects for API client, folder analyzer, file analyzer, - and Git analyzer, then calls the `generate_doc` function with specified - parameters. Finally, it asserts that the correct methods on the mock - objects were called as expected. + This function sets up mock objects for API client, folder analyzer, file + analyzer, and Git analyzer. It then calls the `generate_doc` function + with specified parameters and asserts that the correct methods on the + mock objects were called as expected. Args: mock_api_client (MagicMock): Mock object for the API client. @@ -134,11 +134,9 @@ def test_generate_doc_folder_location(mock_api_client, mock_folder_analyzer, @patch('penify_hook.commands.doc_commands.GitDocGenHook') @patch('penify_hook.api_client.APIClient') def test_generate_doc_error_handling(mock_api_client, mock_git_analyzer, mock_exit): - """Generate a documentation string for the provided code snippet using - Google Docstring style. + """Test function to ensure proper error handling during API calls with + GitAnalyzer. - Short one line description: Test function to ensure proper error - handling during API calls with GitAnalyzer. Multiline long description: This test function is designed to verify that the generate_doc function handles exceptions correctly when an error occurs during API interaction with GitAnalyzer. It sets up a mock API client and a mock Git analyzer, @@ -168,10 +166,9 @@ def test_generate_doc_error_handling(mock_api_client, mock_git_analyzer, mock_ex def test_setup_docgen_parser(): """Test the setup_docgen_parser function to ensure it properly configures - the ArgumentParser for docgen options. - - It verifies that the parser correctly sets up docgen options and handles - different subcommands like 'install-hook' and 'uninstall-hook'. + the ArgumentParser for docgen options. It verifies that the parser + correctly sets up docgen options and handles different subcommands like + 'install-hook' and 'uninstall-hook'. """ parser = ArgumentParser() @@ -201,9 +198,9 @@ def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc mock_uninstall_hook, mock_install_hook): """Test the handling of the 'install-hook' subcommand. - This function sets up a mock environment where it simulates the - execution of the 'install-hook' subcommand. It verifies that the - `mock_install_hook` is called with the correct arguments, while + This function sets up a mock environment to simulate the execution of + the 'install-hook' subcommand. It verifies that the `mock_install_hook` + is called with the correct arguments while ensuring that `mock_generate_doc` and `mock_uninstall_hook` are not called. Args: @@ -233,7 +230,8 @@ def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc def test_handle_docgen_uninstall_hook(mock_exit, mock_get_token, mock_generate_doc, mock_uninstall_hook, mock_install_hook): """Test the uninstall-hook subcommand of the handle_docgen function. - This test case sets up a mock environment and verifies that the + + This function sets up a mock environment and verifies that the uninstall-hook is called with the correct location, while generate_doc and install_hook are not called. @@ -311,11 +309,13 @@ def test_handle_docgen_no_token(mock_exit, mock_get_token): @patch('penify_hook.commands.doc_commands.os.getcwd') @patch('penify_hook.api_client.APIClient') def test_generate_doc_with_file_exception(mock_api_client, mock_getcwd): - """Generate documentation from a Python source file. + """Test generating documentation from a Python source file with an + exception. - This function reads a Python file and generates a docstring based on its - content. It uses mock objects to simulate API calls and directory - operations during testing. + This function reads a Python file and attempts to generate a docstring + based on its content. It uses mock objects to simulate API calls and + directory operations during testing. If an exception occurs during the + process, it raises a SystemExit with status code 1. Args: mock_api_client (unittest.mock.MagicMock): A mock object for simulating API client behavior. @@ -334,18 +334,17 @@ def test_generate_doc_with_file_exception(mock_api_client, mock_getcwd): @patch('penify_hook.commands.doc_commands.os.getcwd') @patch('penify_hook.api_client.APIClient') def test_generate_doc_with_folder_exception(mock_api_client, mock_getcwd): - """Generate documentation from a given API endpoint and save it to a - folder. + """Test that a SystemExit exception is raised when an error occurs during + the fetching process. - This function fetches data from the specified API endpoint, processes - it, and saves the generated documentation in the provided folder. If an - error occurs during the fetching process, a SystemExit exception is - raised with an appropriate message. + This function tests the behavior of the `generate_doc` function when an + error occurs during the fetching process. It sets up a mock API client + to simulate a failure and checks if a SystemExit exception is raised + with the appropriate message. Args: - api_url (str): The URL of the API endpoint from which data will be fetched. - token (str): The authentication token required to access the API. - folder_path (str): The path to the folder where the documentation will be saved. + mock_api_client (MagicMock): A mock object for the API client, simulating an error. + mock_getcwd (MagicMock): A mock object for `os.getcwd`, returning a fake directory path. """ # Setup diff --git a/tests/test_web_config.py b/tests/test_web_config.py index c87c87e..1ebd050 100644 --- a/tests/test_web_config.py +++ b/tests/test_web_config.py @@ -19,11 +19,11 @@ def test_config_llm_web_server_setup(self, mock_resource_filename, mock_server, """Set up and test the web server configuration for an LLM (Large Language Model) web interface. - This function configures a mock web server for testing purposes, - including setting up resource filenames, mocking server behavior, and - verifying that the web browser is opened and the server starts - correctly. The function uses various mocks to simulate external - dependencies such as `resource_filename` and `server`. + This function configures a mock web server for testing purposes. It sets + up resource filenames, mocks server behavior, and verifies that the web + browser is opened and the server starts correctly. The function uses + various mocks to simulate external dependencies such as + `resource_filename` and `server`. Args: mock_resource_filename (MagicMock): A MagicMock object simulating the `resource_filename` function.