### Install FailExtract Python Library Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst Install the FailExtract library using pip. This command installs the core functionality with zero required dependencies. ```bash pip install failextract ``` -------------------------------- ### Run FailExtract Python Example Script Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst Execute the `first_example.py` script from the command line to initiate the failure capture and report generation process. ```bash python first_example.py ``` -------------------------------- ### Install FailExtract Prerequisites Source: https://github.com/dingo-actual/failextract/blob/main/examples/README.md Commands to install FailExtract, including optional dependencies for YAML output support and all recommended features for running examples. ```bash # Install FailExtract (Python 3.11+ required) pip install failextract # For YAML output support (optional) pip install failextract[formatters] # For all features (recommended for examples) pip install failextract[all] ``` -------------------------------- ### Full FailExtract Workflow: Define, Run Tests, and Generate Reports Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst A comprehensive Python example demonstrating how to define multiple decorated test functions, execute them, and then use `FailureExtractor` to save captured failures into both JSON and Markdown reports. ```python #!/usr/bin/env python3 """Your first FailExtract example""" from failextract import extract_on_failure, FailureExtractor, OutputConfig @extract_on_failure def test_basic_assertion(): """A simple test that will fail and be captured.""" x = 10 y = 20 assert x > y, f"Expected {x} to be greater than {y}" @extract_on_failure def test_with_context(): """Test with setup data that will be captured.""" user_data = { 'name': 'John Doe', 'email': 'john@example.com', 'age': 25 } # This failure will capture the user_data context assert user_data['age'] > 30, "User must be over 30" if __name__ == "__main__": print("Running failure extraction example...") # Run the tests (they will fail and be captured) try: test_basic_assertion() except AssertionError: pass # Expected failure try: test_with_context() except AssertionError: pass # Expected failure # Generate reports extractor = FailureExtractor() print(f"Captured {len(extractor.failures)} failures") # Generate JSON report (machine-readable) json_config = OutputConfig("my_failures.json", format="json") extractor.save_report(json_config) print("Generated my_failures.json") # Generate Markdown report (human-readable) md_config = OutputConfig("my_failures.md", format="markdown") extractor.save_report(md_config) print("Generated my_failures.md") ``` -------------------------------- ### FailExtract Development Environment Setup Source: https://github.com/dingo-actual/failextract/blob/main/README.md This comprehensive guide outlines the steps to set up a local development environment for `failextract`. It covers cloning the repository, creating a virtual environment, installing dependencies in development mode, running tests, linting, formatting, and building documentation. ```bash # Clone the repository git clone cd failextract # Create virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install in development mode with all features pip install -e .[development,docs,all] # Run tests pytest # Run linting and formatting ruff check src/ tests/ ruff format src/ tests/ # Build documentation cd docs && make html ``` -------------------------------- ### Quick FailExtract CLI Solutions Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/index.rst Provides quick command-line solutions for common FailExtract tasks, including basic installation, generating JSON reports, and installing with all optional features. ```bash # Quick installation pip install failextract # Generate JSON report failextract report --format json --output failures.json # Install with all features pip install failextract[formatters,cli] ``` -------------------------------- ### Aspirational Installation: FailExtract All Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md An example of aspirational installation instructions that suggest installing all features, including those not yet implemented, or specific non-existent extras like '[analytics]' and '[ide]'. This approach led to user frustration due to non-functional commands. ```bash pip install failextract[all] # Install all features For specific features: - Analytics: `pip install failextract[analytics]` - IDE integration: `pip install failextract[ide]` - Rich HTML: Use external tools (pandoc, sphinx, etc.) ``` -------------------------------- ### Verify FailExtract Core Installation Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Confirm that FailExtract has been successfully installed by importing the library and printing its version. A version number should be displayed without any errors, indicating a successful setup. ```python import failextract print(failextract.__version__) ``` -------------------------------- ### Sample FailExtract Markdown Report for Test Failures Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst An example of the human-readable Markdown report, presenting a captured test failure with its exception details and relevant local variables for easy review. ```markdown # Test Failures Report Generated on: 2025-06-06 09:15:42 ## test_basic_assertion **Exception:** AssertionError **Message:** Expected 10 to be greater than 20 **Local Variables:** - x: 10 - y: 20 ``` -------------------------------- ### User Advocacy Python Example: Simple and Customizable Extraction Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Revised Python examples that are simple, immediately runnable, and demonstrate core functionality. It shows how to start with zero configuration and then customize output when needed, ensuring users can copy-paste and succeed. ```python @extract_on_failure def test_something(): assert process_data() == expected_result # Customize output when needed @extract_on_failure("failures.json") def test_something(): assert process_data() == expected_result ``` -------------------------------- ### FailExtract Monitoring Setup Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/troubleshoot_issues.rst An example Python snippet demonstrating how to set up basic monitoring for FailExtract, including checking memory usage against defined limits. This snippet is incomplete and serves as a starting point. ```python def setup_monitoring(): """Set up monitoring to catch issues early.""" extractor = FailureExtractor() # Check memory usage periodically stats = extractor.get_stats() limits = extractor.get_memory_limits() usage_percent = stats['failures_count'] / limits['max_failures'] * 100 ``` -------------------------------- ### Expected Console Output After Running FailExtract Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst The typical console output seen after successfully running the `first_example.py` script, confirming the execution and report generation. ```text Running failure extraction example... Captured 2 failures Generated my_failures.json Generated my_failures.md ``` -------------------------------- ### User Advocacy Installation: FailExtract Core and Optional Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Revised installation instructions that prioritize user success by recommending a simple core installation first, then guiding users to add optional features as needed. All commands are functional and clearly explain what each enhancement provides. ```bash pip install failextract # Core functionality, zero dependencies ### Add Features When Needed ```bash pip install failextract[formatters] # Adds YAML support pip install failextract[config] # Adds configuration files pip install failextract[cli] # Adds rich terminal output ``` ### All Enhancements ```bash pip install failextract[formatters,config,cli] ``` ``` -------------------------------- ### Bash: Flexible Installation for Different Environments Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md This section demonstrates how `failextract` can be installed with different sets of dependencies using `pip install` based on the deployment environment's needs. It shows installations for minimal serverless environments, full development setups, and specific CI/CD requirements, ensuring the same codebase adapts automatically. ```bash pip install failextract # Core only, minimal size ``` ```bash pip install failextract[formatters,config,cli] # All enhancements ``` ```bash pip install failextract[formatters] # Need YAML for integration ``` -------------------------------- ### First-time Setup for FailExtract Documentation Source: https://github.com/dingo-actual/failextract/blob/main/docs/README.md Initial setup commands to prepare the documentation environment and serve it locally for the first time. ```bash cd docs make setup make serve ``` -------------------------------- ### Python: Get Installation Commands for Missing FailExtract Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/reference/api.rst Shows how to use `suggest_installation` to get the `pip` command required to install optional features, such as YAML formatter support. ```python from failextract import suggest_installation # Suggest installation for YAML support suggestion = suggest_installation("yaml") print(suggestion) # "pip install failextract[formatters]" ``` -------------------------------- ### Install FailExtract for Documentation/Reporting Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Install FailExtract specifically for environments focused on documentation or reporting. This ensures that all available output formatters are installed and ready for use. ```bash pip install failextract[formatters] ``` -------------------------------- ### Sample FailExtract JSON Report for Captured Failures Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst An example of the machine-readable JSON report, detailing a captured test failure including test name, exception type, message, timestamp, and local variables. ```json [ { "test_name": "test_basic_assertion", "exception_type": "AssertionError", "exception_message": "Expected 10 to be greater than 20", "timestamp": "2025-06-06T09:15:42.123456", "local_variables": { "x": 10, "y": 20 } } ] ``` -------------------------------- ### Run Individual FailExtract Examples Source: https://github.com/dingo-actual/failextract/blob/main/examples/README.md Commands to execute specific FailExtract examples directly from the command line, either from the project root or within the example directory. ```bash # Run a specific example python examples/basic/simple_decorator.py # Run from the example directory cd examples/basic/ python multiple_formats.py ``` -------------------------------- ### Get FailExtract CLI Help and Installation Suggestions Source: https://github.com/dingo-actual/failextract/blob/main/README.md Displays the FailExtract CLI help message, which includes suggestions for installing missing features or understanding command options. ```bash failextract --help ``` -------------------------------- ### Local Package Building and Testing for Python Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This snippet provides a sequence of bash commands to locally build, validate, and test the installation of a Python package. It covers installing necessary build tools, creating distribution files, checking their integrity with Twine, and performing a local installation test. ```bash # Install build tools pip install build twine # Build package python -m build # Validate package python -m twine check dist/* # Test installation pip install dist/*.whl python -c "import failextract; print('Success!')" ``` -------------------------------- ### Install FailExtract for Production/CI Environments Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Perform a minimal installation of FailExtract suitable for production or continuous integration environments. This snippet also includes a command to verify that no extra, non-essential dependencies are present after installation. ```bash pip install failextract ``` ```bash pip list | grep -E "(yaml|rich|typer|tomli)" ``` -------------------------------- ### Generate YAML Reports for Configuration Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/generate_reports.rst Demonstrates generating reports in YAML format, useful for configuration files and infrastructure-as-code. Notes that this format requires an optional installation. Examples are provided for both the Python API and the CLI. ```python # Generate YAML (requires: pip install failextract[formatters]) try: config = OutputConfig("failures.yaml", format="yaml") extractor.save_report(config) print("✓ Generated YAML report") except ImportError: print("✗ YAML formatter not available - install with: pip install failextract[formatters]") ``` ```bash # CLI equivalent (if YAML formatter is installed) failextract report --format yaml --output failures.yaml ``` -------------------------------- ### Clone and Install FailExtract for Contribution Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Instructions to clone the FailExtract repository and install it in editable mode with all development dependencies, enabling direct contribution to the project. ```bash git clone https://github.com/your-repo/failextract.git cd failextract pip install -e ".[formatters,config,cli,dev]" ``` -------------------------------- ### Install FailExtract Documentation Dependencies Source: https://github.com/dingo-actual/failextract/blob/main/docs/README.md Commands to install necessary Python dependencies for building the FailExtract documentation, offering multiple installation options. ```bash # Option 1: From requirements.txt pip install -r docs/requirements.txt # Option 2: From pyproject.toml pip install .[docs] # Option 3: Using Makefile make install-deps ``` -------------------------------- ### Install FailExtract in a Virtual Environment Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Recommended steps to create and activate a Python virtual environment, then install FailExtract with optional formatters, ensuring isolated dependencies for your project. ```bash # Create and activate virtual environment python -m venv myproject_env source myproject_env/bin/activate # Linux/Mac # myproject_env\Scripts\activate # Windows # Install FailExtract pip install failextract[formatters] ``` -------------------------------- ### Install All Optional FailExtract Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Install FailExtract along with all available optional features in a single command. This includes support for additional output formatters, TOML configuration, and rich CLI enhancements. ```bash pip install failextract[formatters,config,cli] ``` -------------------------------- ### Honest Documentation Example: FailExtract Core and Optional Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md An example of documentation that accurately reflects current, working features. It clearly distinguishes between core and optional functionalities, providing working examples and realistic installation instructions. This approach reduced support requests and increased user satisfaction. ```markdown # FailExtract: Lightweight Test Failure Extraction ## Core Features (Always Available) - JSON, CSV, and Markdown output formatters - Basic failure information extraction - Simple decorator-based API ## Optional Enhancements - **YAML formatter**: `pip install failextract[formatters]` - **Enhanced configuration**: `pip install failextract[config]` - **Rich CLI**: `pip install failextract[cli]` ## Simple Example (Works Immediately) ```python @extract_on_failure def test_something(): assert 1 + 1 == 3 # Failure automatically saved to JSON ``` ``` -------------------------------- ### CI Pipeline for Documentation Quality Testing Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md A CI pipeline configuration demonstrating how to treat documentation as code, including steps to test documentation examples, validate installation instructions in a clean environment, and check API documentation coverage. ```yaml documentation_quality: runs-on: ubuntu-latest steps: - name: Test Documentation Examples run: | # Extract and test all code examples python scripts/test_docs_examples.py - name: Validate Installation Instructions run: | # Test installation commands in clean environment docker run --rm python:3.9 sh -c " pip install -e . && pip install .[formatters] && python -c 'import failextract; print(failextract.__version__)' " - name: Check Documentation Coverage run: | # Verify all public APIs are documented python scripts/check_api_coverage.py ``` -------------------------------- ### Install FailExtract for Development Environments Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Set up FailExtract for development purposes, including commonly used optional features. This ensures developers have access to formatters and enhanced CLI tools. ```bash pip install failextract[formatters,cli] ``` -------------------------------- ### Install FailExtract with All Features Source: https://github.com/dingo-actual/failextract/blob/main/README.md Installs FailExtract with all available features, including core and all optional extras. ```bash pip install failextract[all] ``` -------------------------------- ### Python Example Template for FailExtract Contributions Source: https://github.com/dingo-actual/failextract/blob/main/examples/README.md Provides a basic template for contributing new examples to the FailExtract project. It includes boilerplate for imports, docstrings for documentation, and a standard main execution block to ensure examples are runnable and well-documented. ```python #!/usr/bin/env python3 """ [Category] example: [Title] Brief description of what this example demonstrates. """ from failextract import extract_on_failure, FailureExtractor, OutputConfig # Your example code here if __name__ == "__main__": print("[Example name] example") # Demonstration code ``` -------------------------------- ### Examples as Integration Tests - Basic Usage Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Emphasizes the principle of treating documentation examples as executable integration tests to guarantee their accuracy and prevent obsolescence. This pytest example shows how to copy documented code, verify its expected behavior (e.g., raising an `AssertionError`), and confirm the creation of output files. ```python # Documentation examples are executable tests @pytest.mark.documentation def test_basic_usage_example(): """Test the basic usage example from documentation.""" # Copy the exact code from documentation @extract_on_failure def test_something(): assert 1 + 1 == 3 # Verify it works as documented with pytest.raises(AssertionError): test_something() # Verify output file is created assert os.path.exists("failures.json") ``` -------------------------------- ### Anti-Pattern: Implementation-Focused Example (Wrong) Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md An example showing how the tool works internally, which is an anti-pattern as users need problem-solving examples. ```python # Example: Using the FormatterRegistry registry = FormatterRegistry() formatter = registry.get_formatter("json") output = formatter.format(failure_data) ``` -------------------------------- ### Run FailExtract Custom Formatter Example Source: https://github.com/dingo-actual/failextract/blob/main/examples/README.md Illustrates how to create custom output formatters by implementing the OutputFormatter interface, registering them, and generating domain-specific output. ```bash cd examples/advanced/ python custom_formatter.py ``` -------------------------------- ### Install Optional Dependencies for YAML Support Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/multiple_formats.rst These commands show how to install the necessary Python packages to enable YAML report generation. Option 1 installs `failextract` with all formatters, while Option 2 installs `pyyaml` separately. ```bash # Option 1: Install with YAML support pip install failextract[formatters] ``` ```bash # Option 2: Install YAML library separately pip install pyyaml ``` -------------------------------- ### Install FailExtract for Shared Team Configuration Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Install the `config` extra to enable shared team settings via `.failextract.toml`. ```bash pip install failextract[config] # Adds .failextract.toml support ``` -------------------------------- ### Install FailExtract Core Package Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Install the core FailExtract library with its most commonly needed features. This includes the @extract_on_failure decorator, basic CLI commands, and support for JSON, Markdown, XML, and CSV output formats, with zero dependencies beyond Python's standard library. ```bash pip install failextract ``` -------------------------------- ### Progressive Disclosure of Complexity - Customize Output Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Expands on the 'Quick Start' by showing how to customize the output format and filename, illustrating the next step in progressive disclosure. This example configures `@extract_on_failure` to generate a readable markdown report, building upon the basic usage. ```python @extract_on_failure("report.md") # Readable markdown report def test_something(): assert condition ``` -------------------------------- ### Fail Fast with Helpful Guidance: Dependency Check Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/architectural_philosophy.md Illustrates FailExtract's principle of failing fast with clear, actionable guidance. This example shows how an `ImportError` is caught and re-raised with a user-friendly message and installation instructions for a missing dependency. ```python try: import yaml except ImportError: raise ImportError( "PyYAML is required for YAML output format. " "Install it with: pip install failextract[formatters]" ) from None ``` -------------------------------- ### Resolve FailExtract Installation Permission Issues Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Commands to install FailExtract for the current user only or within a dedicated virtual environment, addressing common permission-related installation problems. ```bash # Install for current user only pip install --user failextract # Or use virtual environment (recommended) python -m venv failextract_env source failextract_env/bin/activate # Linux/Mac # failextract_env\Scripts\activate # Windows pip install failextract ``` -------------------------------- ### Install FailExtract in GitHub Actions Workflow Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst YAML snippet for a GitHub Actions workflow step that installs FailExtract with formatters and verifies the installation, suitable for integration into CI/CD pipelines. ```yaml - name: Install FailExtract run: | pip install failextract[formatters] python -c "import failextract; print('Installed:', failextract.__version__)" ``` -------------------------------- ### Check Python and Pip Versions Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Verify the installed versions of Python and pip to ensure they meet FailExtract's minimum and recommended requirements. This helps prevent compatibility issues during installation or usage. ```bash python --version ``` ```bash pip --version ``` -------------------------------- ### Install FailExtract for Development (All Optional Features) Source: https://github.com/dingo-actual/failextract/blob/main/README.md Installs FailExtract with all optional features required for development purposes. ```bash pip install failextract[development] ``` -------------------------------- ### Handle FailExtract Version Conflicts Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Commands to check the installed FailExtract version and force a reinstallation, useful for resolving version-related conflicts or ensuring a clean installation. ```bash # Check installed version python -c "import failextract; print(failextract.__version__)" # Force reinstall pip install --force-reinstall failextract ``` -------------------------------- ### Progressive Disclosure: Basic Usage Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md A basic usage example demonstrating simple file output with `@extract_on_failure`. ```python @extract_on_failure("report.json") # Simple file output ``` -------------------------------- ### Install FailExtract for Better Output Formatting (YAML Support) Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Install the `formatters` extra to enable YAML output, making JSON less readable. ```bash pip install failextract[formatters] # Adds YAML support ``` -------------------------------- ### Run Basic FailExtract Decorator Example Source: https://github.com/dingo-actual/failextract/blob/main/examples/README.md Demonstrates the basic usage of the `@extract_on_failure` decorator, automatic failure context capture, and report generation in JSON and Markdown formats. ```bash cd examples/basic/ python simple_decorator.py ``` -------------------------------- ### GitHub Actions Step for Sphinx Multi-format PDF Build Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst A workflow step to build the documentation in PDF format using Sphinx's LaTeX builder. This allows for generating alternative documentation formats alongside the standard HTML output. ```yaml - name: Build PDF run: sphinx-build -b latex docs docs/build/latex ``` -------------------------------- ### Install FailExtract for Rich Terminal Output Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Install the `cli` extra to add colorized CLI reports and rich terminal formatting. ```bash pip install failextract[cli] # Adds rich terminal formatting ``` -------------------------------- ### Locally Test Documentation Build Process Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst These bash commands facilitate local testing of the documentation build. By navigating to the `docs` directory and executing `make html`, developers can build the documentation locally, allowing for early detection of build errors and verification of the generated HTML output before committing or releasing. ```bash cd docs make html # Check for build errors # Verify HTML output in build/html/ ``` -------------------------------- ### Rejected Entry Points Approach for Plugin Discovery in Python Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/architectural_philosophy.md This snippet illustrates an alternative plugin discovery mechanism using `setuptools` entry points, which was considered but rejected. While it allows external packages to register formatters, it was deemed more complex for packaging, harder for users to understand, and introduced discovery complexity compared to the chosen registry pattern. ```Python # setuptools entry points approach (rejected) [console_scripts] failextract_json = failextract.formatters:JSONFormatter failextract_custom = my_package:CustomFormatter ``` -------------------------------- ### Expected Output for Successful Sphinx Documentation Build Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst This text snippet displays the typical console output indicating a successful Sphinx documentation build. It confirms that Sphinx has processed the specified number of source files and generated HTML pages, signifying that the build process completed without critical issues and the output is ready for deployment. ```text Running Sphinx v8.2.3 building [html]: targets for 25 source files build succeeded, X warnings. The HTML pages are in build/html. ``` -------------------------------- ### Perform a Clean Reinstall of FailExtract Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Execute a clean reinstall of FailExtract, which involves first uninstalling the package and then reinstalling it. This process is often effective for resolving persistent installation or dependency issues. ```bash pip uninstall failextract ``` ```bash pip install failextract ``` -------------------------------- ### Install Rich CLI Features for FailExtract Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Integrate enhanced command-line interface features into FailExtract, providing colored and formatted terminal output. This functionality depends on the rich and typer libraries. ```bash pip install failextract[cli] ``` -------------------------------- ### Troubleshoot 'No module named failextract' Error Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/troubleshoot_issues.rst Diagnose and resolve the 'ImportError: No module named 'failextract'' issue, typically caused by incorrect installation or environment setup. Includes steps to check installation, Python interpreter, and various installation methods. ```text ImportError: No module named 'failextract' ``` ```bash # Check if FailExtract is installed pip list | grep failextract # Check which Python interpreter you're using which python python --version # Try importing in Python directly python -c "import failextract; print('FailExtract available')" ``` ```bash # Install FailExtract pip install failextract # If using virtual environment, ensure it's activated source venv/bin/activate # Linux/Mac # venv\Scripts\activate # Windows # Install in user directory if permission issues pip install --user failextract # Force reinstall if corrupted pip uninstall failextract pip install failextract ``` -------------------------------- ### Expected Output for GitHub Pages Deployment Confirmation Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst This text snippet shows the console messages confirming a successful deployment to GitHub Pages by the `peaceiris/actions-gh-pages` action. It indicates that the documentation content has been successfully pushed to the `gh-pages` branch, making it live on the GitHub Pages site. ```text [INFO] Deploy to gh-pages branch [INFO] workDir: /github/workspace [INFO] Deployment successful ``` -------------------------------- ### FailExtract Lazy Loading for Optional Formatters Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md Shows how optional formatters like `YAMLFormatter` are lazily loaded, providing helpful error messages if required dependencies are not installed, guiding users to `pip install failextract[formatters]`. ```python def __getattr__(name: str): """Lazy loading with helpful error messages.""" if name == "YAMLFormatter": try: from .core.formatters.yaml import YAMLFormatter return YAMLFormatter except ImportError: raise ImportError( "YAMLFormatter requires PyYAML. " "Install with: pip install failextract[formatters]" ) from None ``` -------------------------------- ### Generate Progressive Enhancement Error Messages Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md This Python function generates user-friendly error messages that guide users to install additional dependencies for specific features. It provides clear instructions for `pip install failextract[extra]` or `failextract[all]`. ```python def _format_enhancement_error(feature: str, extra: str) -> str: return ( f"{feature} requires additional dependencies. " f"Install with: pip install failextract[{extra}]\n" f"Or install all enhancements: pip install failextract[all]" ) ``` -------------------------------- ### Install and Use Enhanced CLI Output Source: https://github.com/dingo-actual/failextract/blob/main/README.md This example demonstrates how to enable rich terminal output for `failextract` CLI commands. It involves installing the `cli` extra and then running `failextract report` and `failextract stats` to see the enhanced formatting. ```bash pip install failextract[cli] ``` ```bash # Now get enhanced terminal output failextract report --format json --output failures.json failextract stats # Enhanced with rich formatting ``` -------------------------------- ### GitHub Actions Workflow for Automated Documentation Deployment Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst This YAML configuration defines a GitHub Actions workflow (`docs.yml`) that triggers upon a GitHub release publication. It sets up Python 3.11, installs necessary Sphinx dependencies, builds the documentation, and then deploys the generated HTML to GitHub Pages using the `peaceiris/actions-gh-pages` action. This ensures documentation is automatically updated with each new release. ```yaml # .github/workflows/docs.yml name: Documentation on: release: types: [published] jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install dependencies run: | python -m pip install --upgrade pip pip install sphinx sphinx-rtd-theme myst-parser - name: Build documentation run: | cd docs make html - name: Deploy to GitHub Pages uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/build/html ``` -------------------------------- ### Examples of Helpful Enhancement Error Messages Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md These examples demonstrate how `failextract` provides explicit `ImportError` and `ConfigurationError` messages, directing users to the correct `pip install` command to enable missing features like YAML formatting or configuration file support. ```python ImportError: YAMLFormatter requires PyYAML. Install with: pip install failextract[formatters] Or install all enhancements: pip install failextract[all] ConfigurationError: Configuration file support requires tomli. Install with: pip install failextract[config] Or install all enhancements: pip install failextract[all] ``` -------------------------------- ### Python Pytest: Mocking Missing Dependencies for Error Handling Tests Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/testing_strategy.md This Python Pytest snippet illustrates how to use `monkeypatch` to simulate a missing external dependency (PyYAML). It tests the `YAMLFormatter`'s behavior when `yaml` is not installed, verifying that it raises an `ImportError` with a helpful message guiding the user to install the required package. ```python class TestYAMLFormatter: def test_yaml_unavailable_error_message(self, monkeypatch): """Test behavior when PyYAML is not installed.""" # Mock the import to simulate missing dependency def mock_import(name, *args): if name == 'yaml': raise ImportError("No module named 'yaml'") return original_import(name, *args) monkeypatch.setattr(builtins, '__import__', mock_import) formatter = YAMLFormatter() with pytest.raises(ImportError) as exc_info: formatter.format([{"test": "data"}]) # Verify helpful error message assert "PyYAML is required" in str(exc_info.value) assert "pip install" in str(exc_info.value) ``` -------------------------------- ### Capture Python Test Failures with @extract_on_failure Decorator Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/getting_started.rst Apply the `@extract_on_failure` decorator to a Python test function. This automatically captures failure context, such as local variables, when an exception is raised. ```python from failextract import extract_on_failure @extract_on_failure def test_basic_assertion(): """A simple test that will fail and be captured.""" x = 10 y = 20 assert x > y, f"Expected {x} to be greater than {y}" ``` -------------------------------- ### Aspirational Documentation Example: FailExtract Features Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md An example of documentation that describes desired but unimplemented features, leading to user confusion and increased support burden. It showcases features like advanced analytics, IDE integration, CI/CD support, and rich reports, most of which were not yet functional. Includes a 'pip install' command for a non-existent '[formatters]' extra and a 'pandoc' command. ```markdown # FailExtract Features ## Advanced Analytics FailExtract provides comprehensive test failure analytics with dependency graphing, pattern recognition, and trend analysis. ### IDE Integration Seamless integration with VS Code, PyCharm, and Vim through LSP protocol. ### CI/CD Platform Support - GitHub Actions - GitLab CI - Jenkins - CircleCI - Azure DevOps ### Rich Reports via External Tools Generate beautiful HTML reports using external conversion tools. ## Installation ```bash pip install failextract[formatters] # Core formatters # Convert to HTML: pandoc report.md -o report.html ``` ``` -------------------------------- ### Use FailExtract Command Line Interface Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/reference/api.rst This section provides various command-line examples for interacting with FailExtract. It covers generating reports in different formats (JSON, Markdown, CSV, YAML, XML), listing captured failures, displaying statistics, checking available features, and clearing all stored data. An example for advanced analysis is also included, conditional on an optional installation. ```bash # Generate different format reports failextract report --format json --output failures.json failextract report --format markdown --output failures.md failextract report --format csv --output failures.csv failextract report --format yaml --output failures.yaml failextract report --format xml --output failures.xml # List captured failures failextract list --format table failextract list --format json # Show statistics and analysis failextract stats --format table failextract stats --format json # Check available features failextract features --format table # Clear all data failextract clear --confirm # Advanced analysis (if analytics extra installed) # failextract analyze --trends --days 30 ``` -------------------------------- ### Prevent Silent Feature Degradation with Explicit Errors Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md This snippet demonstrates the anti-pattern of silently degrading features when dependencies are missing, contrasting it with the correct approach of raising an explicit `ImportError` that guides the user to install the required dependencies. ```python # Wrong: Silently ignore unsupported features if yaml_available: return yaml.dump(data) else: return json.dumps(data) # User doesn't know they didn't get YAML # Right: Explicit error with upgrade path if not yaml_available: raise ImportError("YAML format requires: pip install failextract[formatters]") ``` -------------------------------- ### GitHub Actions Step for Sphinx Link Checking Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst A workflow step that executes Sphinx's built-in link checker. This ensures all internal and external links within the documentation are valid, preventing broken links in the deployed site. ```yaml - name: Check links run: sphinx-build -b linkcheck docs docs/build/linkcheck ``` -------------------------------- ### Handle FailExtract Import Errors Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/reference/api.rst This example demonstrates a robust way to handle ImportError when the failextract library or its components are not found. It uses a try-except block to catch the error, print a user-friendly message, and suggest the correct installation command, ensuring graceful degradation. ```python try: from failextract import extract_on_failure except ImportError as e: print(f"FailExtract not available: {e}") print("Install with: pip install failextract") ``` -------------------------------- ### Run the Multi-Format Report Generation Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/multiple_formats.rst This command executes the Python script to generate the failure reports in different formats. It assumes the script is saved as `multiple_formats_example.py`. ```bash python multiple_formats_example.py ``` -------------------------------- ### Python: Basic Usage for Data Scientists Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md This snippet shows the initial, simple usage of the `@extract_on_failure` decorator for a data scientist just starting out. It highlights how the core functionality can be used with minimal setup, focusing on immediate problem-solving without requiring advanced configurations. ```python # Day 1: Just wants to see what went wrong @extract_on_failure def test_data_processing(): process_csv("data.csv") ``` -------------------------------- ### Python: Dynamic Import with Helpful Error Messages Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/architectural_philosophy.md Demonstrates using `__getattr__` in Python for dynamic module imports. This approach provides specific, user-friendly error messages when optional dependencies, like PyYAML for `YAMLFormatter`, are missing, guiding users on how to install them. ```python def __getattr__(name: str): """Dynamic import with helpful error messages.""" if name == "YAMLFormatter": try: from .core.formatters.yaml import YAMLFormatter return YAMLFormatter except ImportError: raise ImportError( "YAMLFormatter requires PyYAML. " "Install with: pip install failextract[formatters]" ) from None raise AttributeError(f"module {__name__} has no attribute {name}") ``` -------------------------------- ### Trigger Configuration for Future Testing Workflow Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_ci_cd.rst This partial YAML snippet demonstrates the `on` trigger configuration for a potential future testing workflow. It indicates that, similar to the documentation workflow, a testing workflow would also be configured to execute based on specific events, laying the groundwork for expanding CI/CD capabilities. ```yaml on: ``` -------------------------------- ### Expected Output for Successful PyPI Package Upload Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This text snippet illustrates the console output during a successful package upload to PyPI. It confirms that both the wheel and sdist distribution files are being uploaded to the official PyPI repository, indicating a successful publication. ```text Uploading distributions to https://upload.pypi.org/legacy/ Uploading failextract-1.0.0-py3-none-any.whl Uploading failextract-1.0.0.tar.gz ``` -------------------------------- ### Error Messages as Documentation - PyYAML ImportError Example Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md Illustrates the philosophy of treating error messages as a form of documentation, providing immediate help to users. This Python `try-except` block shows how to catch an `ImportError` and provide a clear, actionable message with exact installation commands and alternative solutions. ```python try: import yaml except ImportError: raise ImportError( "YAML formatter requires PyYAML. " "Install with: pip install failextract[formatters]\n" "Or install all enhancements: pip install failextract[all]" ) from None ``` -------------------------------- ### FailExtract Configuration Evolution Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md Demonstrates the progression of configuration in FailExtract, from simple decorator parameters to configuration objects and finally to file-based configuration using `.failextract.toml`. ```python # Level 1: Simple parameters @extract_on_failure("report.json") # Level 2: Configuration object @extract_on_failure(OutputConfig("report.json", append=True)) # Level 3: File-based configuration @extract_on_failure # Uses configuration file ``` ```toml # .failextract.toml: [output] default_format = "yaml" include_fixtures = true output_directory = "test_reports" ``` -------------------------------- ### Install FailExtract in a Docker Container Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Dockerfile instructions to build a Docker image with Python 3.9, install FailExtract with formatters, and verify its installation within the container environment. ```dockerfile FROM python:3.9-slim # Install FailExtract RUN pip install failextract[formatters] # Verify installation RUN python -c "import failextract; print('FailExtract ready')" ``` -------------------------------- ### Anti-Pattern: Over-Documentation of OutputConfig Parameters Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/documentation_philosophy.md An example of documenting every possible parameter and option, which can overwhelm users. This shows the `OutputConfig` parameters with their types and descriptions. ```APIDOC OutputConfig Parameters - `output`: str | Path | OutputFormat | None - Output destination - `format`: str | OutputFormat | None - Output format specifier - `append`: bool = False - Append to existing file - `include_source`: bool = True - Include source code - `include_fixtures`: bool = False - Include fixture information - `include_locals`: bool = False - Include local variables - `max_depth`: int = 5 - Maximum stack trace depth - `filter_stdlib`: bool = True - Filter standard library frames - `timestamp_format`: str = ISO8601 - Timestamp format string - `encoding`: str = 'utf-8' - Output file encoding ``` -------------------------------- ### Pytest Conftest Setup for Advanced Failure Extraction Plugin Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/tutorials/pytest_integration.rst This `conftest.py` example demonstrates how to create a custom Pytest plugin (`FailExtractPlugin`) for maximum flexibility in failure extraction. It includes methods for configuring the plugin, applying extraction to marked tests, and capturing detailed test information for both failed and passed tests. ```python # conftest.py import pytest from failextract import FailureExtractor, OutputConfig, extract_on_failure class FailExtractPlugin: """Advanced FailExtract pytest plugin.""" def __init__(self): self.extractor = FailureExtractor() self.config = None def pytest_configure(self, config): """Configure plugin based on pytest options.""" self.config = config # Set memory limits based on test count estimate self.extractor.set_memory_limits(max_failures=500, max_passed=100) def pytest_runtest_call(self, pyfuncitem): """Called during test execution.""" # Apply extraction for marked tests if pyfuncitem.get_closest_marker("extract_failures"): original_func = pyfuncitem.obj if not hasattr(original_func, '_failextract_wrapped'): decorated_func = extract_on_failure( include_locals=True, include_fixtures=True, max_depth=10 )(original_func) decorated_func._failextract_wrapped = True pyfuncitem.obj = decorated_func def pytest_runtest_makereport(self, item, call): """Capture detailed test information.""" if call.when == "call": if call.excinfo is not None: # Test failed - enhanced capture failure_data = { "test_name": item.name, "test_module": item.module.__name__ if item.module else "unknown", "test_file": str(item.fspath), "test_line": item.location[1] if item.location else None, "exception_type": call.excinfo.type.__name__, "exception_message": str(call.excinfo.value), "timestamp": call.start, "duration": call.stop - call.start, "markers": [mark.name for mark in item.iter_markers()], } self.extractor.add_failure(failure_data) else: # Test passed - track for statistics passed_data = { "test_name": item.name, "timestamp": call.start, "duration": call.stop - call.start } ``` -------------------------------- ### GitHub Actions Step for Uploading to TestPyPI Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This YAML snippet provides a GitHub Actions step to upload a package to TestPyPI before a full release. It uses 'twine upload' with the '--repository testpypi' flag, allowing for pre-publication testing of the package distribution and upload process. ```yaml - name: Upload to TestPyPI first run: python -m twine upload --repository testpypi dist/* ``` -------------------------------- ### Python: Graceful Import of Optional Dependencies Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/discussions/progressive_enhancement.md This Python class demonstrates how to import optional dependencies like 'rich' only when they are accessed, preventing performance overhead and providing clear error messages if the dependency is missing. It ensures that advanced features are only loaded when explicitly needed, guiding users on how to install required libraries. ```python class AdvancedFeature: def __init__(self): self._rich = None @property def rich(self): if self._rich is None: try: import rich self._rich = rich except ImportError: raise ImportError( "Rich formatting requires the 'rich' library. " "Install with: pip install failextract[cli]" ) from None return self._rich ``` -------------------------------- ### GitHub Actions Workflow for Test PyPI Release Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This YAML snippet defines a GitHub Actions workflow for testing a PyPI release. It is configured for manual triggering via 'workflow_dispatch' and includes a job designed to simulate the main release workflow steps without actually uploading to PyPI. ```yaml # .github/workflows/test-pypi-release.yml name: Test PyPI Release on: workflow_dispatch: # Manual trigger jobs: test-build-and-publish: # Same steps as main workflow but without PyPI upload ``` -------------------------------- ### Expected Output for Successful Python Package Build Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This text snippet shows the console output expected when a Python package successfully builds using 'python -m build'. It indicates the creation of an isolated environment, installation of build dependencies, and the successful generation of sdist and wheel distribution files. ```text * Creating isolated environment: venv+pip... * Installing packages in isolated environment: - hatchling * Building sdist... * Building wheel from sdist Successfully built failextract-1.0.0.tar.gz and failextract-1.0.0-py3-none-any.whl ``` -------------------------------- ### GitHub Actions Workflow for Automated PyPI Release Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/setup_pypi_release.rst This GitHub Actions workflow automates the PyPI release process, triggering upon a new GitHub release. It sets up Python, installs necessary build tools, validates the package version against the git tag, builds and validates the distribution, and securely publishes it to PyPI using a repository secret. This ensures consistent and automated deployment of Python packages. ```yaml # .github/workflows/pypi-release.yml name: PyPI Release on: release: types: [published] jobs: build-and-publish: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install build tools run: | python -m pip install --upgrade pip pip install build twine - name: Validate version consistency run: | # Extract version from git tag (remove 'v' prefix if present) GIT_TAG=${GITHUB_REF#refs/tags/} GIT_VERSION=${GIT_TAG#v} # Extract version from pyproject.toml PYPROJECT_VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") echo "Git tag version: $GIT_VERSION" echo "pyproject.toml version: $PYPROJECT_VERSION" if [ "$GIT_VERSION" != "$PYPROJECT_VERSION" ]; then echo "Version mismatch: git tag ($GIT_VERSION) != pyproject.toml ($PYPROJECT_VERSION)" exit 1 fi echo "Version validation passed: $GIT_VERSION" - name: Build package run: | python -m build - name: Validate package run: | # Check that the package can be built and contains expected files python -m twine check dist/* # List built artifacts echo "Built artifacts:" ls -la dist/ # Verify wheel can be installed and imported pip install dist/*.whl python -c "import failextract; print(f'FailExtract version: {failextract.__version__}')" - name: Publish to PyPI env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} run: | python -m twine upload dist/* ``` -------------------------------- ### Diagnose FailExtract Import Errors Source: https://github.com/dingo-actual/failextract/blob/main/docs/source/how-to/install_failextract.rst Python code to verify if the FailExtract library is properly installed and importable, catching and reporting any ImportError to help troubleshoot installation issues. ```python # Check if FailExtract is properly installed try: import failextract print("✓ FailExtract is available") except ImportError as e: print(f"✗ FailExtract not found: {e}") ```