|
| 1 | +"""Base classes and utilities for pytest-based CLI commands.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from dataclasses import dataclass |
| 6 | +from functools import wraps |
| 7 | +from typing import Any, Callable, Dict, List, Optional |
| 8 | + |
| 9 | +import click |
| 10 | +import pytest |
| 11 | +from rich.console import Console |
| 12 | + |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class PytestExecution: |
| 16 | + """Configuration for a single pytest execution.""" |
| 17 | + |
| 18 | + config_file: str |
| 19 | + """Path to the pytest configuration file (e.g., 'pytest.ini').""" |
| 20 | + |
| 21 | + args: List[str] |
| 22 | + """Arguments to pass to pytest.""" |
| 23 | + |
| 24 | + description: Optional[str] = None |
| 25 | + """Optional description for this execution phase.""" |
| 26 | + |
| 27 | + |
| 28 | +class ArgumentProcessor(ABC): |
| 29 | + """Base class for processing command-line arguments.""" |
| 30 | + |
| 31 | + @abstractmethod |
| 32 | + def process_args(self, args: List[str]) -> List[str]: |
| 33 | + """Process the given arguments and return modified arguments.""" |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class PytestRunner: |
| 38 | + """Handles execution of pytest commands.""" |
| 39 | + |
| 40 | + def __init__(self): |
| 41 | + """Initialize the pytest runner with a console for output.""" |
| 42 | + self.console = Console(highlight=False) |
| 43 | + |
| 44 | + def run_single(self, config_file: str, args: List[str]) -> int: |
| 45 | + """Run pytest once with the given configuration and arguments.""" |
| 46 | + pytest_args = ["-c", config_file] + args |
| 47 | + |
| 48 | + if self._is_verbose(args): |
| 49 | + pytest_cmd = f"pytest {' '.join(pytest_args)}" |
| 50 | + self.console.print(f"Executing: [bold]{pytest_cmd}[/bold]") |
| 51 | + |
| 52 | + return pytest.main(pytest_args) |
| 53 | + |
| 54 | + def _is_verbose(self, args: List[str]) -> bool: |
| 55 | + """Check if verbose output is requested.""" |
| 56 | + return any(arg in ["-v", "--verbose", "-vv", "-vvv"] for arg in args) |
| 57 | + |
| 58 | + def run_multiple(self, executions: List[PytestExecution]) -> int: |
| 59 | + """ |
| 60 | + Run multiple pytest executions in sequence. |
| 61 | +
|
| 62 | + Returns the exit code of the final execution, or the first non-zero exit code. |
| 63 | + """ |
| 64 | + for i, execution in enumerate(executions): |
| 65 | + if execution.description and len(executions) > 1: |
| 66 | + self.console.print( |
| 67 | + f"Phase {i + 1}/{len(executions)}: [italic]{execution.description}[/italic]" |
| 68 | + ) |
| 69 | + |
| 70 | + result = self.run_single(execution.config_file, execution.args) |
| 71 | + if result != 0: |
| 72 | + return result |
| 73 | + |
| 74 | + return 0 |
| 75 | + |
| 76 | + |
| 77 | +class PytestCommand: |
| 78 | + """ |
| 79 | + Base class for pytest-based CLI commands. |
| 80 | +
|
| 81 | + Provides a standard structure for commands that execute pytest |
| 82 | + with specific configurations and argument processing. |
| 83 | + """ |
| 84 | + |
| 85 | + def __init__( |
| 86 | + self, |
| 87 | + config_file: str, |
| 88 | + argument_processors: Optional[List[ArgumentProcessor]] = None, |
| 89 | + ): |
| 90 | + """ |
| 91 | + Initialize the pytest command. |
| 92 | +
|
| 93 | + Args: |
| 94 | + config_file: Pytest configuration file to use |
| 95 | + argument_processors: List of processors to apply to arguments |
| 96 | +
|
| 97 | + """ |
| 98 | + self.config_file = config_file |
| 99 | + self.argument_processors = argument_processors or [] |
| 100 | + self.runner = PytestRunner() |
| 101 | + |
| 102 | + def execute(self, pytest_args: List[str]) -> None: |
| 103 | + """Execute the command with the given pytest arguments.""" |
| 104 | + executions = self.create_executions(pytest_args) |
| 105 | + result = self.runner.run_multiple(executions) |
| 106 | + sys.exit(result) |
| 107 | + |
| 108 | + def create_executions(self, pytest_args: List[str]) -> List[PytestExecution]: |
| 109 | + """ |
| 110 | + Create the list of pytest executions for this command. |
| 111 | +
|
| 112 | + This method can be overridden by subclasses to implement |
| 113 | + multi-phase execution (e.g., for future fill command). |
| 114 | + """ |
| 115 | + processed_args = self.process_arguments(pytest_args) |
| 116 | + |
| 117 | + return [ |
| 118 | + PytestExecution( |
| 119 | + config_file=self.config_file, |
| 120 | + args=processed_args, |
| 121 | + ) |
| 122 | + ] |
| 123 | + |
| 124 | + def process_arguments(self, args: List[str]) -> List[str]: |
| 125 | + """Apply all argument processors to the given arguments.""" |
| 126 | + processed_args = args[:] |
| 127 | + |
| 128 | + for processor in self.argument_processors: |
| 129 | + processed_args = processor.process_args(processed_args) |
| 130 | + |
| 131 | + return processed_args |
| 132 | + |
| 133 | + |
| 134 | +def common_pytest_options(func: Callable[..., Any]) -> Callable[..., Any]: |
| 135 | + """ |
| 136 | + Apply common Click options for pytest-based commands. |
| 137 | +
|
| 138 | + This decorator adds the standard help options that all pytest commands use. |
| 139 | + """ |
| 140 | + func = click.option( |
| 141 | + "-h", |
| 142 | + "--help", |
| 143 | + "help_flag", |
| 144 | + is_flag=True, |
| 145 | + default=False, |
| 146 | + expose_value=True, |
| 147 | + help="Show help message.", |
| 148 | + )(func) |
| 149 | + |
| 150 | + func = click.option( |
| 151 | + "--pytest-help", |
| 152 | + "pytest_help_flag", |
| 153 | + is_flag=True, |
| 154 | + default=False, |
| 155 | + expose_value=True, |
| 156 | + help="Show pytest's help message.", |
| 157 | + )(func) |
| 158 | + |
| 159 | + return click.argument("pytest_args", nargs=-1, type=click.UNPROCESSED)(func) |
| 160 | + |
| 161 | + |
| 162 | +def create_pytest_command_decorator( |
| 163 | + config_file: str, |
| 164 | + argument_processors: Optional[List[ArgumentProcessor]] = None, |
| 165 | + context_settings: Optional[Dict[str, Any]] = None, |
| 166 | +) -> Callable[[Callable[..., Any]], click.Command]: |
| 167 | + """ |
| 168 | + Create a Click command decorator for a pytest-based command. |
| 169 | +
|
| 170 | + Args: |
| 171 | + config_file: Pytest configuration file to use |
| 172 | + argument_processors: List of argument processors to apply |
| 173 | + context_settings: Additional Click context settings |
| 174 | +
|
| 175 | + Returns: |
| 176 | + A decorator that creates a Click command executing pytest |
| 177 | +
|
| 178 | + """ |
| 179 | + default_context_settings = {"ignore_unknown_options": True} |
| 180 | + if context_settings: |
| 181 | + default_context_settings.update(context_settings) |
| 182 | + |
| 183 | + def decorator(func: Callable[..., Any]) -> click.Command: |
| 184 | + command = PytestCommand(config_file, argument_processors) |
| 185 | + |
| 186 | + @click.command( |
| 187 | + context_settings=default_context_settings, |
| 188 | + ) |
| 189 | + @common_pytest_options |
| 190 | + @wraps(func) |
| 191 | + def wrapper(pytest_args: List[str], **kwargs) -> None: |
| 192 | + command.execute(list(pytest_args)) |
| 193 | + |
| 194 | + return wrapper |
| 195 | + |
| 196 | + return decorator |
0 commit comments