### Install JavaScript Dependencies and Run Tests
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Installs necessary Node.js dependencies for JavaScript testing using npm and then executes the unit tests.
```bash
$ npm install
```
```bash
$ npm run unit
```
--------------------------------
### Install Pre-commit Hooks
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Installs pre-commit hooks for code styling and formatting using Hatch or pip. This ensures code quality before commits.
```bash
$ hatch -e test run pre-commit install
```
```bash
$ pip install pre-commit
$ pre-commit install
```
--------------------------------
### Start Docker Image for Integration Tests
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Starts the Docker image required for running integration tests, which involves rendering reports using Selenium and BeautifulSoup. Includes commands to restart the image if it becomes unresponsive.
```bash
./start
```
```bash
./start down && ./start
```
--------------------------------
### Attach Text and URLs
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Provides examples for attaching plain text logs or clickable URL links to test reports.
```python
import pytest
import pytest_html
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call":
extras.append(pytest_html.extras.text("Additional notes about this test case", name="Notes"))
extras.append(pytest_html.extras.url("http://www.example.com/", name="Related Documentation"))
report.extras = extras
```
--------------------------------
### Compile CSS with npm
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Installs npm dependencies and compiles SASS/SCSS files into CSS. This command is used to build the application's stylesheets.
```bash
$ npm install
```
```bash
$ npm run build
```
--------------------------------
### Override Report Display via Query Parameters
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Examples of using URL query parameters to dynamically control report visibility, collapsing, and sorting.
```bash
report.html?visible=failed,error
report.html?collapsed=All
report.html?sort=testId
```
--------------------------------
### Advanced Report Customization with Hooks
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
A comprehensive example showing how to modify the report title, add custom summary sections, inject table columns, and attach extra debugging information to failed tests.
```python
import pytest
import pytest_html
from datetime import datetime
from pytest_metadata.plugin import metadata_key
def pytest_configure(config):
config.stash[metadata_key]["Project"] = "My Application"
config.stash[metadata_key]["Tester"] = "QA Team"
def pytest_html_report_title(report):
report.title = f"Test Report - {datetime.now().strftime('%Y-%m-%d %H:%M')}"
def pytest_html_results_summary(prefix, summary, postfix):
prefix.extend(["
Test Suite: Regression Tests
"])
def pytest_html_results_table_header(cells):
cells.insert(2, "Description | ")
def pytest_html_results_table_row(report, cells):
cells.insert(2, f"{getattr(report, 'description', '')} | ")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__) if item.function.__doc__ else ""
extras = getattr(report, "extras", [])
if report.when == "call":
if report.failed:
extras.append(pytest_html.extras.html("Test failed - check logs
"))
extras.append(pytest_html.extras.url("https://wiki.example.com/debugging", name="Debugging Guide"))
report.extras = extras
```
--------------------------------
### Build Documentation
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Builds the project documentation using Tox with the 'docs' environment. This command is used to generate the documentation that is hosted on Read the Docs.
```bash
$ tox -e docs
```
--------------------------------
### Use Extras Fixture
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Demonstrates using the 'extras' fixture to add content directly within test functions, avoiding the need for hook implementations.
```python
import pytest_html
def test_with_extra_content(extras):
extras.append(pytest_html.extras.text("This test validates user login"))
extras.append(pytest_html.extras.url("https://docs.example.com/login"))
assert True
def test_with_screenshot_on_failure(extras, request):
try:
assert False, "Expected failure for demonstration"
except AssertionError:
extras.append(pytest_html.extras.png(screenshot_base64, name="Failure Screenshot"))
raise
```
--------------------------------
### Basic Usage: Generating HTML Reports
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Demonstrates how to generate HTML reports using the `--html` command-line option, including options for self-contained reports and custom CSS.
```APIDOC
## Basic Usage: Generating HTML Reports
### Description
Generate an HTML test report by running pytest with the `--html` option. You can also specify options for self-contained reports and custom CSS.
### Method
Command Line
### Endpoint
N/A
### Parameters
#### Command Line Options
- **--html** (string) - Required - Path to save the HTML report file.
- **--self-contained-html** (boolean) - Optional - Embeds all assets (CSS, JS) into the HTML file.
- **--css** (string) - Optional - Path to a custom CSS file to style the report. Can be specified multiple times.
### Request Example
```bash
# Generate a basic HTML report
pytest --html=report.html
# Generate a self-contained HTML report (all assets embedded)
pytest --html=report.html --self-contained-html
# Apply custom CSS styling
pytest --html=report.html --css=highcontrast.css --css=accessible.css
```
### Response
#### Success Response (200)
Generates an HTML file at the specified path containing the test report.
#### Response Example
N/A
```
--------------------------------
### Configure Report Metadata via conftest.py
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Demonstrates how to use pytest_configure and pytest_sessionfinish hooks to inject custom project metadata into the report.
```python
import pytest
from pytest_metadata.plugin import metadata_key
def pytest_configure(config):
config.stash[metadata_key]["Project"] = "My Application"
config.stash[metadata_key]["Build"] = "1.2.3"
config.stash[metadata_key]["Environment"] = "staging"
@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
session.config.stash[metadata_key]["Total Duration"] = "5 minutes"
session.config.stash[metadata_key]["Exit Status"] = str(exitstatus)
```
--------------------------------
### Adding Extra Content via Fixtures
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Shows how to use the 'extras' fixture to inject content directly into a test function without requiring a hook implementation.
```python
import pytest_html
def test_extra(extras):
extras.append(pytest_html.extras.text("some string"))
```
--------------------------------
### Configure Report Streaming with pyproject.toml or pytest.ini
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Enables report generation for each finished test instead of waiting for the entire test run. This can be configured using either the pyproject.toml or pytest.ini file.
```toml
[tool.pytest.ini_options]
generate_report_on_test = true
```
```ini
[pytest]
generate_report_on_test = True
```
--------------------------------
### Attach Video Content
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Shows how to attach video files like MP4 or WebM to test reports for visual debugging purposes.
```python
import pytest
import pytest_html
import base64
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call" and report.failed:
with open("test_recording.mp4", "rb") as f:
video_data = base64.b64encode(f.read()).decode("utf-8")
extras.append(pytest_html.extras.mp4(video_data, name="Test Recording"))
extras.append(pytest_html.extras.video(webm_data, name="Recording", mime_type="video/webm", extension="webm"))
report.extras = extras
```
--------------------------------
### Generate Basic HTML Report with pytest-html
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Command-line options to generate HTML reports using pytest-html. Includes options for basic reports, self-contained reports, and applying custom CSS.
```bash
pytest --html=report.html
pytest --html=report.html --self-contained-html
pytest --html=report.html --css=highcontrast.css --css=accessible.css
```
--------------------------------
### Attach Images to Reports
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Demonstrates how to attach images in various formats (PNG, JPG, SVG) to test reports. Supports loading from file paths, URLs, or base64-encoded strings.
```python
import pytest
import pytest_html
import base64
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call":
extras.append(pytest_html.extras.image("/path/to/screenshot.png"))
extras.append(pytest_html.extras.image("https://example.com/image.png"))
with open("screenshot.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
extras.append(pytest_html.extras.png(image_data, name="Screenshot"))
extras.append(pytest_html.extras.jpg(jpeg_base64_data, name="Photo"))
extras.append(pytest_html.extras.svg(svg_content, name="Diagram"))
extras.append(pytest_html.extras.image(gif_data, name="Animation", mime_type="image/gif", extension="gif"))
report.extras = extras
```
--------------------------------
### Apply Custom CSS to Report Appearance
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Allows customization of the report's appearance by applying custom CSS files. Multiple CSS files can be specified and are applied in the order they are listed.
```bash
pytest --html=report.html --css=highcontrast.css --css=accessible.css
```
--------------------------------
### Tag and Push Release
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Tags a new release version locally and pushes the tag to the upstream repository. This is a crucial step in the release process.
```bash
git tag
```
```bash
git push upstream --tags
```
--------------------------------
### Run Python Tests with Tox
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/development.md
Executes Python tests across various versions using Tox. This can be done directly with Tox or managed via Hatch.
```bash
$ hatch -e test run tox
```
```bash
$ pip install tox
$ tox
```
--------------------------------
### Migrate py.xml HTML generation to string-based HTML
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/deprecations.md
Demonstrates how to replace the deprecated py.xml dependency with raw HTML strings in pytest_html_results_table_header hooks. This ensures compatibility after the removal of the py module dependency.
```python
import pytest
from py.xml import html
def pytest_html_results_table_header(cells):
cells.insert(2, html.th("Description"))
cells.insert(1, html.th("Time", class_="sortable time", data_column_type="time"))
```
```python
import pytest
def pytest_html_results_table_header(cells):
cells.insert(2, "Description | ")
cells.insert(1, 'Time | ')
```
```python
import pytest
from py.xml import html
def pytest_html_results_table_header(cells):
cells.insert(2, str(html.th("Description")))
cells.insert(
1, str(html.th("Time", class_="sortable time", data_column_type="time"))
)
```
--------------------------------
### Create Self-Contained HTML Report
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Generates a single HTML file for the report, including all necessary assets like CSS and images. This is useful for sharing results and respects Content Security Policy (CSP) by default, but external images might not render.
```bash
pytest --html=report.html --self-contained-html
```
--------------------------------
### Configure Redaction and Display Options in pytest.ini
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Shows how to define sensitive environment variables for redaction and set default report display behaviors like collapsed sections and sorting.
```ini
[pytest]
environment_table_redact_list = ^password$
.*secret.*
.*api_key.*
^AWS_.*
render_collapsed = passed,skipped
initial_sort = duration
```
--------------------------------
### Data and Metadata API
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Functions to attach structured JSON data, plain text, and URLs to test reports.
```APIDOC
## extras.json() / extras.text() / extras.url()
### Description
Attaches structured JSON, plain text logs, or clickable URLs to the test report.
### Parameters
- **content** (string) - Required - The data, text, or URL string.
- **name** (string) - Optional - Display name for the attachment.
### Request Example
extras.append(pytest_html.extras.json(json.dumps(data), name="API Response"))
extras.append(pytest_html.extras.url("https://example.com", name="Docs"))
```
--------------------------------
### Report Streaming Configuration
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Configure pytest-html to generate the report incrementally as tests complete using `generate_report_on_test` setting.
```APIDOC
## Report Streaming Configuration
### Description
Enable report streaming to generate the report incrementally as each test finishes, rather than waiting for the full run to complete. This is configured via `generate_report_on_test`.
### Method
Configuration File
### Endpoint
N/A
### Parameters
#### Configuration Options
- **generate_report_on_test** (boolean) - Required - If set to `true`, the report will be generated incrementally.
### Request Example
```toml
# pyproject.toml
[tool.pytest.ini_options]
generate_report_on_test = true
```
```ini
# pytest.ini
[pytest]
generate_report_on_test = True
```
### Response
#### Success Response (200)
Report generation is configured for streaming.
#### Response Example
N/A
```
--------------------------------
### Add Raw HTML Content with extras.html() Function
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Python code demonstrating how to use `pytest_html.extras.html()` within the `pytest_runtest_makereport` hook to add raw HTML content to test results, particularly for failed tests.
```python
import pytest
import pytest_html
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call" and report.failed:
extras.append(pytest_html.extras.html("Additional debugging information here
"))
report.extras = extras
```
--------------------------------
### Video Attachment API
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Functions to attach video files (MP4, WebM) to test reports for visual debugging.
```APIDOC
## extras.video() / extras.mp4()
### Description
Attaches video files to the report. Useful for debugging failed tests by providing a visual recording.
### Parameters
- **content** (string) - Required - Base64-encoded video data.
- **name** (string) - Optional - Display name for the video.
- **mime_type** (string) - Optional - Custom MIME type (e.g., video/webm).
### Request Example
extras.append(pytest_html.extras.mp4(video_base64, name="Test Recording"))
```
--------------------------------
### Filtering Report Results
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Demonstrates how to remove specific rows from the results table or replace log content using hooks.
```python
def pytest_html_results_table_row(report, cells):
if report.passed:
del cells[:]
def pytest_html_results_table_html(report, data):
if report.passed:
del data[:]
data.append("No log output captured.
")
```
--------------------------------
### extras.html() Function
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Add raw HTML content to a specific test report entry using the `pytest_html.extras.html()` function.
```APIDOC
## extras.html() Function
### Description
Add raw HTML content to a test report. This is typically done within the `pytest_runtest_makereport` hook to attach extra information to test results, especially failures.
### Method
Python Function within Hook
### Endpoint
N/A
### Parameters
#### Function Parameters
- **html_content** (string) - Required - The raw HTML string to add to the report.
### Request Example
```python
import pytest
import pytest_html
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call" and report.failed:
extras.append(pytest_html.extras.html("Additional debugging information here
"))
report.extras = extras
```
### Response
#### Success Response (200)
Raw HTML content is added to the 'extras' section of the relevant test report entries.
#### Response Example
N/A
```
--------------------------------
### Adding Extra Content to Reports via Hooks
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Demonstrates how to use the pytest_runtest_makereport hook to append custom HTML or URLs to a test report based on test outcomes.
```python
import pytest
import pytest_html
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call":
extras.append(pytest_html.extras.url("http://www.example.com/"))
xfail = hasattr(report, "wasxfail")
if (report.skipped and xfail) or (report.failed and not xfail):
extras.append(pytest_html.extras.html("Additional HTML
"))
report.extras = extras
```
--------------------------------
### Modify Environment Section Before Tests with pytest_configure
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Uses the pytest_configure hook to modify the 'Environment' section of the report before tests begin. This requires the pytest-metadata plugin and uses a stash to store metadata.
```python
from pytest_metadata.plugin import metadata_key
def pytest_configure(config):
config.stash[metadata_key]["foo"] = "bar"
```
--------------------------------
### Image Attachment API
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Functions to attach images (PNG, JPG, SVG) to test reports using file paths, URLs, or base64 data.
```APIDOC
## extras.image() / extras.png() / extras.jpg() / extras.svg()
### Description
Attaches image content to the test report. Supports local file paths, remote URLs, or base64-encoded binary data.
### Parameters
- **content** (string) - Required - The file path, URL, or base64 string.
- **name** (string) - Optional - Display name for the image in the report.
- **mime_type** (string) - Optional - Custom MIME type.
- **extension** (string) - Optional - File extension for the attachment.
### Request Example
extras.append(pytest_html.extras.png(base64_data, name="Screenshot"))
```
--------------------------------
### Configure Collapsed Rows via pytest.ini
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Sets the default collapsed state for test rows in the generated HTML report using the configuration file. The query parameter 'collapsed' will take precedence over this setting.
```ini
[pytest]
render_collapsed = failed,error
```
--------------------------------
### Modify Environment Section After Tests with pytest_sessionfinish
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Uses the pytest_sessionfinish hook to modify the 'Environment' section of the report after all tests have completed. The tryfirst=True decorator is crucial for ensuring this hook runs before other plugins'.
```python
import pytest
from pytest_metadata.plugin import metadata_key
@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
session.config.stash[metadata_key]["foo"] = "bar"
```
--------------------------------
### Hook: pytest_html_results_summary
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Add custom content to the summary section of the HTML report using the `pytest_html_results_summary` hook.
```APIDOC
## Hook: pytest_html_results_summary
### Description
Add custom content to the summary section of the report by implementing this hook. You can extend the `prefix`, `summary`, or `postfix` lists with HTML strings.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **prefix** (list) - A list of strings to prepend to the summary section.
- **summary** (list) - A list of strings representing the main summary content.
- **postfix** (list) - A list of strings to append to the summary section.
- **session** (object) - The pytest session object.
### Request Example
```python
# conftest.py
def pytest_html_results_summary(prefix, summary, postfix, session):
"""Called before adding the summary section to the report"""
prefix.extend(["Build: #12345
"])
prefix.extend(["Environment: Production
"])
postfix.extend(["Report generated by CI/CD pipeline
"])
```
### Response
#### Success Response (200)
Custom content is added to the summary section of the HTML report.
#### Response Example
N/A
```
--------------------------------
### Hook: pytest_html_duration_format
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Customize the formatting of test duration values in the HTML report using the `pytest_html_duration_format` hook.
```APIDOC
## Hook: pytest_html_duration_format
### Description
Customize the formatting of test duration values in the report. This hook receives the duration in seconds and should return a formatted string.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **duration** (float) - Required - The test duration in seconds.
### Request Example
```python
# conftest.py
import datetime
def pytest_html_duration_format(duration):
"""Called before using the default duration formatting."""
duration_timedelta = datetime.timedelta(seconds=duration)
time = datetime.datetime(1, 1, 1) + duration_timedelta
return time.strftime("%H:%M:%S")
```
### Response
#### Success Response (200)
Test duration values in the report are formatted as HH:MM:SS.
#### Response Example
N/A
```
--------------------------------
### Add Custom Content to Summary with pytest_html_results_summary Hook
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Python code for the `pytest_html_results_summary` hook in `conftest.py` to add custom HTML content to the report's summary section.
```python
# conftest.py
def pytest_html_results_summary(prefix, summary, postfix, session):
"""Called before adding the summary section to the report"""
prefix.extend(["Build: #12345
"])
prefix.extend(["Environment: Production
"])
postfix.extend(["Report generated by CI/CD pipeline
"])
```
--------------------------------
### Hook: pytest_html_results_table_row
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Customize each row in the results table, add cell data, or filter out rows using the `pytest_html_results_table_row` hook.
```APIDOC
## Hook: pytest_html_results_table_row
### Description
Customize each row in the results table, add cell data, or filter out rows entirely. The `cells` parameter is a list of HTML `` elements for the current row.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **report** (object) - Required - The report object for the current test result.
- **description** (string) - The description of the test, often derived from its docstring.
- **cells** (list) - A list of HTML strings representing the table data cells (` | `) for the current row.
### Request Example
```python
# conftest.py
import pytest
from datetime import datetime
def pytest_html_results_table_row(report, cells):
"""Called after building results table row."""
cells.insert(2, f" | {report.description} | ")
cells.insert(1, f'{datetime.utcnow()} | ')
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__) if item.function.__doc__ else ""
# Remove all passed results from the report
def pytest_html_results_table_row_filter(report, cells):
if report.passed:
del cells[:]
```
### Response
#### Success Response (200)
Each row in the results table is customized with additional data or filtered.
#### Response Example
N/A
```
--------------------------------
### Customize Results Table Rows with pytest_html_results_table_row Hook
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Python code for the `pytest_html_results_table_row` and `pytest_runtest_makereport` hooks to customize individual rows in the results table, including adding cell data and filtering rows.
```python
# conftest.py
import pytest
from datetime import datetime
def pytest_html_results_table_row(report, cells):
"""Called after building results table row."""
cells.insert(2, f"{report.description} | ")
cells.insert(1, f'{datetime.utcnow()} | ')
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__) if item.function.__doc__ else ""
# Remove all passed results from the report
def pytest_html_results_table_row_filter(report, cells):
if report.passed:
del cells[:]
```
--------------------------------
### pytest-html Hook API
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/api_reference.md
A collection of hook functions provided by pytest-html to customize the HTML report output during test execution.
```APIDOC
## Hooks API
### pytest_html_duration_format(duration)
- **Description**: Called before using the default duration formatting.
- **Parameters**: duration (float) - The duration value to be formatted.
### pytest_html_report_title(report)
- **Description**: Called before adding the title to the report.
- **Parameters**: report (object) - The report object being generated.
### pytest_html_results_summary(prefix, summary, postfix, session)
- **Description**: Called before adding the summary section to the report.
- **Parameters**: prefix, summary, postfix, session - Components of the summary section.
### pytest_html_results_table_header(cells)
- **Description**: Called after building results table header.
- **Parameters**: cells (list) - The list of header cells.
### pytest_html_results_table_html(report, data)
- **Description**: Called after building results table additional HTML.
- **Parameters**: report (object), data (list) - The report and associated HTML data.
### pytest_html_results_table_row(report, cells)
- **Description**: Called after building results table row.
- **Parameters**: report (object), cells (list) - The report and the row cells.
```
--------------------------------
### Customize Duration Format via Hook
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Uses the pytest_html_duration_format hook in conftest.py to define a custom string format for test durations. This overrides the default millisecond or hh:mm:ss formatting.
```python
import datetime
def pytest_html_duration_format(duration):
duration_timedelta = datetime.timedelta(seconds=duration)
time = datetime.datetime(1, 1, 1) + duration_timedelta
return time.strftime("%H:%M:%S")
```
--------------------------------
### Add Custom Content to Summary Section
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Allows adding custom HTML content to the 'Summary' section of the report using the pytest_html_results_summary hook. This hook can prepend or append information to the summary.
```python
def pytest_html_results_summary(prefix, summary, postfix):
prefix.extend(["foo: bar
"])
```
--------------------------------
### Hook: pytest_html_results_table_html
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Modify the additional HTML content and log output displayed for each test result using the `pytest_html_results_table_html` hook.
```APIDOC
## Hook: pytest_html_results_table_html
### Description
Modify the additional HTML content and log output displayed for each test result. The `data` parameter is a list of HTML strings.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **report** (object) - Required - The report object for the current test result.
- **data** (list) - A list of HTML strings representing the additional content for the test result.
### Request Example
```python
# conftest.py
def pytest_html_results_table_html(report, data):
"""Called after building results table additional HTML."""
if report.passed:
del data[:]
data.append("No log output captured.
")
```
### Response
#### Success Response (200)
The additional HTML content for test results is modified.
#### Response Example
N/A
```
--------------------------------
### Hook: pytest_html_report_title
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Customize the title of the generated HTML report by implementing the `pytest_html_report_title` hook.
```APIDOC
## Hook: pytest_html_report_title
### Description
Customize the HTML report title by implementing this hook in your conftest.py file. This hook is called before the title is added to the report.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **report** (object) - Required - The report object to which the title will be set.
- **title** (string) - The desired title for the HTML report.
### Request Example
```python
# conftest.py
def pytest_html_report_title(report):
"""Called before adding the title to the report"""
report.title = "My Custom Test Report"
```
### Response
#### Success Response (200)
The HTML report title is customized.
#### Response Example
N/A
```
--------------------------------
### Attach JSON Data
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Attaches structured JSON data to reports, useful for debugging API responses or complex test state.
```python
import pytest
import pytest_html
import json
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call":
api_response = {"status": "success", "data": {"user_id": 123, "name": "Test User"}}
extras.append(pytest_html.extras.json(json.dumps(api_response), name="API Response"))
report.extras = extras
```
--------------------------------
### Redact Environment Variables in Report
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Configures the redaction of sensitive environment variables from the report's 'Environment' section using regular expressions in the pytest.ini file. Redacted variables show their names but grayed-out values.
```ini
[pytest]
environment_table_redact_list = ^foo$
.*redact.*
bar
```
--------------------------------
### Modify HTML Content and Log Output with pytest_html_results_table_html Hook
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Python code for the `pytest_html_results_table_html` hook in `conftest.py` to modify the additional HTML content and log output displayed for each test result.
```python
# conftest.py
def pytest_html_results_table_html(report, data):
"""Called after building results table additional HTML."""
if report.passed:
del data[:]
data.append("No log output captured.
")
```
--------------------------------
### Customize Report Title with pytest_html_report_title Hook
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Provides a Python hook to programmatically set a custom title for the HTML report. The default title is the report's filename.
```python
def pytest_html_report_title(report):
report.title = "My very own title!"
```
--------------------------------
### Modifying Report Table Columns
Source: https://github.com/pytest-dev/pytest-html/blob/master/docs/user_guide.md
Uses pytest_html_results_table_header and pytest_html_results_table_row hooks to add custom columns like descriptions and timestamps to the report table.
```python
import pytest
from datetime import datetime
def pytest_html_results_table_header(cells):
cells.insert(2, "Description | ")
cells.insert(1, 'Time | ')
def pytest_html_results_table_row(report, cells):
cells.insert(2, f"{report.description} | ")
cells.insert(1, f'{datetime.utcnow()} | ')
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__)
```
--------------------------------
### Modify Results Table Header with pytest_html_results_table_header Hook
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Python code for the `pytest_html_results_table_header` hook in `conftest.py` to modify the results table header, such as adding or reordering columns.
```python
# conftest.py
def pytest_html_results_table_header(cells):
"""Called after building results table header."""
cells.insert(2, "Description | ")
cells.insert(1, 'Time | ')
```
--------------------------------
### Hook: pytest_html_results_table_header
Source: https://context7.com/pytest-dev/pytest-html/llms.txt
Modify the results table header in the HTML report by implementing the `pytest_html_results_table_header` hook.
```APIDOC
## Hook: pytest_html_results_table_header
### Description
Modify the results table header to add, remove, or reorder columns. The `cells` parameter is a list of HTML `` elements.
### Method
Python Hook
### Endpoint
N/A
### Parameters
#### Hook Parameters
- **cells** (list) - A list of HTML strings representing the table header cells (` | `).
### Request Example
```python
# conftest.py
def pytest_html_results_table_header(cells):
"""Called after building results table header."""
cells.insert(2, " | Description | ")
cells.insert(1, 'Time | ')
```
### Response
#### Success Response (200)
The results table header is modified with custom columns.
#### Response Example
N/A
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.