CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pytest-html

A pytest plugin for generating HTML reports of test results with enhanced visualizations and extensibility.

Pending
Overview
Eval results
Files

hooks.mddocs/

Report Customization Hooks

Pytest hooks that enable customization of HTML report content, formatting, and behavior. These hooks integrate with pytest's plugin system to provide extensive control over report generation and appearance.

Capabilities

Report Title Customization

Customizes the title displayed in the HTML report.

def pytest_html_report_title(report):
    """
    Called before adding the title to the report.
    
    This hook allows modification of the report title that appears
    at the top of the HTML report.

    Parameters:
    - report: Report object with title attribute that can be modified

    Usage:
        def pytest_html_report_title(report):
            report.title = "Custom Test Report - " + report.title
    """

Usage Example:

# In conftest.py
def pytest_html_report_title(report):
    report.title = f"Test Results - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"

Results Summary Customization

Customizes the summary section that appears before the test results table.

def pytest_html_results_summary(prefix, summary, postfix, session):
    """
    Called before adding the summary section to the report.
    
    This hook allows modification of the summary information displayed
    above the test results table, including test counts and duration.

    Parameters:
    - prefix (list): List of summary items to display before main summary
    - summary (list): List of main summary items (test counts, duration)
    - postfix (list): List of summary items to display after main summary
    - session: pytest session object

    Usage:
        def pytest_html_results_summary(prefix, summary, postfix, session):
            prefix.append("Custom prefix information")
            postfix.append("Custom postfix information")
    """

Usage Example:

# In conftest.py
def pytest_html_results_summary(prefix, summary, postfix, session):
    # Add environment information
    prefix.append(f"Test Environment: {os.environ.get('TEST_ENV', 'unknown')}")
    
    # Add custom metrics
    postfix.append(f"Total Test Files: {len(session.items)}")

Table Header Customization

Customizes the column headers in the test results table.

def pytest_html_results_table_header(cells):
    """
    Called after building results table header.
    
    This hook allows modification of the table header columns,
    including adding custom columns or reordering existing ones.

    Parameters:
    - cells (list): List of HTML strings representing table header cells

    Usage:
        def pytest_html_results_table_header(cells):
            cells.insert(1, '<th class="sortable">Priority</th>')
    """

Usage Example:

# In conftest.py
def pytest_html_results_table_header(cells):
    # Add a column for test category
    cells.insert(1, '<th class="sortable" data-column-type="category">Category</th>')
    
    # Add a column for custom metadata
    cells.append('<th>Custom Info</th>')

Table Row Customization

Customizes individual rows in the test results table.

def pytest_html_results_table_row(report, cells):
    """
    Called after building results table row.
    
    This hook allows modification of individual test result rows,
    including adding custom cell content that corresponds to custom headers.

    Parameters:
    - report: pytest test report object
    - cells (list): List of HTML strings representing table row cells

    Usage:
        def pytest_html_results_table_row(report, cells):
            # Add custom cell content
            priority = getattr(report, 'priority', 'normal')
            cells.insert(1, f'<td>{priority}</td>')
    """

Usage Example:

# In conftest.py
def pytest_html_results_table_row(report, cells):
    # Add test category based on node ID
    if 'unit' in report.nodeid:
        category = 'Unit'
    elif 'integration' in report.nodeid:
        category = 'Integration'
    else:
        category = 'Other'
    
    cells.insert(1, f'<td>{category}</td>')
    
    # Add custom metadata
    custom_info = getattr(report, 'custom_data', 'N/A')
    cells.append(f'<td>{custom_info}</td>')

Additional HTML Content

Adds custom HTML content to individual test results.

def pytest_html_results_table_html(report, data):
    """
    Called after building results table additional HTML.
    
    This hook allows addition of custom HTML content that appears
    in the expandable section of each test result row.

    Parameters:
    - report: pytest test report object
    - data (list): List of HTML strings for additional content

    Usage:
        def pytest_html_results_table_html(report, data):
            if hasattr(report, 'custom_html'):
                data.append(report.custom_html)
    """

Usage Example:

# In conftest.py
def pytest_html_results_table_html(report, data):
    # Add custom debugging information
    if hasattr(report, 'debug_info'):
        debug_html = f"""
        <div class="debug-info">
            <h3>Debug Information</h3>
            <pre>{report.debug_info}</pre>
        </div>
        """
        data.append(debug_html)

Duration Formatting

Customizes how test durations are formatted and displayed.

def pytest_html_duration_format(duration):
    """
    Called before using the default duration formatting.
    
    This hook allows customization of how test execution durations
    are formatted in the HTML report.

    Parameters:
    - duration (float): Test duration in seconds

    Returns:
    - str or None: Custom formatted duration string, or None to use default

    Usage:
        def pytest_html_duration_format(duration):
            if duration < 1:
                return f"{duration*1000:.0f}ms"
            return f"{duration:.2f}s"
    """

Usage Example:

# In conftest.py
def pytest_html_duration_format(duration):
    # Format durations with appropriate units
    if duration < 0.001:
        return f"{duration*1000000:.0f}μs"
    elif duration < 1:
        return f"{duration*1000:.0f}ms"
    elif duration < 60:
        return f"{duration:.2f}s"
    else:
        minutes = int(duration // 60)
        seconds = duration % 60
        return f"{minutes}m {seconds:.1f}s"

Hook Implementation

All hooks are implemented using pytest's hookimpl decorator and can be defined in conftest.py files or pytest plugins:

import pytest

@pytest.hookimpl
def pytest_html_report_title(report):
    # Implementation here
    pass

# Or without decorator for simple hooks
def pytest_html_results_summary(prefix, summary, postfix, session):
    # Implementation here
    pass

Integration with Report Generation

These hooks are called at specific points during HTML report generation:

  1. pytest_html_report_title: Called when setting up the report structure
  2. pytest_html_results_summary: Called before rendering the summary section
  3. pytest_html_results_table_header: Called when building the table header
  4. pytest_html_results_table_row: Called for each test result row
  5. pytest_html_results_table_html: Called when adding extra HTML content
  6. pytest_html_duration_format: Called when formatting duration values

The hooks provide a powerful way to customize reports without modifying the core plugin code, enabling teams to adapt the HTML reports to their specific needs and branding requirements.

Install with Tessl CLI

npx tessl i tessl/pypi-pytest-html

docs

extras.md

fixtures.md

hooks.md

index.md

tile.json