Metadata-Version: 2.4
Name: pytest-human
Version: 0.5.0
Summary: A beautiful nested HTML test report
Author-email: Dan Ilan <dan.ilan@q.ai>
Maintainer-email: Dan Ilan <dan.ilan@q.ai>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "{}"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright {yyyy} {name of copyright owner}
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
Project-URL: Repository, https://github.com/Q-cue-ai/pytest-human
Keywords: pytest,human,testing,html,report,log,logging,debug
Classifier: Framework :: Pytest
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pytest>=8.0.0
Requires-Dist: rich==14.*
Dynamic: license-file

# pytest-human

[![PyPI version](https://img.shields.io/pypi/v/pytest-human.svg)](https://pypi.org/project/pytest-human)
[![Python versions](https://img.shields.io/pypi/pyversions/pytest-human.svg)](https://pypi.org/project/pytest-human)
[![License](https://img.shields.io/pypi/l/pytest-human.svg)](https://github.com/Q-cue-ai/pytest-human/blob/main/LICENSE)

![logo](assets/logo-horizontal.svg)

A pytest plugin for generating beautiful, human-readable HTML reports for individual tests with collapsible nested logging spans and syntax highlighting. Inspired by Robot Framework and Playwright reports.

Unlike other pytest HTML report plugins, **pytest-human** creates a separate HTML log file for each test, aimed at helping you dive into specific parts of the test that are relevant for debugging.
Works with standard python logging, no need to rewrite existing tests to get going!


## Features
* Logs
  * Beautiful test logs
  * Collapsible spans
  * Syntax highlighting
  * Colored log levels
  * Support for existing native python logging
  * Streaming log writing
* Tracing
  * Automatic fixture logging
  * Automatic method call logging
  * Third-party method tracing
* Debugging
  * Deep error highlighting
  * Regex search in collapsed spans
  * Artifacts collection


## Demo 

https://github.com/user-attachments/assets/831b53ea-cf7f-468d-9303-335e444525e9

[Example Report](assets/test_pizza.html) and test [source file](tests/examples/test_pizza.py).

## Installation

Install from PyPI:

```bash
pip install pytest-human
```

## Quick Start

### Basic Usage

1. Enable the plugin when running pytest:

    ```bash
    pytest --enable-html-log --log-level DEBUG --html-output-dir output/
    ```

    Setting the log level is important as the pytest default is high (`WARNING`).

2. Use the `human` object and the `@traced` decorator in your tests:

    ```python
    from pytest_human.log import traced

    @traced()
    def insert_db(data):
        query = "INSERT INTO flowers (petals) VALUES ('{{1,2,3,4,5}}');"
        logging.info(f"executing {query=}")
        return len(data)

    def test_example(human):
        """This test demonstrates pytest-human logging."""
        human.log.info("Established test agent connection")

        with human.log.span.info("Generating sample data"):
            data = [1, 2, 3, 4, 5]
            human.log.info(f"Loaded sample data {data=} {len(data)=}", highlight=True)
            insert_db(data)

            with human.log.span.debug("Validating sample"):
                result = sum(data)
                human.log.debug(f"Sum {result=}", highlight=True)

        assert result == 15
    ```

3. Open the HTML test log

    At the end of individual tests you will see a similar line:

    ```console
    🌎 Test test_single_stage_ui HTML log at file:///tmp/pytest-of-john.doe/pytest-2/session_logs/test_frobulator.html
    ```

    You can <kbd>Ctrl</kbd>/<kbd>⌘</kbd>-Click the link in most terminals to open the file.

4. Debug!
    ![Screenshot](assets/test_example.png) 


## Command Line Options

### Enable HTML Logging


```bash
# To enable HTML logging support and use this plugin, pass this flag

pytest --enable-html-log
```

### Log Location

Control where HTML logs are saved:

```bash
# Save all test logs in a custom directory specified by the user.
pytest --html-output-dir /path/to/logs

# By default logs are saved in the session temp directory with the test name
# e.g. /tmp/pytest-of-user.name/pytest-446/session_logs/test_method_tracing.html
pytest --enable-html-log 

# Save in individual test temporary directories as test.html
# e.g. /tmp/pytest-of-user.name/pytest-446/session_logs/test_examplecurrent/test.html
pytest --enable-html-log --html-use-test-tmp
```

### Log Level

Control the minimum log level:

```bash
# Use pytest's global log level.
# Opt to use this setting.
pytest --enable-html-log --log-level DEBUG

# Set log level for HTML logs specifically.
# This requires the root logger to be properly configured.
pytest --enable-html-log --html-log-level INFO
```

`--html-log-level` controls the html logger directly but might still be restricted by the python root level. 
The root logger level can be tweaked programatically or using the `--log-level` parameter. `--html-log-level` default to `DEBUG` while in pytest the root log level defaults to `WARNING`.

For human features to work, ensure the root logger is set to `DEBUG` or `TRACE` using `--log-level`.

## Logger API

### Fixtures

- `human` - Supplies a human object to the test. Includes a logger and attachment collector.
- `test_log` - Supplies a logger to the test, equivalent to `human.log`.
- `human_test_log_path` - Path of the html log file for the current test
### Logging Methods

![Screenshot](assets/test_logging_methods.png)

```python
def test_logging_methods(human):
    # Basic logging at different levels
    human.log.trace("Trace level message")
    human.log.debug("Debug level message")
    human.log.info("Info level message")
    human.log.warning("Warning level message")
    human.log.error("Error level message")
    human.log.critical("Critical level message")
    
    # Syntax highlighting for code
    code = """
    import numpy as np

    def bark(volume: float) -> bool:
        return volume > 0.5:
    """
    human.log.info(code, highlight=True)
```

### Direct logger access

Get the test logger programmatically, this allows to tweak the source name and is useful if you don't want to pass the human object around.

```python
from pytest_human.log import get_logger

def test_programmatic_logger():
    logger = get_logger(__name__)
    logger.info("Custom logger")
```

### Collapsible Spans

Create nested, collapsible sections in your HTML logs.

This allows partitioning the log into sections and diving only into the parts of the logs that are relevant to your debug session.

![Screenshot](assets/test_spans.png)

```python
def test_spans(human):
    human.log.info("Starting complex operation")
    
    with human.log.span.info("Phase 1: Initialization"):
        human.log.debug("Initializing resources...")
        
        with human.log.span.debug("Loading configuration"):
            human.log.trace("Reading config file")
            config = load_config()
            human.log.debug(f"Config loaded: {config}")
        
        human.log.info("Initialization complete")
    
    with human.log.span.info("Phase 2: Processing"):
        human.log.debug("Processing data...")
        process_data()
    
    human.log.info("Operation completed")
```

## Method Tracing


A lot of debug logging is centered around logging a function when called, returned a value or threw an error. Human supplies the `@traced` decorator to allow for automatic method tracing in log. 

Each method call shows the function call parameters, opens a new span that includes all of the logging that happened in its scope, as well as its return value. This allows for easy segmentation of nested loggings and reduces the amount of noise encountered when debugging.


![Screenshot](assets/test_method_tracing.png)

```python
import logging
import time
from pytest_human.log import traced, get_logger

# Add the traced() decorator for automatic logging of method call/return
@traced()
def save_login(login):
    log = get_logger(__name__)
    log.info("a log inside save_login")
    return update_db(login)

@traced(log_level=logging.TRACE)
def update_db(login):
    log = get_logger(__name__)
    delay_time = 2
    log.info("delaying db update by 2 seconds")    
    time.sleep(delay_time)   
    return delay_time

def test_method_tracing(human):
    delay = save_login("hello")
    assert delay == 2
```

`@traced` supports the following parameters:
* `suppress_return` - do not log the return value, useful when it is overly long
* `suppress_params` - do not log the method parameters, useful when they are overly long
* `suppress_self` - do not show the `self` argument logging function parameters, default `True`
* `log_level` - set a log level for the method trace

Note: tracing will have some performance implications on method calls, also you should limit using `@traced` on frequently
called functions as to reduce log noise.

### Third-party method tracing

The `@traced` decorator is very useful for debugging but it is unfortunately restricted to code you own.

In order to log third-party methods, you can use the `trace_calls` and `trace_public_api` methods, which monkey patch third party code with human tracing.

`trace_calls` adds logging to a list of functions, while `trace_public_api` adds logging to all public methods of modules/classes.

```python
import pytest
from playwright.sync_api import Locator, LocatorAssertionsImpl, Page
from pytest_human.log import trace_calls, trace_public_api

@pytest.fixture(autouse=True)
def log_3rdparty_methods():
    with (
        trace_calls(
            pytest.Pytester.runpytest,
            pytest.Pytester.makepyfile,
        ),
        trace_calls(Page.screenshot, suppress_return=True),
        # this skips retracing Page.screenshot as it is already defined above
        trace_public_api(Page, Locator, LocatorAssertionsImpl),
    ):
        yield
```


## Artifacts

Sometimes you might have extra logs that are generated by subprocesses or used external resources such as Kubernetes, Docker or others.
Human automatically collects stdout/stderr and allows you to collect custom logs to be attached to the log.

![Screenshot](assets/test_artifacts.png)

```python
def test_artifacts(human):
    human.log.info("Attaching artifacts to the test log")

    print("logging something to stdout")

    log_content = """
    [10:00:01] First line of the log.
    [10:00:03] Line 2 of the log.
    [10:00:05] Line 3 of the log.
    """
    human.artifacts.add_log_text(log_content, "sample.log", description="Sample log file")
```

## Logging

### Using Standard Python Logging

pytest-human integrates with Python's standard logging system. All logs from any logger will be captured:

```python
import logging

def test_standard_logging(human):
    # pytest-human logger
    human.log.info("Using human fixture")
    
    # Standard Python logger - also captured in HTML
    logger = logging.getLogger(__name__)
    logger.info("Using standard logger")
```

### TRACE Logging

pytest-human adds a custom `TRACE` log level below `DEBUG` for more verbose logging:

```python
def test_trace_logging(human):
    human.log.trace("Very detailed trace information")
```

Run with trace level:

```bash
pytest --enable-html-log --log-level trace
```


### Keyboard navigation
You can use the keyboard to navigate around the log.
* Press <kbd>Tab</kbd> and <kbd>Shift</kbd>+<kbd>Tab</kbd> to jump between the expand buttons (+).
* Press <kbd>Enter</kbd> to expand and collapse a span when hovering over a button.
* Press <kbd>/</kbd> to jump to the search box and <kbd>Esc</kbd> to unfocus.
* When searching use <kbd>Enter</kbd> to jump to the next result and <kbd>Shift</kbd>+<kbd>Enter</kbd> to jump to the previous result.
## Development

### Running Tests

```bash
# Install development dependencies
pip install --group dev -e .

# Run tests
pytest

# Run with coverage
pytest --cov=pytest_human
```

Alternatively use tox

```bash
tox
```

### Building Documentation

```bash
mkdocs serve
```

Documentation is still TBD


## License

Distributed under the Apache Software License 2.0. See `LICENSE` for more information.


## Links

- **PyPI**: https://pypi.org/project/pytest-human
- **Repository**: https://github.com/Q-cue-ai/pytest-human
- **Issue Tracker**: https://github.com/Q-cue-ai/pytest-human/issues

