Metadata-Version: 2.5
Name: unittest-live-report
Version: 0.1.0
Summary: A unittest result that writes its HTML report while your tests are still running
Project-URL: Homepage, https://github.com/Vsoapmac/unittest-live-report
Project-URL: Repository, https://github.com/Vsoapmac/unittest-live-report
Project-URL: Issues, https://github.com/Vsoapmac/unittest-live-report/issues
Project-URL: Changelog, https://github.com/Vsoapmac/unittest-live-report/releases
Author-email: Vsoapmac <49892459+Vsoapmac@users.noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Keywords: html-report,live-report,test-automation,test-report,testing,unittest
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# unittest-live-report

A `unittest` result that writes its HTML report **while your tests run**, one card
per test case, straight into a single self-contained file.

Open the report in a browser and refresh: finished tests are already there. No
template directory to configure, no "wait for the whole suite to finish" step — and
if you hit `Ctrl+C` or the stop button in your IDE, everything that already ran is
still in the report.

```console
$ pip install unittest-live-report
```

```python
import unittest
from unittest_live_report import LiveReport

suite = unittest.TestLoader().loadTestsFromTestCase(TestDemo)
LiveReport(suite).report(filename="report", description="Regression", report_dir="reports")
```

There is no CLI and no runner to configure: `LiveReport` is both the driver and a
`unittest.TestResult`, so the call above runs the suite and writes the report.

## Why this exists

- **No template directory, no external runtime.** The stylesheet, page script and
  templates ship inside the package. `pip install` is the whole setup.
- **Written incrementally.** Each card is flushed the moment its test finishes, so a
  long run is readable while it is still going.
- **Interruption-safe.** A crashed editor, a killed process or `Ctrl+C` does not lose
  the cases that already finished.
- **One file.** Screenshots and attachments are inlined; the report can be mailed or
  archived and opened offline.
- **Machine-readable.** Every page embeds a run manifest and one JSON record per test
  case, and `read_report()` hands them back to Python.

## Quick start

```python
import unittest

from unittest_live_report import LiveReport, live_report


class TestDemo(unittest.TestCase):
    """A small demo suite."""

    def test_add(self):
        """1 + 1 should be 2."""
        live_report.log("step 1:", "1 + 1")
        self.assertEqual(1 + 1, 2)

    def test_string(self):
        """String concatenation."""
        self.assertEqual("hello" + " " + "world", "hello world")

    @unittest.skip("demo skip")
    def test_skip(self):
        pass


if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestDemo)
    report = LiveReport(suite)
    path = report.report(
        filename="report",
        description="Demo run",
        report_dir="reports",
    )
    print(f"report: {path}")
    print(f"counts: {report.counts}")
    print(f"all passed: {report.wasSuccessful()}")
```

Run it, then open `reports/report.html` and refresh while it runs.

## What the report contains

- **One card per test case**, written when the case finishes, with start/end time,
  wall-clock duration, method name, and its docstring as the description.
- **Filtering and search** on the page, plus a donut chart of
  passed / failed / skipped, so a long run is scannable.
- **The failure traceback** in the card, so you do not have to scroll the terminal.
- **Logs, screenshots and attachments** written from inside a test, rendered per card.
- **A machine-readable record** per case, plus a run manifest with counts and timing.
- **Single-file output**: stylesheet, page script, images and attachments are inlined.

The page chrome is English (`Passed` / `Failed` / `Skipped`); the report content is
whatever you write into it.

## Live behavior

The report file exists before the first test runs: the head is written first, then
each card is appended and flushed as its case finishes. Refresh the browser to see
new cards — the page does not refresh itself, which keeps filter, search and expanded
cards from resetting under you.

| Interruption | What survives |
|---|---|
| `Ctrl+C` | Every finished card, plus the footer and a run manifest with `exitstatus: 2`. The case that was running is dropped. |
| IDE stop button / `SIGKILL` | Every finished card. No footer and no run manifest — `read_report()["manifest"]` is `None`, but `counts` and `cases` still work. |

No Python code runs on a hard kill, so nothing at exit time could save the content;
the guarantee comes from flushing one card at a time. A case that was still running is
never written half-done — it simply does not appear.

## Writing content from a test

```python
from unittest_live_report import live_report


class TestLogin(unittest.TestCase):
    def test_login(self):
        """Verify the login flow."""
        live_report.log("POST /login as admin")
        live_report.log("status", 200, live_report.span_html("OK", bold=True, code=True))

        live_report.case_name("Login flow")           # override the card title
        live_report.case_desc("Covers the redirect")  # override the docstring
        live_report.save_image("screenshots/home.png", caption="after login")
        live_report.attach("logs/server.log", caption="server log")

        self.assertTrue(True)
```

