From 2d55b659caa8bb3435c0f22fb1edd966186fe019 Mon Sep 17 00:00:00 2001 From: "penify-dev[bot]" <146478655+penify-dev[bot]@users.noreply.github.com> Date: Thu, 3 Apr 2025 00:49:33 +0000 Subject: [PATCH] Generated Documentation --- penify_hook/api_client.py | 23 +-- penify_hook/commands/auth_commands.py | 36 ++++- penify_hook/commands/commit_commands.py | 48 ++++++- penify_hook/commands/config_commands.py | 131 ++++++++++++++--- penify_hook/commands/doc_commands.py | 40 ++++++ penify_hook/commands/hook_commands.py | 20 ++- penify_hook/config_command.py | 25 ++++ penify_hook/file_analyzer.py | 8 +- penify_hook/folder_analyzer.py | 10 +- penify_hook/jira_client.py | 25 +++- penify_hook/llm_client.py | 31 ++-- penify_hook/login_command.py | 8 +- penify_hook/main.py | 18 ++- penify_hook/ui_utils.py | 13 +- penify_hook/utils.py | 8 +- tests/test_commit_commands.py | 180 +++++++++++++++++++++++ tests/test_config_commands.py | 181 ++++++++++++++++++++++++ tests/test_doc_commands.py | 150 ++++++++++++++++++++ tests/test_web_config.py | 29 ++++ 19 files changed, 900 insertions(+), 84 deletions(-) diff --git a/penify_hook/api_client.py b/penify_hook/api_client.py index 07b604e..6c527eb 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. @@ -102,10 +102,11 @@ def generate_commit_summary(self, git_diff, instruction: str = "", repo_details def get_supported_file_types(self) -> list[str]: """Retrieve the supported file types from the API. - This function sends a request to the API to obtain a list of supported - file types. If the API responds successfully, it returns the list of - supported file types. If the API call fails, it returns a default list - of common file types. + This function sends a request to the API endpoint + `/v1/file/supported_languages` to obtain a list of supported file types. + If the API call is successful (status code 200), it parses the JSON + response and returns the list of supported file types. If the API call + fails, it returns a default list of common file types. Returns: list[str]: A list of supported file types, either from the API or a default set. @@ -143,11 +144,11 @@ def generate_commit_summary_with_llm(self, diff, message, generate_description: return self.generate_commit_summary(diff, message, repo_details, jira_context) def get_api_key(self): - """Get an API key from the specified URL. + """Fetch an API key from a specified URL. - It constructs a request to fetch an API token using a Bearer token in - the headers. The function handles the response and returns the API key - if successful, or `None` otherwise. + This function sends a GET request to retrieve an API token using a + Bearer token in the headers. It handles the response and returns the API + key if the request is successful, or `None` otherwise. Returns: str: The API key if the request is successful, `None` otherwise. diff --git a/penify_hook/commands/auth_commands.py b/penify_hook/commands/auth_commands.py index 8c41041..b8b4a1c 100644 --- a/penify_hook/commands/auth_commands.py +++ b/penify_hook/commands/auth_commands.py @@ -9,8 +9,14 @@ from ..api_client import APIClient def save_credentials(api_key): - """ - Save the token and API keys in the .penify file in the user's home directory. + """Save or update the API keys in the .penify file in the user's home + directory. + + Args: + api_key (str): The new API key to be saved or updated. + + Returns: + bool: if the credentials were successfully saved, False otherwise. """ home_dir = Path.home() penify_file = home_dir / '.penify' @@ -35,8 +41,20 @@ def save_credentials(api_key): return False def login(api_url, dashboard_url): - """ - Open the login page in a web browser and listen for the redirect URL to capture the token. + """Open the login page in a web browser and listen for the redirect URL to + capture the token. + + This function generates a random redirect port, constructs the full + login URL with the provided dashboard URL, opens the login page in the + default web browser, and sets up a simple HTTP server to listen for the + redirect. Upon receiving the redirect, it extracts the token from the + query parameters, fetches API keys using the token, saves them if + successful, and handles login failures by notifying the user. + + Args: + api_url (str): The URL of the API service to fetch API keys. + dashboard_url (str): The URL of the dashboard where the user will be redirected after logging + in. """ redirect_port = random.randint(30000, 50000) redirect_url = f"http://localhost:{redirect_port}/callback" @@ -48,6 +66,16 @@ def login(api_url, dashboard_url): class TokenHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): + """Handle a GET request to process login token and redirect or display + error message. + + This method processes the incoming GET request, extracts the token from + the query string, and performs actions based on whether the token is + present. If the token is valid, it redirects the user to the Penify + dashboard and fetches API keys if successful. If the token is invalid, + it displays an error message. + """ + query = urllib.parse.urlparse(self.path).query query_components = urllib.parse.parse_qs(query) token = query_components.get("token", [None])[0] diff --git a/penify_hook/commands/commit_commands.py b/penify_hook/commands/commit_commands.py index e69a31a..a9d93f8 100644 --- a/penify_hook/commands/commit_commands.py +++ b/penify_hook/commands/commit_commands.py @@ -8,8 +8,27 @@ 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. + """Enhance 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. + + 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. + 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. + jira_user (str?): Username for authenticating with JIRA. Defaults to None. + jira_api_token (str?): API token for accessing JIRA. Defaults to None. """ from penify_hook.ui_utils import print_error @@ -79,6 +98,18 @@ def commit_code(api_url, token, message, open_terminal, generate_description, def setup_commit_parser(parser): + """Generates a parser for setting up a command to generate smart commit + messages. + + This function sets up an argument parser that can be used to generate + commit messages with contextual information. It allows users to specify + options such as including a message, opening an edit terminal before + committing, and generating a detailed commit message. + + Args: + parser (argparse.ArgumentParser): The ArgumentParser object to be configured. + """ + commit_parser_description = """ It generates smart commit messages. By default, it will just generate just the Title of the commit message. 1. If you have not configured LLM, it will give an error. You either need to configure LLM or use the API key. @@ -95,6 +126,19 @@ def setup_commit_parser(parser): parser.add_argument("-d", "--description", action="store_false", help="It will generate commit message with title and description.", default=False) def handle_commit(args): + """Handle the commit functionality by processing arguments and invoking the + appropriate commands. + + This function processes the provided command-line arguments to configure + settings for commit operations, including LLM (Language Model) and Jira + configurations. It then calls the `commit_code` function with these + configurations to perform the actual commit operation. + + Args: + args (argparse.Namespace): The parsed command-line arguments containing options like terminal, + description, message, etc. + """ + from penify_hook.commands.commit_commands import commit_code from penify_hook.commands.config_commands import get_jira_config, get_llm_config, get_token from penify_hook.constants import API_URL diff --git a/penify_hook/commands/config_commands.py b/penify_hook/commands/config_commands.py index 4d27c42..518042a 100644 --- a/penify_hook/commands/config_commands.py +++ b/penify_hook/commands/config_commands.py @@ -12,10 +12,15 @@ def get_penify_config() -> Path: - """ - Get the home directory for the .penify configuration file. - This function searches for the .penify file in the current directory - and its parent directories until it finds it or reaches the home directory. + """Get the home directory for the .penify configuration file. + + This function searches for the `.penify` file in the current directory + and its parent directories until it finds it or reaches the home + directory. If not found, it creates the `.penify` directory and an empty + `config.json` file. + + Returns: + Path: The path to the `config.json` file within the `.penify` directory. """ current_dir = os.getcwd() home_dir = recursive_search_git_folder(current_dir) @@ -43,8 +48,19 @@ def get_penify_config() -> Path: def save_llm_config(model, api_base, api_key): - """ - Save LLM configuration settings in the .penify file. + """Save LLM configuration settings in the .penify file. + + It reads the existing configuration from the .penify file if it exists, + updates or adds the LLM configuration with the provided model, API base, + and API key, and then writes the updated configuration back to the file. + + Args: + model (str): The name of the language model. + api_base (str): The base URL for the API. + api_key (str): The API key for authentication. + + Returns: + bool: True if the LLM configuration was successfully saved, False otherwise. """ penify_file = get_penify_config() @@ -75,8 +91,19 @@ def save_llm_config(model, api_base, api_key): return False def save_jira_config(url, username, api_token): - """ - Save JIRA configuration settings in the .penify file. + """Save JIRA configuration settings in the .penify file. + + This function reads existing JIRA configuration from the .penify file, + updates or adds new JIRA configuration details, and writes it back to + the file. + + Args: + url (str): The URL of the JIRA instance. + username (str): The username for accessing the JIRA instance. + api_token (str): The API token used for authentication. + + Returns: + bool: True if the configuration was successfully saved, False otherwise. """ from penify_hook.utils import recursive_search_git_folder @@ -108,8 +135,15 @@ def save_jira_config(url, username, api_token): return False def get_llm_config(): - """ - Get LLM configuration from the .penify file. + """Retrieve LLM configuration from the .penify file. + + This function reads the .penify configuration file and extracts the LLM + settings. If the file does not exist or contains invalid JSON, it + returns an empty dictionary. + + Returns: + dict: A dictionary containing the LLM configuration, or an empty dictionary if + the file is missing or invalid. """ config_file = get_penify_config() if config_file.exists(): @@ -123,8 +157,15 @@ def get_llm_config(): return {} def get_jira_config(): - """ - Get JIRA configuration from the .penify file. + """Get JIRA configuration from 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. + Otherwise, it returns an empty dictionary. + + Returns: + dict: The JIRA configuration or an empty dictionary if not found or invalid. """ config_file = get_penify_config() if config_file.exists(): @@ -138,8 +179,16 @@ def get_jira_config(): return {} def config_llm_web(): - """ - Open a web browser interface for configuring LLM settings. + """Open a web browser interface for configuring LLM settings. + + 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 + 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 + down. """ redirect_port = random.randint(30000, 50000) server_url = f"http://localhost:{redirect_port}" @@ -148,6 +197,15 @@ def config_llm_web(): class ConfigHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): + """Handle HTTP GET requests. + + This function processes incoming GET requests and sends appropriate + responses based on the requested path. It serves an HTML template for + the root path ("/") and returns a JSON response with the current LLM + configuration for the "/get_config" path. For any other paths, it + returns a "Not Found" error. + """ + if self.path == "/": self.send_response(200) self.send_header("Content-type", "text/html") @@ -189,6 +247,17 @@ def do_GET(self): self.wfile.write(b"Not Found") def do_POST(self): + """Handle POST requests on the /save endpoint. + + This method processes incoming POST requests to save language model + configuration data. It extracts the necessary parameters from the + request body, saves the configuration using the provided details, and + then schedules the server to shut down after a successful save. + + Args: + self (HTTPRequestHandler): The instance of the HTTPRequestHandler class handling the request. + """ + if self.path == "/save": content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) @@ -240,8 +309,13 @@ def log_message(self, format, *args): print("Configuration completed.") def config_jira_web(): - """ - Open a web browser interface for configuring JIRA settings. + """Open a web browser interface for configuring JIRA settings. + + This function sets up a simple HTTP server using Python's built-in + `http.server` module to handle GET and POST requests. The server serves + an HTML page for configuration and handles saving the JIRA configuration + details through API tokens and URLs. Upon successful configuration, it + shuts down the server gracefully. """ redirect_port = random.randint(30000, 50000) server_url = f"http://localhost:{redirect_port}" @@ -250,6 +324,14 @@ def config_jira_web(): class ConfigHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): + """Handle GET requests for different paths. + + 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. + """ + if self.path == "/": self.send_response(200) self.send_header("Content-type", "text/html") @@ -291,6 +373,16 @@ def do_GET(self): self.wfile.write(b"Not Found") def do_POST(self): + """Handle HTTP POST requests to save JIRA configuration. + + This method processes incoming POST requests to save JIRA configuration + details. It reads JSON data from the request body, extracts necessary + parameters (URL, username, API token, and verify), saves the + configuration using the `save_jira_config` function, and responds with + success or error messages. If an exception occurs during the process, it + sends a 500 Internal Server Error response. + """ + if self.path == "/save": content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) @@ -345,8 +437,11 @@ def log_message(self, format, *args): print("Configuration completed.") def get_token(): - """ - Get the token based on priority. + """Get the token based on priority from environment variables or + configuration files. + + Returns: + str: The API token if found, otherwise None. """ import os env_token = os.getenv('PENIFY_API_TOKEN') diff --git a/penify_hook/commands/doc_commands.py b/penify_hook/commands/doc_commands.py index 7701967..5fb3273 100644 --- a/penify_hook/commands/doc_commands.py +++ b/penify_hook/commands/doc_commands.py @@ -4,6 +4,22 @@ import os 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. + + 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. + """ + import os import sys from ..folder_analyzer import FolderAnalyzerGenHook @@ -64,6 +80,18 @@ def generate_doc(api_url, token, location=None): """ def setup_docgen_parser(parser): + """Set up and configure a parser for documentation generation using Git + commands. + + This function configures a parser with various subcommands and arguments + necessary for generating documentation for Git diffs, files, or folders. + It also installs and uninstalls commit hooks to automate documentation + generation on commits. + + Args: + parser (argparse.ArgumentParser): The parser to configure. + """ + # We don't need to create a new docgen_parser since it's passed as a parameter docgen_parser_description = """ It generates Documentation for the Git diff, file or folder. @@ -94,6 +122,18 @@ def setup_docgen_parser(parser): default=os.getcwd()) def handle_docgen(args): + """Handle various subcommands related to document generation and hook + management. + + This function processes different subcommands such as installing or + uninstalling git hooks, and directly generating documentation based on + provided arguments. + + Args: + args (Namespace): Parsed command-line arguments containing the subcommand and location + details. + """ + # Only import dependencies needed for docgen functionality here from penify_hook.commands.config_commands import get_token import sys diff --git a/penify_hook/commands/hook_commands.py b/penify_hook/commands/hook_commands.py index 9a56f40..1a49bfe 100644 --- a/penify_hook/commands/hook_commands.py +++ b/penify_hook/commands/hook_commands.py @@ -10,9 +10,14 @@ """ def install_git_hook(location, token): - """ - Install a post-commit hook in the specified location that generates documentation + """Install a post-commit hook in the specified location that generates + documentation for changed files after each commit. + + Args: + location (str): The path to the Git repository where the hook should be installed. + token (str): The authentication token required to access the documentation generation + service. """ hooks_dir = Path(location) / ".git/hooks" hook_path = hooks_dir / HOOK_FILENAME @@ -29,8 +34,15 @@ def install_git_hook(location, token): print(f"Documentation will now be automatically generated after each commit.") def uninstall_git_hook(location): - """ - Uninstalls the post-commit hook from the specified location. + """Uninstalls the post-commit hook from the specified location. + + This function attempts to remove a post-commit git hook located at the + given path. It constructs the path to the hook and checks if it exists. + If the hook is found, it is deleted, and a confirmation message is + printed. If no hook is found, a message indicating this is also printed. + + Args: + location (Path): The base directory where the .git/hooks directory is located. """ hook_path = Path(location) / ".git/hooks" / HOOK_FILENAME diff --git a/penify_hook/config_command.py b/penify_hook/config_command.py index 6f76894..1d9a6ab 100644 --- a/penify_hook/config_command.py +++ b/penify_hook/config_command.py @@ -2,6 +2,18 @@ def setup_config_parser(parent_parser): + """Set up a configuration parser with subparsers for different types of + configurations. + + This function configures and adds subcommands to the parent parser. Each + subcommand corresponds to a specific type of configuration, such as LLM + (Language Model) or JIRA. It allows users to configure settings for + these systems through command-line arguments. + + Args: + parent_parser (argparse.ArgumentParser): The parent parser to which the config subparsers will be added. + """ + # Config subcommand: Create subparsers for config types parser = parent_parser.add_subparsers(title="config_type", dest="config_type") @@ -27,6 +39,19 @@ def setup_config_parser(parent_parser): # Add all other necessary arguments for config command def handle_config(args): + """Handle configuration settings based on the specified config type. + + This function processes different types of configurations such as LLM + (Language Model) and JIRA. It saves configurations, sets up web-based + configurations, and verifies JIRA connections. + + Args: + args (argparse.Namespace): Command-line arguments containing the type of configuration to handle. + + Returns: + int: Exit code indicating success or failure. + """ + # Only import dependencies needed for config functionality here from penify_hook.commands.config_commands import save_llm_config from penify_hook.jira_client import JiraClient # Import moved here diff --git a/penify_hook/file_analyzer.py b/penify_hook/file_analyzer.py index cfbe826..c161afc 100644 --- a/penify_hook/file_analyzer.py +++ b/penify_hook/file_analyzer.py @@ -28,10 +28,10 @@ def process_file(self, file_path, pbar): """Process a file by reading its content and sending it to an API for processing. - This function checks if the provided file has a supported extension. If - the file is valid, it reads the content of the file and sends it to an - API client for further processing. If the API responds successfully, the - original file content is replaced with the response. + This function validates the provided file extension, reads the content + of the file, and sends it to an API client for further processing. If + the API responds successfully, the original file content is replaced + with the response. Args: file_path (str): The relative path to the file that needs to be processed. diff --git a/penify_hook/folder_analyzer.py b/penify_hook/folder_analyzer.py index 3e23f7d..15ec20f 100644 --- a/penify_hook/folder_analyzer.py +++ b/penify_hook/folder_analyzer.py @@ -12,12 +12,12 @@ def __init__(self, dir_path: str, api_client: APIClient): super().__init__(dir_path, api_client) def list_all_files_in_dir(self, dir_path: str): - """List all files in a directory and its subdirectories. + """List all non-hidden files in a directory and its subdirectories. - This function traverses the specified directory using `os.walk`, - collecting paths of all non-hidden files into a list. It filters out - hidden directories (those starting with a dot) to ensure only visible - files are returned. + 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. Args: dir_path (str): The path to the directory whose files and subdirectory files need to be diff --git a/penify_hook/jira_client.py b/penify_hook/jira_client.py index b193ecf..56d2e22 100644 --- a/penify_hook/jira_client.py +++ b/penify_hook/jira_client.py @@ -46,7 +46,7 @@ def __init__(self, jira_url: str = None, jira_user: str = None, jira_api_token: def is_connected(self) -> bool: """Check if the JIRA client is connected. - This function checks whether the JIRA client has successfully + This function verifies whether the JIRA client has successfully established a connection. It returns `True` if the client is connected, and `False` otherwise. @@ -84,6 +84,12 @@ def extract_issue_keys_from_branch(self, branch_name: str) -> List[str]: def extract_issue_keys(self, text: str) -> List[str]: """Extract JIRA issue keys from a given text. + This function searches through the provided text to find and return all + unique JIRA issue keys. A JIRA issue key typically follows the pattern + of PROJECT-123, where PROJECT is alphanumeric and consists of at least + one uppercase letter followed by one or more alphanumeric characters, + and 123 is a numeric sequence. + Args: text (str): The text in which to search for JIRA issue keys. @@ -162,8 +168,8 @@ def update_issue_status(self, issue_key: str, transition_name: str) -> bool: """Update the status of a JIRA issue. Args: - issue_key (str): The key of the JIRA issue to be updated (e.g., "PROJECT-123"). - transition_name (str): The name of the desired transition (e.g., "In Progress", "Done"). + issue_key (str): The key of the JIRA issue to be updated. + transition_name (str): The name of the desired transition. Returns: bool: True if the status was successfully updated, False otherwise. @@ -202,8 +208,8 @@ def format_commit_message_with_jira_info(self, commit_title: str, commit_descrip commit_title (str): The original commit title. commit_description (str): The original commit description. issue_keys (List[str]?): A list of JIRA issue keys to include in the commit message. If not - provided, - issue keys will be extracted from both the title and the description. + provided, issue keys will be extracted from both the title and the + description. Returns: tuple: A tuple containing the updated commit title and description with JIRA @@ -246,9 +252,16 @@ def format_commit_message_with_jira_info(self, commit_title: str, commit_descrip return updated_title, updated_description def get_detailed_issue_context(self, issue_key: str) -> Dict[str, Any]: - """Get comprehensive details about a JIRA issue including context for + """Retrieve comprehensive details about a JIRA issue including context for better commit messages. + This function fetches detailed information from a specified JIRA issue + and constructs a dictionary containing various context fields such as + the issue summary, description, type, status, priority, comments, URL, + and additional custom fields like acceptance criteria and sprint + information. If any errors occur during the fetching process, + appropriate warnings or errors are logged. + Args: issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). diff --git a/penify_hook/llm_client.py b/penify_hook/llm_client.py index fb429ba..e5fe2b2 100644 --- a/penify_hook/llm_client.py +++ b/penify_hook/llm_client.py @@ -26,17 +26,30 @@ 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. - + """Generate 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 + optional JIRA context. It constructs a prompt for the LLM to produce a + commit title and an optional detailed description, adhering to Semantic + Commit Messages guidelines. If the JIRA context is provided, it enriches + the prompt with relevant issue information. + Args: - diff: Git diff of changes - message: User-provided commit message or instructions - repo_details: Details about the repository - jira_context: Optional JIRA issue context to enhance the summary - + diff (str): Git diff of changes. + message (str): User-provided commit message or instructions. + generate_description (bool): Flag indicating whether to include a detailed description in the + summary. + repo_details (Dict): Details about the repository. + jira_context (Dict?): Optional JIRA issue context to enhance the summary. + Returns: - Dict with title and description for the commit + Dict: A dictionary containing the title and description for the commit. If + generate_description is False, + the 'description' key may be absent. + + Raises: + ValueError: If the LLM model is not configured. """ if not self.model: raise ValueError("LLM model not configured. Please provide a model when initializing LLMClient.") diff --git a/penify_hook/login_command.py b/penify_hook/login_command.py index 93da34e..2d97cc3 100644 --- a/penify_hook/login_command.py +++ b/penify_hook/login_command.py @@ -5,11 +5,9 @@ def setup_login_parser(parser): def handle_login(args): """Handle the login command. - This function is responsible for initiating a user login process by - calling the `login` function from the - `penify_hook.commands.auth_commands` module. It uses predefined - constants `API_URL` and `DASHBOARD_URL` from the `penify_hook.constants` - module to perform the login operation. + Initiates a user login process by calling the `login` function from the + `penify_hook.commands.auth_commands` module using predefined constants + `API_URL` and `DASHBOARD_URL` from the `penify_hook.constants` module. Args: args (argparse.Namespace): Parsed arguments containing necessary parameters for the login command. diff --git a/penify_hook/main.py b/penify_hook/main.py index 3273e23..2f4312f 100644 --- a/penify_hook/main.py +++ b/penify_hook/main.py @@ -4,13 +4,17 @@ def main(): - """Penify CLI tool for generating smart commit messages with JIRA - integration, configuring local-LLM and JIRA, - and generating code documentation. This tool provides a command-line - interface to interact with Penify's services. 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. + """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. + + Returns: + int: Exit status of the program (0 for success, 1 for error). """ parser = argparse.ArgumentParser( diff --git a/penify_hook/ui_utils.py b/penify_hook/ui_utils.py index 6c7c27a..5fce269 100644 --- a/penify_hook/ui_utils.py +++ b/penify_hook/ui_utils.py @@ -68,7 +68,8 @@ def format_error(message): This function takes a plain error message and wraps it in ANSI escape codes to apply the specified error color, ensuring that the error - message is visually distinct when output. + message is visually distinct when output. The function supports various + error colors defined by constants like `ERROR_COLOR`. Args: message (str): The plain text error message to be formatted. @@ -117,7 +118,7 @@ def print_info(message): print(format_info(message)) def print_success(message): - """Print a success message with appropriate formatting. + """Print a formatted success message. This function takes a string `message` and prints it as a formatted success message. The formatting includes adding a prefix "Success: " to @@ -131,6 +132,10 @@ def print_success(message): def print_warning(message): """Print a warning message with appropriate formatting. + This function takes a warning message as input and prints it with + formatted output. The formatting may include color, timestamp, or other + styles to emphasize that it is a warning. + Args: message (str): The warning message to be printed. """ @@ -139,6 +144,10 @@ def print_warning(message): def print_error(message): """Print an error message with appropriate formatting. + This function takes a string message, formats it as an error message, + and then prints it. The formatting typically includes prefixing the + message with "Error: " to clearly indicate that it is an error. + Args: message (str): The error message to be printed. """ diff --git a/penify_hook/utils.py b/penify_hook/utils.py index 3854ef4..d5a939b 100644 --- a/penify_hook/utils.py +++ b/penify_hook/utils.py @@ -11,7 +11,7 @@ class GitRepoNotFoundError(Exception): def get_repo_details(repo: Repo): - """Get the details of a Git repository, including its hosting service, + """Get details of a Git repository, including its hosting service, organization name, and repository name. This function extracts these details from the remote URL of the provided @@ -78,12 +78,6 @@ def recursive_search_git_folder(folder_path): """Recursively search for the .git folder in the specified directory and return its parent directory. - This function takes a folder path as input and checks if the specified - directory contains a '.git' folder. If it does, the function returns the - path of that directory. If not, it recursively searches the parent - directory until it finds a '.git' folder or reaches the root of the - filesystem. - Args: folder_path (str): The path of the directory to search for the .git folder. diff --git a/tests/test_commit_commands.py b/tests/test_commit_commands.py index 75a34c9..daf4b0f 100644 --- a/tests/test_commit_commands.py +++ b/tests/test_commit_commands.py @@ -9,6 +9,17 @@ class TestCommitCommands: @pytest.fixture def mock_api_client(self): + """Mocks an instance of APIClient using unittest.mock. + + This function creates a mock object for APIClient and yields it along + with the mocked instance. It is useful for testing purposes where real + API calls should be avoided. + + Yields: + tuple: A tuple containing the mock of APIClient and the mocked instance of + APIClient. + """ + with patch('penify_hook.api_client.APIClient', create=True) as mock: api_client_instance = MagicMock() mock.return_value = api_client_instance @@ -16,6 +27,19 @@ def mock_api_client(self): @pytest.fixture def mock_llm_client(self): + """Mock an instance of LLMClient for testing purposes. + + This function yields a mock object representing an instance of + LLMClient, which can be used to simulate interactions with a language + model during testing. The mock is patched to replace the actual + LLMClient class from the penify_hook module. + + Yields: + tuple: A tuple containing two elements: + - mock (MagicMock): The mock object for LLMClient. + - llm_client_instance (MagicMock): An instance of the mocked LLMClient. + """ + with patch('penify_hook.llm_client.LLMClient', create=True) as mock: llm_client_instance = MagicMock() mock.return_value = llm_client_instance @@ -23,6 +47,18 @@ def mock_llm_client(self): @pytest.fixture def mock_jira_client(self): + """Create a mock JIRA client for testing purposes. + + 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 + interaction with a JIRA client without making actual network calls. + + Yields: + tuple: A tuple containing the mocked JIRA client instance and its + `is_connected` method. + """ + with patch('penify_hook.jira_client.JiraClient', create=True) as mock: jira_instance = MagicMock() jira_instance.is_connected.return_value = True @@ -31,6 +67,22 @@ def mock_jira_client(self): @pytest.fixture def mock_commit_doc_gen(self): + """Mocks the CommitDocGenHook class and returns a MagicMock instance. + + This function uses the `patch` decorator from the `unittest.mock` module + to create a mock of the `CommitDocGenHook` class. It then sets up this + mock to return a new `MagicMock` instance when invoked. The function + yields both the mock object and the mocked instance, allowing for easy + testing of functions that rely on `CommitDocGenHook`. + + Returns: + tuple: A tuple containing two elements: + - mock (patch): The patch object used to mock the `CommitDocGenHook` + class. + - doc_gen_instance (MagicMock): The mocked instance of + `CommitDocGenHook`. + """ + with patch('penify_hook.commit_analyzer.CommitDocGenHook', create=True) as mock: doc_gen_instance = MagicMock() mock.return_value = doc_gen_instance @@ -38,12 +90,39 @@ def mock_commit_doc_gen(self): @pytest.fixture def mock_git_folder_search(self): + """Mock the `recursive_search_git_folder` function to return a predefined + git folder path. + + This function uses the `patch` decorator from the `unittest.mock` module + to intercept calls to `penify_hook.utils.recursive_search_git_folder`. + When called, it will return '/mock/git/folder' instead of performing an + actual search. This is useful for testing purposes where you need a + consistent response without interacting with the file system. + + Yields: + MagicMock: A mock object that simulates the `recursive_search_git_folder` function. + """ + with patch('penify_hook.utils.recursive_search_git_folder', create=True) as mock: mock.return_value = '/mock/git/folder' yield mock @pytest.fixture def mock_print_functions(self): + """Mocks the print functions from `penify_hook.ui_utils` for testing + 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. + + Yields: + tuple: A tuple containing three mock objects corresponding to `print_info`, + `print_warning`, + and `print_error`. + """ + with patch('penify_hook.ui_utils.print_info', create=True) as mock_info, \ patch('penify_hook.ui_utils.print_warning', create=True) as mock_warning, \ patch('penify_hook.ui_utils.print_error', create=True) as mock_error: @@ -59,6 +138,22 @@ def mock_print_functions(self): def test_commit_code_with_llm_client(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_llm_client, mock_api_client): + """Test committing code using an LLM client. + + This function sets up mock objects for various components and then calls + the `commit_code` function with specified parameters. It verifies that + the correct mocks are created and called with the appropriate arguments. + + Args: + mock_error (MagicMock): Mock object for error handling. + mock_warning (MagicMock): Mock object for warning logging. + mock_info (MagicMock): Mock object for info logging. + mock_git_folder_search (MagicMock): Mock object to simulate git folder search. + mock_doc_gen (MagicMock): Mock object for document generation. + mock_llm_client (MagicMock): Mock object for LLM client interaction. + mock_api_client (MagicMock): Mock object for API client interaction. + """ + # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -104,6 +199,26 @@ def test_commit_code_with_llm_client(self, mock_error, mock_warning, mock_info, def test_commit_code_with_jira_client(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_jira_client, mock_llm_client, mock_api_client): + """Test committing code using a JIRA client. + + This function tests the commit_code function with various parameters, + including API and JIRA credentials. It sets up mock objects for + dependencies such as the JIRA client, LLM client, and doc generator to + simulate the behavior of the real classes. The function then calls + commit_code and verifies that the JIRA client and doc generator are + called with the correct parameters. + + Args: + mock_error (MagicMock): A MagicMock object for simulating error logging. + mock_warning (MagicMock): A MagicMock object for simulating warning logging. + mock_info (MagicMock): A MagicMock object for simulating info logging. + mock_git_folder_search (MagicMock): A MagicMock object for simulating the git folder search function. + mock_doc_gen (MagicMock): A MagicMock object for simulating the doc generator function. + mock_jira_client (MagicMock): A MagicMock object for simulating the JIRA client class. + mock_llm_client (MagicMock): A MagicMock object for simulating the LLM client class. + mock_api_client (MagicMock): A MagicMock object for simulating the API client class. + """ + # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -153,6 +268,24 @@ def test_commit_code_with_jira_client(self, mock_error, mock_warning, mock_info, def test_commit_code_with_jira_connection_failure(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_jira_client, mock_api_client): + """Test the commit_code function when JIRA connection fails. + + This function tests the scenario where the JIRA connection fails during + a code commit. It sets up various mocks to simulate different components + of the system and then calls the `commit_code` function with specific + parameters. The function is expected to handle the JIRA connection + failure gracefully by logging an appropriate warning. + + Args: + mock_error (MagicMock): Mock for error logging. + mock_warning (MagicMock): Mock for warning logging. + mock_info (MagicMock): Mock for info logging. + mock_git_folder_search (MagicMock): Mock for searching the Git folder. + mock_doc_gen (MagicMock): Mock for generating documentation. + mock_jira_client (MagicMock): Mock for creating a JIRA client. + mock_api_client (MagicMock): Mock for creating an API client. + """ + # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -189,6 +322,24 @@ 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. + + This function sets up mocks to simulate exceptions and test 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. + + Args: + mock_print (MagicMock): Mock for the print function, used to verify error message output. + mock_exit (MagicMock): Mock for the sys.exit function, used to verify exit behavior. + mock_git_folder_search (MagicMock): Mock for the git_folder_search function, returning a mock Git folder + path. + mock_doc_gen (MagicMock): Mock for the doc_gen function, simulating an exception during + documentation generation. + mock_api_client (MagicMock): Mock for the API client class, not directly used but referenced in the + function signature. + """ + # Setup mocks mock_doc_gen.side_effect = Exception("Test error") mock_git_folder_search.return_value = '/mock/git/folder' @@ -206,6 +357,20 @@ def test_commit_code_error_handling(self, mock_print, mock_exit, mock_exit.assert_called_once_with(1) 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. + + Args: + parser (MagicMock): The argument parser to be configured. + """ + parser = MagicMock() setup_commit_parser(parser) @@ -223,6 +388,21 @@ def test_setup_commit_parser(self): @patch('penify_hook.constants.API_URL', "http://api.example.com") def test_handle_commit(self, mock_print_info, mock_commit_code, mock_get_token, mock_get_llm_config, mock_get_jira_config): + """Test the handle_commit function with various mock objects. + + This function sets up mocks for retrieving LLM configuration, JIRA + configuration, and commit code. It then creates an argument object and + calls the handle_commit function. Finally, it verifies that the mock + functions were called with the expected arguments. + + Args: + mock_print_info (MagicMock): Mock object for printing information. + mock_commit_code (MagicMock): Mock object for committing code. + mock_get_token (MagicMock): Mock object for retrieving API token. + mock_get_llm_config (MagicMock): Mock object for retrieving LLM configuration. + mock_get_jira_config (MagicMock): Mock object for retrieving JIRA configuration. + """ + # Setup mocks mock_get_llm_config.return_value = { 'model': 'test-model', diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py index ba84c10..995f5ae 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -20,6 +20,19 @@ class TestConfigCommands: @patch('os.makedirs') @patch('builtins.open', new_callable=mock_open) def test_get_penify_config_existing_dir(self, mock_file_open, mock_makedirs, mock_path, mock_git_folder): + """Test the get_penify_config function when the .penify config directory + exists. + + 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 mock_git_folder.return_value = '/mock/git/folder' @@ -45,6 +58,21 @@ def test_get_penify_config_existing_dir(self, mock_file_open, mock_makedirs, moc @patch('os.makedirs') @patch('builtins.open', new_callable=mock_open) def test_get_penify_config_new_dir(self, mock_file_open, mock_makedirs, mock_path, mock_git_folder): + """Test the behavior of get_penify_config when the .penify directory does + not exist. + + This function mocks various system calls to simulate a scenario where + 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. + + 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`. + mock_git_folder (MagicMock): A MagicMock object simulating a git folder search function. + """ + # Mock git folder search mock_git_folder.return_value = '/mock/git/folder' @@ -67,6 +95,19 @@ def test_get_penify_config_new_dir(self, mock_file_open, mock_makedirs, mock_pat @patch('penify_hook.commands.config_commands.get_penify_config') @patch('builtins.open', new_callable=mock_open, read_data='{"llm": {"model": "gpt-4", "api_base": "https://api.openai.com", "api_key": "test-key"}}') def test_get_llm_config_exists(self, mock_file_open, mock_get_config): + """Test the get_llm_config function when the configuration file exists. + + This function sets up a mock configuration file that exists and returns + it when called. It then calls the get_llm_config function and asserts + that it returns the correct configuration dictionary. Additionally, it + checks that the mock_file_open function was called with the correct + arguments. + + Args: + mock_file_open (MagicMock): A mock for the open() function. + mock_get_config (MagicMock): A mock for the get_config() function. + """ + # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True @@ -86,6 +127,19 @@ def test_get_llm_config_exists(self, mock_file_open, mock_get_config): @patch('penify_hook.commands.config_commands.get_penify_config') @patch('builtins.open', new_callable=mock_open, read_data='{}') def test_get_llm_config_empty(self, mock_file_open, mock_get_config): + """Test the behavior of get_llm_config when called with an empty + configuration file. + + This function sets up a mock configuration file that exists but returns + no content. It then calls the `get_llm_config` function and asserts that + it returns an empty dictionary and that the file open method was called + exactly once with the correct arguments. + + Args: + mock_file_open (MagicMock): A MagicMock object simulating the built-in open function. + mock_get_config (MagicMock): A MagicMock object simulating the get_config function. + """ + # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True @@ -102,6 +156,20 @@ def test_get_llm_config_empty(self, mock_file_open, mock_get_config): @patch('builtins.open', new_callable=mock_open, read_data='invalid json') @patch('builtins.print') def test_get_llm_config_invalid_json(self, mock_print, mock_file_open, mock_get_config): + """Test function to verify the behavior of get_llm_config when reading an + invalid JSON file. + + It sets up a mock configuration file that exists but contains invalid + JSON. The function is expected to handle this gracefully by printing an + error message and returning an empty dictionary. + + Args: + mock_print (MagicMock): Mock for the print function. + mock_file_open (MagicMock): Mock for the open function. + mock_get_config (MagicMock): Mock for the get_config function, which returns the mock configuration + file. + """ + # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True @@ -118,6 +186,24 @@ def test_get_llm_config_invalid_json(self, mock_print, mock_file_open, mock_get_ @patch('penify_hook.commands.config_commands.get_penify_config') @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. + + Args: + mock_file_open (MagicMock): A mock for the `open` function. + mock_get_config (MagicMock): A mock for the `get_config` function, which is expected to return a mock + configuration file object. + + Returns: + None: This test function does not explicitly return anything. Its assertions + serve as the verification of its correctness. + """ + # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True @@ -139,6 +225,20 @@ def test_get_jira_config_exists(self, mock_file_open, mock_get_config): @patch('json.dump') @patch('builtins.print') def test_save_llm_config_success(self, mock_print, mock_json_dump, mock_file_open, mock_get_config): + """Test the save_llm_config function successfully. + + This function tests that the save_llm_config function correctly saves an + LLM configuration and handles various mock objects and side effects. It + ensures that the function returns True upon successful execution, writes + the expected configuration to a file, and prints a confirmation message. + + Args: + mock_print (MagicMock): A mock object for the print function. + mock_json_dump (MagicMock): A mock object for json.dump. + mock_file_open (MagicMock): A mock object for file opening. + mock_get_config (MagicMock): A mock object to return a configuration file mock. + """ + # Setup mock mock_config_file = MagicMock() mock_get_config.return_value = mock_config_file @@ -167,6 +267,25 @@ def test_save_llm_config_success(self, mock_print, mock_json_dump, mock_file_ope @patch('builtins.open', side_effect=IOError("Permission denied")) @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. + + 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 + denied" in case of a failure. + + Args: + self (TestLLMConfig): An instance of the test class. + mock_print (MagicMock): A MagicMock object representing the print function, which will be used + to assert that it was called with the expected error message. + mock_file_open (MagicMock): A MagicMock object representing the open function, which is not used in + this test but is included as a parameter for completeness. + mock_get_config (MagicMock): A MagicMock object representing the get_config function, which will be + used to return the mock configuration file. + """ + # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True @@ -184,6 +303,21 @@ def test_save_llm_config_failure(self, mock_print, mock_file_open, mock_get_conf @patch('json.dump') @patch('builtins.print') def test_save_jira_config_success(self, mock_print, mock_json_dump, mock_file_open, mock_path): + """Test the save_jira_config function to ensure it saves JIRA configuration + successfully. + + This function sets up mocks for various dependencies and tests the + functionality of saving a JIRA configuration. It asserts that the + function returns `True`, the JSON dump is called with the correct + configuration, and the print statement contains the expected message. + + Args: + mock_print (MagicMock): Mock for the print function. + mock_json_dump (MagicMock): Mock for the json.dump function. + mock_file_open (MagicMock): Mock for the open function. + mock_path (MagicMock): Mock for the path module. + """ + # Setup mock mock_home_dir = MagicMock() mock_path.home.return_value = mock_home_dir @@ -213,6 +347,19 @@ def test_save_jira_config_success(self, mock_print, mock_json_dump, mock_file_op @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"api_keys": "config-token"}') def test_get_token_from_env(self, mock_file_open, mock_path, mock_getenv): + """Test retrieving a token from the environment variable. + + This function tests the behavior of `get_token` when an environment + variable is set. It verifies that if the 'PENIFY_API_TOKEN' environment + variable exists, the function returns its value without attempting to + read a file. + + Args: + mock_file_open (MagicMock): A MagicMock object for simulating file operations. + mock_path (MagicMock): A MagicMock object for simulating path operations. + mock_getenv (MagicMock): A MagicMock object for simulating environment variable retrieval. + """ + # Setup mock for env var mock_getenv.return_value = "env-token" @@ -229,6 +376,20 @@ def test_get_token_from_env(self, mock_file_open, mock_path, mock_getenv): @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"api_keys": "config-token"}') 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. + + 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. + """ + # Setup mock for env var (not found) mock_getenv.return_value = None @@ -250,6 +411,26 @@ def test_get_token_from_config(self, mock_file_open, mock_path, mock_getenv): @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"other_key": "value"}') def test_get_token_not_found(self, mock_file_open, mock_path, mock_getenv): + """Test the get_token function when the API token environment variable is + not found. + + This function tests the scenario where the `PENIFY_API_TOKEN` + environment variable is not set. It mocks the environment variable to + return `None`, and verifies that the function returns `None`. The test + also checks that the environment variable is accessed once and that a + file open operation is attempted on a configuration file located in the + user's home directory. + + Args: + mock_file_open (MagicMock): Mock for the built-in `open` function. + mock_path (MagicMock): Mock for the `pathlib.Path` module. + mock_getenv (MagicMock): Mock for the `os.getenv` function. + + Returns: + None: The function does not return anything; it asserts conditions to verify + correctness. + """ + # Setup mock for env var (not found) mock_getenv.return_value = None diff --git a/tests/test_doc_commands.py b/tests/test_doc_commands.py index ae4651c..a51ba53 100644 --- a/tests/test_doc_commands.py +++ b/tests/test_doc_commands.py @@ -21,6 +21,22 @@ def test_generate_doc_no_location(mock_getcwd, mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): + """Test function to generate documentation without location information. + + This function sets up mocks for the API client, current working + directory, and Git analyzer. It then calls the `generate_doc` function + with a fake API URL and token. The function is expected to initialize + the API client, configure the Git analyzer, and run it without any + location information. + + Args: + mock_getcwd (MagicMock): Mock for os.getcwd(). + mock_api_client (MagicMock): Mock for creating an API client. + mock_folder_analyzer (MagicMock): Mock for folder analysis. + mock_file_analyzer (MagicMock): Mock for file analysis. + mock_git_analyzer (MagicMock): Mock for Git analyzer setup. + """ + # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance @@ -45,6 +61,21 @@ def test_generate_doc_no_location(mock_getcwd, mock_api_client, @patch('penify_hook.api_client.APIClient') def test_generate_doc_file_location(mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): + """Test generating a documentation file location. + + This function tests the process of generating a documentation file + location using mock objects for API client, folder analyzer, file + analyzer, and Git analyzer. It sets up the necessary mocks, calls the + `generate_doc` function with specified parameters, and asserts that the + appropriate methods on the mock objects are called as expected. + + Args: + mock_api_client (MagicMock): Mock object for the API client. + mock_folder_analyzer (MagicMock): Mock object for the folder analyzer. + mock_file_analyzer (MagicMock): Mock object for the file analyzer. + mock_git_analyzer (MagicMock): Mock object for the Git analyzer. + """ + # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance @@ -68,6 +99,20 @@ def test_generate_doc_file_location(mock_api_client, mock_folder_analyzer, @patch('penify_hook.api_client.APIClient') 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. + + Args: + mock_api_client (MagicMock): Mock object for the API client. + mock_folder_analyzer (MagicMock): Mock object for the folder analyzer. + mock_file_analyzer (MagicMock): Mock object for the file analyzer. + mock_git_analyzer (MagicMock): Mock object for the Git analyzer. + """ + # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance @@ -89,6 +134,26 @@ 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. + + 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, + causing the analyzer to raise an exception to simulate a failure + condition. The function then asserts that the exit code is set to 1 when + the error handling mechanism is invoked. + + Args: + mock_api_client (MagicMock): A mock object simulating the API client. + mock_git_analyzer (MagicMock): A mock object simulating the Git analyzer, configured to raise an + exception. + mock_exit (MagicMock): A mock object representing the exit function, which should be called + with an error code. + """ + # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance @@ -102,6 +167,13 @@ 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'. + """ + parser = ArgumentParser() setup_docgen_parser(parser) @@ -127,6 +199,21 @@ def test_setup_docgen_parser(): @patch('sys.exit') 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 + `mock_generate_doc` and `mock_uninstall_hook` are not called. + + Args: + mock_exit (MagicMock): Mock object for sys.exit. + mock_get_token (MagicMock): Mock object to simulate fetching a token. + mock_generate_doc (MagicMock): Mock object to simulate generating documentation. + mock_uninstall_hook (MagicMock): Mock object to simulate uninstalling a hook. + mock_install_hook (MagicMock): Mock object to simulate installing a hook. + """ + # Setup mock_get_token.return_value = 'fake-token' @@ -145,6 +232,19 @@ def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc @patch('sys.exit') 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 + uninstall-hook is called with the correct location, while generate_doc + and install_hook are not called. + + Args: + mock_exit (MagicMock): A mock for the exit function. + mock_get_token (MagicMock): A mock for the get_token function. + mock_generate_doc (MagicMock): A mock for the generate_doc function. + mock_uninstall_hook (MagicMock): A mock for the uninstall_hook function. + mock_install_hook (MagicMock): A mock for the install_hook function. + """ + # Setup mock_get_token.return_value = 'fake-token' @@ -162,6 +262,19 @@ def test_handle_docgen_uninstall_hook(mock_exit, mock_get_token, mock_generate_d @patch('penify_hook.commands.doc_commands.get_token') def test_handle_docgen_generate(mock_get_token, mock_generate_doc, mock_uninstall_hook, mock_install_hook): + """Test the direct documentation generation functionality. + + This function tests the `handle_docgen` function when no subcommand is + provided. It verifies that the document generation hook is called and + the uninstall and install hooks are not called. + + Args: + mock_get_token (MagicMock): Mocked function to get authentication token. + mock_generate_doc (MagicMock): Mocked function for generating documentation. + mock_uninstall_hook (MagicMock): Mocked function for uninstalling the document generation hook. + mock_install_hook (MagicMock): Mocked function for installing the document generation hook. + """ + # Setup mock_get_token.return_value = 'fake-token' @@ -176,6 +289,18 @@ def test_handle_docgen_generate(mock_get_token, mock_generate_doc, @patch('penify_hook.commands.doc_commands.get_token') @patch('sys.exit') def test_handle_docgen_no_token(mock_exit, mock_get_token): + """Test the behavior of the `handle_docgen` function when no token is + provided. + + This function asserts that if no token is returned by `mock_get_token`, + the `handle_docgen` function will call `mock_exit` with a status code of + 1. + + Args: + mock_exit (MagicMock): A MagicMock object simulating the `exit` function. + mock_get_token (MagicMock): A MagicMock object simulating the `get_token` function. + """ + # Test with no token mock_get_token.return_value = None args = MagicMock(docgen_subcommand=None, location='doc_location') @@ -186,6 +311,17 @@ 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. + + 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. + + Args: + mock_api_client (unittest.mock.MagicMock): A mock object for simulating API client behavior. + mock_getcwd (unittest.mock.MagicMock): A mock object for simulating the current working directory function. + """ + # Setup mock_api_client.side_effect = Exception("API error") mock_getcwd.return_value = '/fake/current/dir' @@ -198,6 +334,20 @@ 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. + + 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. + + 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. + """ + # Setup mock_api_client.side_effect = Exception("API error") mock_getcwd.return_value = '/fake/current/dir' diff --git a/tests/test_web_config.py b/tests/test_web_config.py index 09e10da..c87c87e 100644 --- a/tests/test_web_config.py +++ b/tests/test_web_config.py @@ -16,6 +16,21 @@ class TestWebConfig: @patch('socketserver.TCPServer') @patch('pkg_resources.resource_filename') def test_config_llm_web_server_setup(self, mock_resource_filename, mock_server, mock_webbrowser): + """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`. + + Args: + mock_resource_filename (MagicMock): A MagicMock object simulating the `resource_filename` function. + mock_server (MagicMock): A MagicMock object simulating the context manager for the web server. + mock_webbrowser (MagicMock): A MagicMock object simulating the `webbrowser` module. + """ + # Setup mocks mock_resource_filename.return_value = 'mock/template/path' mock_server_instance = MagicMock() @@ -42,6 +57,20 @@ def stop_server_after_call(): @patch('socketserver.TCPServer') @patch('pkg_resources.resource_filename') def test_config_jira_web_server_setup(self, mock_resource_filename, mock_server, mock_webbrowser): + """Test the configuration and setup of a JIRA web server. + + This function tests the entire process of setting up a JIRA web server, + including mocking necessary resources, configuring the server to shut + down after handling one request, and verifying that the web browser is + opened with the correct URL. The function uses several mocks to simulate + external dependencies such as resource files, servers, and web browsers. + + Args: + mock_resource_filename (MagicMock): A MagicMock object for simulating the `resource_filename` function. + mock_server (MagicMock): A MagicMock object for simulating the server setup. + mock_webbrowser (MagicMock): A MagicMock object for simulating the web browser opening. + """ + # Setup mocks mock_resource_filename.return_value = 'mock/template/path' mock_server_instance = MagicMock()