| Method | What it does |
|---|---|
| `live_report.log(*parts)` | Appends a log line to the current card. `*parts` are joined with spaces like `print`; newlines become separate lines; everything is HTML-escaped. |
| `live_report.span_html(text, *, bold=False, code=False)` | Renders an inline fragment (bold / monospace). Pass the result to `live_report.log()` to have it embedded as-is. The only entry point you may call outside a test case. |
| `live_report.case_name(text)` | Overrides the card title (default: the test method name). |
| `live_report.case_desc(text)` | Overrides the card description (default: the test method's docstring). |
| `live_report.save_image(path, caption=None)` | Inlines an image as a base64 data URI. Raises `FileNotFoundError` if the path is not an existing file. |
| `live_report.attach(path, caption=None)` | Inlines any file as a base64 data URI and puts a download link on the card, with name, size and MIME type. Raises `FileNotFoundError` if the path is not an existing file. |

Calling the other four outside a test case only emits a warning and drops the
content; it never fails your run. Apart from the two `FileNotFoundError` cases above,
the report system never raises into your tests: a broken report becomes a warning and
reporting is disabled for the rest of the run.

`print()` output is **not** captured — it stays in your terminal. Write what you want
in the card with `live_report.log()`.

## `report()` options

```python
path = LiveReport(suite).report(
    description="Regression",   # report title (default: "unittest report")
    filename="report",          # ".html" is appended when missing (default: "report.html")
    report_dir="reports",       # created if missing (default: current directory)
    log_path=None,              # alias of report_dir, kept for BeautifulReport users
)
```

`report()` returns the absolute `Path` of the report, or `None` when the file could
not be written (the suite still runs to completion in that case). A `LiveReport`
instance drives exactly one run; calling `report()` twice raises `RuntimeError`.

Because it is a normal `unittest.TestResult`, `report.counts`, `report.testsRun` and
`report.wasSuccessful()` behave as usual after the run. `report()` does not change
your process exit code; check `wasSuccessful()` if you need to.

## How statuses are counted

`unittest` has more outcomes than the three the report shows, so they are folded in:

| Report status | Comes from |
|---|---|
| `passed` | `addSuccess` |
| `failed` | `addFailure` **and** `addError` — a broken fixture or a failing teardown counts as a failed case; `addUnexpectedSuccess` and failing `subTest`s count too |
| `skipped` | `addSkip` **and** `addExpectedFailure` |

A class- or module-level fixture error (`setUpClass`, `setUpModule`, …) has no test
case object, so it gets a card of its own — otherwise a run would silently lose a
result. Counts always satisfy `total = passed + failed + skipped`.

## Reading the report from a script

```python
from unittest_live_report import read_report

report = read_report("report.html")

print(report["counts"])                   # {'total': 42, 'passed': 40, 'failed': 1, 'skipped': 1}
print(report["manifest"]["exitstatus"])

for case in report["cases"]:
    print(case["nodeid"], case["status"], case["duration"])
```

The returned dict has three keys:

- `manifest` — the run manifest, or `None` when the process was killed before the
  report could be finished. That is how a truncated report is told apart from one
  that ran to the end. `Ctrl+C` is not that case: the manifest is written with
  `exitstatus` `2`.
- `counts` — `total` / `passed` / `failed` / `skipped`, tallied from the cases on the
  page, so it is available even for a truncated report.
- `cases` — one dict per test case, in the order they appear in the file. Each record
  holds `status`, `duration`, `started` / `finished`, `error`, `traceback`,
  `skip_reason`, plus summaries of the `logs`, `shots` and `attachments` you wrote.

`read_report()` raises `FileNotFoundError` if the path does not exist, and
`ValueError` when the file is not a unittest-live-report report or a JSON block is
broken.

The manifest's `exitstatus` is synthesized by this package: `0` means every card
passed, `1` means at least one failed, `2` means the run was interrupted. It does not
change the exit code of your process.

Each case record uses the same shape and version (`v: 1`) as
[pytest-live-report](https://pypi.org/project/pytest-live-report/), so one script can
read both. Only **additive** changes happen within a version — read optional fields
defensively.

The same data is embedded as plain JSON blocks, so a regex is enough if you would
rather not depend on the package:

```python
import json
import re
from pathlib import Path

html = Path("report.html").read_text(encoding="utf-8")

manifest = json.loads(
    re.search(r'<script type="application/json" id="rpt-run">(.*?)</script>', html).group(1)
)
records = [
    json.loads(block)
    for block in re.findall(
        r'<script type="application/json" class="rpt-case-json">(.*?)</script>', html, re.S
    )
]
```

## Migrating from BeautifulReport

```python
# before
from BeautifulReport import BeautifulReport
BeautifulReport(suite).report(filename="report", description="Regression", report_dir="reports")

# after
from unittest_live_report import LiveReport
LiveReport(suite).report(filename="report", description="Regression", report_dir="reports")
```

`filename`, `description` and `report_dir` keep their names and meaning, and the
deprecated `log_path` is accepted as an alias. Unlike BeautifulReport:

- the report is written while the suite runs instead of at the end;
- there is no `theme` parameter (one built-in style);
- `print()` output is not captured — use `live_report.log()`;
- `report()` returns the report path.

## Development

```console
$ uv sync                                       # create/update .venv and install the package
$ .venv\Scripts\python -m unittest discover -s tests -t . -v   # 32 tests
$ uv build                                      # wheel + sdist in dist/
```

On POSIX, use `.venv/bin/python` instead. Tests write to temporary directories and
leave the working tree alone.

Layout:

```text
src/unittest_live_report/
├── _result.py      LiveReport: driver + unittest result callbacks
├── _report.py      live_report.log / case_name / case_desc / save_image / attach
├── _case.py        CaseData and the per-case JSON record (v1)
├── _reader.py      read_report()
├── _store.py       process-wide "current case" and counts
├── _writer.py      report file handle, flush per card
└── _render/        HTML card, page head/tail, CSS, JS, static templates
tests/              32 unittest tests, including hard-kill and Ctrl+C behaviour
```

## Limitations

- No CLI and no `python -m unittest` integration: `unittest` has no plugin mechanism,
  so a run has to go through `LiveReport`.
- One `LiveReport` per run; no concurrent reports in one process (the "current case"
  is process-wide).
- No auto-refresh; refresh the page to see new cards.
- No theme selection; one built-in style.
- `error` and `failure` share the `failed` badge; the error summary and traceback
  still show which one happened.

## Requirements

- Python 3.10+
- No runtime dependencies

## License and links

MIT licensed. Copyright (c) 2026 Vsoapmac.

- Source, issues and changelog: <https://github.com/Vsoapmac/unittest-live-report>
- Package on PyPI: <https://pypi.org/project/unittest-live-report/>
