junit-merge 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- junit_merge-0.1.0/.github/workflows/ci.yml +23 -0
- junit_merge-0.1.0/.github/workflows/release.yml +38 -0
- junit_merge-0.1.0/.gitignore +9 -0
- junit_merge-0.1.0/LICENSE +21 -0
- junit_merge-0.1.0/PKG-INFO +110 -0
- junit_merge-0.1.0/README.md +88 -0
- junit_merge-0.1.0/pyproject.toml +47 -0
- junit_merge-0.1.0/src/junit_merge/__init__.py +346 -0
- junit_merge-0.1.0/src/junit_merge/__main__.py +60 -0
- junit_merge-0.1.0/tests/test_junit_merge.py +364 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ${{ matrix.os }}
|
|
11
|
+
strategy:
|
|
12
|
+
fail-fast: false
|
|
13
|
+
matrix:
|
|
14
|
+
os: [ubuntu-latest, windows-latest, macos-latest]
|
|
15
|
+
python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
- uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: ${{ matrix.python }}
|
|
21
|
+
- run: python -m pip install -e ".[test]" ruff
|
|
22
|
+
- run: python -m ruff check .
|
|
23
|
+
- run: python -m pytest -q
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
name: release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ["v*"]
|
|
6
|
+
workflow_dispatch:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: actions/setup-python@v5
|
|
14
|
+
with:
|
|
15
|
+
python-version: "3.12"
|
|
16
|
+
- run: python -m pip install build twine
|
|
17
|
+
- run: python -m build
|
|
18
|
+
- run: python -m twine check dist/*
|
|
19
|
+
- uses: actions/upload-artifact@v4
|
|
20
|
+
with:
|
|
21
|
+
name: dist
|
|
22
|
+
path: dist/
|
|
23
|
+
|
|
24
|
+
publish:
|
|
25
|
+
needs: build
|
|
26
|
+
# Set the PYPI_READY repository variable once PyPI trusted publishing is
|
|
27
|
+
# configured for this project; until then the release only builds.
|
|
28
|
+
if: vars.PYPI_READY == 'true'
|
|
29
|
+
runs-on: ubuntu-latest
|
|
30
|
+
environment: pypi
|
|
31
|
+
permissions:
|
|
32
|
+
id-token: write
|
|
33
|
+
steps:
|
|
34
|
+
- uses: actions/download-artifact@v4
|
|
35
|
+
with:
|
|
36
|
+
name: dist
|
|
37
|
+
path: dist/
|
|
38
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sandesh Bagmare
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: junit-merge
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Merge JUnit XML reports from sharded or retried test runs, recomputing counts
|
|
5
|
+
Project-URL: Homepage, https://github.com/sandeshbagmare/junit-merge
|
|
6
|
+
Project-URL: Issues, https://github.com/sandeshbagmare/junit-merge/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/sandeshbagmare/junit-merge/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Sandesh Bagmare
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ci,junit,junitxml,merge,pytest,test-report
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# junit-merge
|
|
24
|
+
|
|
25
|
+
One JUnit XML file from many, with counts you can trust.
|
|
26
|
+
|
|
27
|
+
```console
|
|
28
|
+
python -m junit_merge check-reports/*.xml --out junit.xml
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from junit_merge import merge_files
|
|
33
|
+
|
|
34
|
+
report = merge_files(["shard-1.xml", "shard-2.xml"], "junit.xml")
|
|
35
|
+
print(report.tests, report.failures)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Sharded CI jobs, `pytest --junitxml` per matrix leg and retried flaky tests all leave
|
|
39
|
+
you with several reports when the dashboard wants one. Concatenating the XML is
|
|
40
|
+
invalid, and adding up each file's `tests` and `failures` attributes double counts
|
|
41
|
+
every test a shard re-ran.
|
|
42
|
+
|
|
43
|
+
This package parses the reports, rebuilds the merged document from the test cases
|
|
44
|
+
themselves, and recomputes every count, so the numbers always match the contents.
|
|
45
|
+
|
|
46
|
+
## Duplicate tests
|
|
47
|
+
|
|
48
|
+
A test that appears in more than one report (the usual result of a retry) is
|
|
49
|
+
resolved with `on_duplicate`:
|
|
50
|
+
|
|
51
|
+
| policy | behaviour |
|
|
52
|
+
| ------ | --------- |
|
|
53
|
+
| `keep-worst` (default) | keep the failure or error over the pass; a test that failed anywhere stays failed |
|
|
54
|
+
| `keep-first` | keep the first occurrence |
|
|
55
|
+
| `keep-last` | keep the last occurrence |
|
|
56
|
+
| `keep-both` | keep every occurrence |
|
|
57
|
+
| `fail` | raise, naming the test, instead of guessing |
|
|
58
|
+
|
|
59
|
+
Keeping the worst outcome is the safe default: a flaky retry cannot hide a real
|
|
60
|
+
failure from the report.
|
|
61
|
+
|
|
62
|
+
## Install
|
|
63
|
+
|
|
64
|
+
```console
|
|
65
|
+
pip install junit-merge
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## API
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from junit_merge import merge, merge_files, parse, parse_file, to_xml
|
|
72
|
+
|
|
73
|
+
report = parse_file("shard-1.xml") # Report
|
|
74
|
+
merged = merge([report, parse_file("shard-2.xml")], on_duplicate="keep-worst")
|
|
75
|
+
merged.tests, merged.failures, merged.errors, merged.skipped, merged.time
|
|
76
|
+
data = to_xml(merged) # bytes, valid <testsuites> document
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`parse` accepts `str`, `bytes`, a path is handled by `parse_file`, and a document
|
|
80
|
+
name-spaced by tools like Jenkins is understood. Invalid XML raises `ValueError` with
|
|
81
|
+
the reason, not a bare `ParseError`.
|
|
82
|
+
|
|
83
|
+
## What is preserved
|
|
84
|
+
|
|
85
|
+
- `classname`, `name`, `time`, `file`, `line`
|
|
86
|
+
- `<failure>`, `<error>` and `<skipped>` including `message` and the text body
|
|
87
|
+
- `<system-out>` and `<system-err>`
|
|
88
|
+
- suite `<properties>`, first value winning on a clash
|
|
89
|
+
|
|
90
|
+
Cases are sorted by class and name by default, so two runs of the same merge produce
|
|
91
|
+
identical bytes; pass `sort=False` to keep the input order.
|
|
92
|
+
|
|
93
|
+
## What is not
|
|
94
|
+
|
|
95
|
+
- It does not run tests, retry them or upload anything: it merges files.
|
|
96
|
+
- Attributes nobody sets from test cases (`timestamp`, `hostname`) are not invented.
|
|
97
|
+
- A report whose contents contradict each other is trusted on the cases, which is
|
|
98
|
+
the only part that can be verified.
|
|
99
|
+
|
|
100
|
+
## Development
|
|
101
|
+
|
|
102
|
+
```console
|
|
103
|
+
python -m venv .venv
|
|
104
|
+
.venv/bin/pip install -e ".[test]"
|
|
105
|
+
.venv/bin/pytest
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
MIT.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# junit-merge
|
|
2
|
+
|
|
3
|
+
One JUnit XML file from many, with counts you can trust.
|
|
4
|
+
|
|
5
|
+
```console
|
|
6
|
+
python -m junit_merge check-reports/*.xml --out junit.xml
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from junit_merge import merge_files
|
|
11
|
+
|
|
12
|
+
report = merge_files(["shard-1.xml", "shard-2.xml"], "junit.xml")
|
|
13
|
+
print(report.tests, report.failures)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Sharded CI jobs, `pytest --junitxml` per matrix leg and retried flaky tests all leave
|
|
17
|
+
you with several reports when the dashboard wants one. Concatenating the XML is
|
|
18
|
+
invalid, and adding up each file's `tests` and `failures` attributes double counts
|
|
19
|
+
every test a shard re-ran.
|
|
20
|
+
|
|
21
|
+
This package parses the reports, rebuilds the merged document from the test cases
|
|
22
|
+
themselves, and recomputes every count, so the numbers always match the contents.
|
|
23
|
+
|
|
24
|
+
## Duplicate tests
|
|
25
|
+
|
|
26
|
+
A test that appears in more than one report (the usual result of a retry) is
|
|
27
|
+
resolved with `on_duplicate`:
|
|
28
|
+
|
|
29
|
+
| policy | behaviour |
|
|
30
|
+
| ------ | --------- |
|
|
31
|
+
| `keep-worst` (default) | keep the failure or error over the pass; a test that failed anywhere stays failed |
|
|
32
|
+
| `keep-first` | keep the first occurrence |
|
|
33
|
+
| `keep-last` | keep the last occurrence |
|
|
34
|
+
| `keep-both` | keep every occurrence |
|
|
35
|
+
| `fail` | raise, naming the test, instead of guessing |
|
|
36
|
+
|
|
37
|
+
Keeping the worst outcome is the safe default: a flaky retry cannot hide a real
|
|
38
|
+
failure from the report.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```console
|
|
43
|
+
pip install junit-merge
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## API
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from junit_merge import merge, merge_files, parse, parse_file, to_xml
|
|
50
|
+
|
|
51
|
+
report = parse_file("shard-1.xml") # Report
|
|
52
|
+
merged = merge([report, parse_file("shard-2.xml")], on_duplicate="keep-worst")
|
|
53
|
+
merged.tests, merged.failures, merged.errors, merged.skipped, merged.time
|
|
54
|
+
data = to_xml(merged) # bytes, valid <testsuites> document
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`parse` accepts `str`, `bytes`, a path is handled by `parse_file`, and a document
|
|
58
|
+
name-spaced by tools like Jenkins is understood. Invalid XML raises `ValueError` with
|
|
59
|
+
the reason, not a bare `ParseError`.
|
|
60
|
+
|
|
61
|
+
## What is preserved
|
|
62
|
+
|
|
63
|
+
- `classname`, `name`, `time`, `file`, `line`
|
|
64
|
+
- `<failure>`, `<error>` and `<skipped>` including `message` and the text body
|
|
65
|
+
- `<system-out>` and `<system-err>`
|
|
66
|
+
- suite `<properties>`, first value winning on a clash
|
|
67
|
+
|
|
68
|
+
Cases are sorted by class and name by default, so two runs of the same merge produce
|
|
69
|
+
identical bytes; pass `sort=False` to keep the input order.
|
|
70
|
+
|
|
71
|
+
## What is not
|
|
72
|
+
|
|
73
|
+
- It does not run tests, retry them or upload anything: it merges files.
|
|
74
|
+
- Attributes nobody sets from test cases (`timestamp`, `hostname`) are not invented.
|
|
75
|
+
- A report whose contents contradict each other is trusted on the cases, which is
|
|
76
|
+
the only part that can be verified.
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```console
|
|
81
|
+
python -m venv .venv
|
|
82
|
+
.venv/bin/pip install -e ".[test]"
|
|
83
|
+
.venv/bin/pytest
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "junit-merge"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Merge JUnit XML reports from sharded or retried test runs, recomputing counts"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Sandesh Bagmare" }]
|
|
13
|
+
keywords = ["junit", "junitxml", "ci", "pytest", "merge", "test-report"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = []
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/sandeshbagmare/junit-merge"
|
|
26
|
+
Issues = "https://github.com/sandeshbagmare/junit-merge/issues"
|
|
27
|
+
Changelog = "https://github.com/sandeshbagmare/junit-merge/blob/main/CHANGELOG.md"
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
junit-merge = "junit_merge.__main__:main"
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
test = ["pytest>=8"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/junit_merge"]
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
testpaths = ["tests"]
|
|
40
|
+
addopts = "-q"
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
line-length = 100
|
|
44
|
+
target-version = "py39"
|
|
45
|
+
|
|
46
|
+
[tool.ruff.lint]
|
|
47
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""Merge JUnit XML reports from sharded or retried test runs into one report.
|
|
2
|
+
|
|
3
|
+
A CI pipeline that splits tests across jobs, or retries flaky ones, ends up with
|
|
4
|
+
several JUnit XML files when the reporter wants exactly one. Concatenating them
|
|
5
|
+
double counts, and adding up the ``tests``/``failures`` attributes of each file is
|
|
6
|
+
wrong as soon as a shard re-ran a test.
|
|
7
|
+
|
|
8
|
+
>>> from junit_merge import merge, parse
|
|
9
|
+
>>> one = parse('<testsuite name="s"><testcase classname="t" name="a"/></testsuite>')
|
|
10
|
+
>>> two = parse('<testsuite name="s"><testcase classname="t" name="b"/></testsuite>')
|
|
11
|
+
>>> merge([one, two]).tests
|
|
12
|
+
2
|
|
13
|
+
|
|
14
|
+
The merged report is rebuilt from the test cases, so its counts always match what it
|
|
15
|
+
contains. Duplicate cases, which are what a retry produces, are resolved by keeping
|
|
16
|
+
the worst outcome by default: a test that failed in one shard and passed in another
|
|
17
|
+
is reported as a failure rather than quietly disappearing.
|
|
18
|
+
|
|
19
|
+
Standard library only, Python 3.9+.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import xml.etree.ElementTree as ET
|
|
26
|
+
from collections.abc import Iterable, Sequence
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Case",
|
|
32
|
+
"DuplicatePolicy",
|
|
33
|
+
"MergedReport",
|
|
34
|
+
"Report",
|
|
35
|
+
"case_key",
|
|
36
|
+
"merge",
|
|
37
|
+
"merge_files",
|
|
38
|
+
"parse",
|
|
39
|
+
"parse_file",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
#: Worst last, so ``max`` over these ranks picks the outcome that matters most.
|
|
45
|
+
SEVERITY = {"passed": 0, "skipped": 1, "failure": 2, "error": 3}
|
|
46
|
+
|
|
47
|
+
POLICIES = ("keep-worst", "keep-first", "keep-last", "keep-both", "fail")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Case:
|
|
52
|
+
"""One ``<testcase>``."""
|
|
53
|
+
|
|
54
|
+
name: str
|
|
55
|
+
classname: str = ""
|
|
56
|
+
time: float = 0.0
|
|
57
|
+
status: str = "passed"
|
|
58
|
+
message: str = ""
|
|
59
|
+
detail: str = ""
|
|
60
|
+
file: str = ""
|
|
61
|
+
line: int | None = None
|
|
62
|
+
system_out: str = ""
|
|
63
|
+
system_err: str = ""
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def key(self) -> tuple[str, str]:
|
|
67
|
+
return case_key(self)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def node_id(self) -> str:
|
|
71
|
+
return f"{self.classname}::{self.name}" if self.classname else self.name
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def case_key(case: Case) -> tuple[str, str]:
|
|
75
|
+
"""The identity of a test across shards: its class and its name."""
|
|
76
|
+
return (case.classname, case.name)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Report:
|
|
81
|
+
"""A parsed report: test cases plus the properties of the run."""
|
|
82
|
+
|
|
83
|
+
cases: list[Case] = field(default_factory=list)
|
|
84
|
+
properties: dict[str, str] = field(default_factory=dict)
|
|
85
|
+
suite_name: str = "pytest"
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def tests(self) -> int:
|
|
89
|
+
return len(self.cases)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def failures(self) -> int:
|
|
93
|
+
return sum(1 for c in self.cases if c.status == "failure")
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def errors(self) -> int:
|
|
97
|
+
return sum(1 for c in self.cases if c.status == "error")
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def skipped(self) -> int:
|
|
101
|
+
return sum(1 for c in self.cases if c.status == "skipped")
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def time(self) -> float:
|
|
105
|
+
return round(sum(c.time for c in self.cases), 6)
|
|
106
|
+
|
|
107
|
+
def to_xml(self, *, name: str | None = None) -> bytes:
|
|
108
|
+
"""Serialise this report as a JUnit ``<testsuites>`` document."""
|
|
109
|
+
return to_xml(self, name=name)
|
|
110
|
+
|
|
111
|
+
def counts(self) -> dict[str, int]:
|
|
112
|
+
return {
|
|
113
|
+
"tests": self.tests,
|
|
114
|
+
"failures": self.failures,
|
|
115
|
+
"errors": self.errors,
|
|
116
|
+
"skipped": self.skipped,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
MergedReport = Report
|
|
121
|
+
DuplicatePolicy = str
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _text(element: ET.Element | None) -> str:
|
|
125
|
+
if element is None or element.text is None:
|
|
126
|
+
return ""
|
|
127
|
+
return element.text
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _float(value: str | None, default: float = 0.0) -> float:
|
|
131
|
+
try:
|
|
132
|
+
return float(value) if value else default
|
|
133
|
+
except (TypeError, ValueError):
|
|
134
|
+
return default
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _case_from(element: ET.Element) -> Case:
|
|
138
|
+
status, message, detail = "passed", "", ""
|
|
139
|
+
for child in element:
|
|
140
|
+
tag = child.tag.rsplit("}", 1)[-1]
|
|
141
|
+
if tag in ("failure", "error"):
|
|
142
|
+
status = tag
|
|
143
|
+
message = child.get("message", "")
|
|
144
|
+
detail = _text(child)
|
|
145
|
+
break
|
|
146
|
+
if tag == "skipped":
|
|
147
|
+
status = "skipped"
|
|
148
|
+
message = child.get("message", "")
|
|
149
|
+
detail = _text(child)
|
|
150
|
+
break
|
|
151
|
+
system_out = ""
|
|
152
|
+
system_err = ""
|
|
153
|
+
for child in element:
|
|
154
|
+
tag = child.tag.rsplit("}", 1)[-1]
|
|
155
|
+
if tag == "system-out":
|
|
156
|
+
system_out = _text(child)
|
|
157
|
+
elif tag == "system-err":
|
|
158
|
+
system_err = _text(child)
|
|
159
|
+
line = element.get("line")
|
|
160
|
+
return Case(
|
|
161
|
+
name=element.get("name", ""),
|
|
162
|
+
classname=element.get("classname", ""),
|
|
163
|
+
time=_float(element.get("time")),
|
|
164
|
+
status=status,
|
|
165
|
+
message=message,
|
|
166
|
+
detail=detail,
|
|
167
|
+
file=element.get("file", ""),
|
|
168
|
+
line=int(line) if line and line.isdigit() else None,
|
|
169
|
+
system_out=system_out,
|
|
170
|
+
system_err=system_err,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _walk_suites(root: ET.Element) -> Iterable[ET.Element]:
|
|
175
|
+
tag = root.tag.rsplit("}", 1)[-1]
|
|
176
|
+
if tag == "testsuite":
|
|
177
|
+
yield root
|
|
178
|
+
return
|
|
179
|
+
if tag == "testsuites":
|
|
180
|
+
for suite in root:
|
|
181
|
+
if suite.tag.rsplit("}", 1)[-1] == "testsuite":
|
|
182
|
+
yield from _walk_suites(suite)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def parse(source: str | bytes | ET.Element) -> Report:
|
|
186
|
+
"""Parse a JUnit XML document (text, bytes or an element) into a :class:`Report`."""
|
|
187
|
+
if isinstance(source, ET.Element):
|
|
188
|
+
root = source
|
|
189
|
+
else:
|
|
190
|
+
try:
|
|
191
|
+
root = ET.fromstring(source)
|
|
192
|
+
except ET.ParseError as exc:
|
|
193
|
+
raise ValueError(f"not valid JUnit XML: {exc}") from None
|
|
194
|
+
if root.tag.rsplit("}", 1)[-1] not in ("testsuite", "testsuites"):
|
|
195
|
+
raise ValueError(f"not a JUnit report: root element is <{root.tag}>")
|
|
196
|
+
|
|
197
|
+
cases: list[Case] = []
|
|
198
|
+
properties: dict[str, str] = {}
|
|
199
|
+
suite_name = ""
|
|
200
|
+
for suite in _walk_suites(root):
|
|
201
|
+
if not suite_name:
|
|
202
|
+
suite_name = suite.get("name", "")
|
|
203
|
+
for props in suite:
|
|
204
|
+
if props.tag.rsplit("}", 1)[-1] != "properties":
|
|
205
|
+
continue
|
|
206
|
+
for entry in props:
|
|
207
|
+
key = entry.get("name", "")
|
|
208
|
+
if key and key not in properties:
|
|
209
|
+
properties[key] = entry.get("value", "")
|
|
210
|
+
for child in suite:
|
|
211
|
+
if child.tag.rsplit("}", 1)[-1] == "testcase":
|
|
212
|
+
cases.append(_case_from(child))
|
|
213
|
+
return Report(cases=cases, properties=properties, suite_name=suite_name or "pytest")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def parse_file(path: str | os.PathLike[str]) -> Report:
|
|
217
|
+
"""Parse a JUnit XML file into a :class:`Report`."""
|
|
218
|
+
return parse(Path(path).read_bytes())
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _resolve(duplicates: list[Case], policy: DuplicatePolicy) -> list[Case]:
|
|
222
|
+
if len(duplicates) == 1:
|
|
223
|
+
return duplicates
|
|
224
|
+
if policy == "keep-first":
|
|
225
|
+
return duplicates[:1]
|
|
226
|
+
if policy == "keep-last":
|
|
227
|
+
return duplicates[-1:]
|
|
228
|
+
if policy == "keep-both":
|
|
229
|
+
return duplicates
|
|
230
|
+
if policy == "keep-worst":
|
|
231
|
+
worst = max(duplicates, key=lambda c: SEVERITY.get(c.status, 0))
|
|
232
|
+
return [worst]
|
|
233
|
+
raise ValueError(f"duplicate policy must be one of {', '.join(POLICIES)}")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def merge(
|
|
237
|
+
reports: Sequence[Report],
|
|
238
|
+
*,
|
|
239
|
+
on_duplicate: DuplicatePolicy = "keep-worst",
|
|
240
|
+
sort: bool = True,
|
|
241
|
+
) -> Report:
|
|
242
|
+
"""Merge reports, resolving cases that appear in more than one of them.
|
|
243
|
+
|
|
244
|
+
``on_duplicate`` is one of ``keep-worst`` (default), ``keep-first``,
|
|
245
|
+
``keep-last``, ``keep-both`` or ``fail``.
|
|
246
|
+
"""
|
|
247
|
+
if on_duplicate not in POLICIES:
|
|
248
|
+
raise ValueError(f"duplicate policy must be one of {', '.join(POLICIES)}")
|
|
249
|
+
|
|
250
|
+
order: list[tuple[str, str]] = []
|
|
251
|
+
grouped: dict[tuple[str, str], list[Case]] = {}
|
|
252
|
+
properties: dict[str, str] = {}
|
|
253
|
+
suite_names: list[str] = []
|
|
254
|
+
for report in reports:
|
|
255
|
+
for case in report.cases:
|
|
256
|
+
if case.key not in grouped:
|
|
257
|
+
grouped[case.key] = []
|
|
258
|
+
order.append(case.key)
|
|
259
|
+
grouped[case.key].append(case)
|
|
260
|
+
for key, value in report.properties.items():
|
|
261
|
+
properties.setdefault(key, value)
|
|
262
|
+
if report.suite_name and report.suite_name not in suite_names:
|
|
263
|
+
suite_names.append(report.suite_name)
|
|
264
|
+
|
|
265
|
+
cases: list[Case] = []
|
|
266
|
+
for key in order:
|
|
267
|
+
duplicates = grouped[key]
|
|
268
|
+
if len(duplicates) > 1 and on_duplicate == "fail":
|
|
269
|
+
raise ValueError(
|
|
270
|
+
f"{duplicates[0].node_id} appears {len(duplicates)} times; "
|
|
271
|
+
"pass on_duplicate to choose which outcome to keep"
|
|
272
|
+
)
|
|
273
|
+
cases.extend(_resolve(duplicates, on_duplicate))
|
|
274
|
+
|
|
275
|
+
if sort:
|
|
276
|
+
cases.sort(key=lambda c: (c.classname, c.name))
|
|
277
|
+
|
|
278
|
+
name = suite_names[0] if suite_names else "pytest"
|
|
279
|
+
if len(suite_names) > 1:
|
|
280
|
+
name = "merged"
|
|
281
|
+
return Report(cases=cases, properties=properties, suite_name=name)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def merge_files(
|
|
285
|
+
paths: Sequence[str | os.PathLike[str]],
|
|
286
|
+
out: str | os.PathLike[str] | None = None,
|
|
287
|
+
*,
|
|
288
|
+
on_duplicate: DuplicatePolicy = "keep-worst",
|
|
289
|
+
sort: bool = True,
|
|
290
|
+
) -> Report:
|
|
291
|
+
"""Parse several files, merge them, and write the result when ``out`` is given."""
|
|
292
|
+
report = merge([parse_file(p) for p in paths], on_duplicate=on_duplicate, sort=sort)
|
|
293
|
+
if out is not None:
|
|
294
|
+
Path(out).write_bytes(report.to_xml())
|
|
295
|
+
return report
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _set_attr(element: ET.Element, key: str, value: object) -> None:
|
|
299
|
+
element.set(key, str(value))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def to_xml(report: Report, *, name: str | None = None) -> bytes:
|
|
303
|
+
"""Serialise a report. Counts are computed from the cases, never copied."""
|
|
304
|
+
suite_name = name or report.suite_name
|
|
305
|
+
root = ET.Element("testsuites")
|
|
306
|
+
for key, value in report.counts().items():
|
|
307
|
+
_set_attr(root, key, value)
|
|
308
|
+
_set_attr(root, "time", report.time)
|
|
309
|
+
suite = ET.SubElement(root, "testsuite")
|
|
310
|
+
suite.set("name", suite_name)
|
|
311
|
+
for key, value in report.counts().items():
|
|
312
|
+
_set_attr(suite, key, value)
|
|
313
|
+
_set_attr(suite, "time", report.time)
|
|
314
|
+
|
|
315
|
+
if report.properties:
|
|
316
|
+
props = ET.SubElement(suite, "properties")
|
|
317
|
+
for key, value in report.properties.items():
|
|
318
|
+
ET.SubElement(props, "property", {"name": key, "value": value})
|
|
319
|
+
|
|
320
|
+
for case in report.cases:
|
|
321
|
+
element = ET.SubElement(suite, "testcase", {"name": case.name})
|
|
322
|
+
if case.classname:
|
|
323
|
+
element.set("classname", case.classname)
|
|
324
|
+
if case.time:
|
|
325
|
+
element.set("time", f"{case.time:g}")
|
|
326
|
+
if case.file:
|
|
327
|
+
element.set("file", case.file)
|
|
328
|
+
if case.line is not None:
|
|
329
|
+
element.set("line", str(case.line))
|
|
330
|
+
if case.status in ("failure", "error"):
|
|
331
|
+
child = ET.SubElement(element, case.status)
|
|
332
|
+
if case.message:
|
|
333
|
+
child.set("message", case.message)
|
|
334
|
+
child.text = case.detail
|
|
335
|
+
elif case.status == "skipped":
|
|
336
|
+
child = ET.SubElement(element, "skipped")
|
|
337
|
+
if case.message:
|
|
338
|
+
child.set("message", case.message)
|
|
339
|
+
child.text = case.detail
|
|
340
|
+
if case.system_out:
|
|
341
|
+
ET.SubElement(element, "system-out").text = case.system_out
|
|
342
|
+
if case.system_err:
|
|
343
|
+
ET.SubElement(element, "system-err").text = case.system_err
|
|
344
|
+
|
|
345
|
+
ET.indent(root, space=" ")
|
|
346
|
+
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Command line entry point: ``python -m junit_merge`` or ``junit-merge``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import POLICIES, merge, parse_file, to_xml
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog="junit-merge",
|
|
15
|
+
description="Merge JUnit XML reports into one, recomputing the counts.",
|
|
16
|
+
)
|
|
17
|
+
parser.add_argument("reports", nargs="+", type=Path, metavar="REPORT", help="JUnit XML files")
|
|
18
|
+
parser.add_argument("-o", "--out", type=Path, help="write the merged report here")
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--on-duplicate",
|
|
21
|
+
choices=POLICIES,
|
|
22
|
+
default="keep-worst",
|
|
23
|
+
help="what to do with a test that appears in several reports (default: keep-worst)",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--check",
|
|
27
|
+
action="store_true",
|
|
28
|
+
help="exit with status 1 when the merged report contains failures or errors",
|
|
29
|
+
)
|
|
30
|
+
return parser
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def main(argv: list[str] | None = None) -> int:
|
|
34
|
+
args = build_parser().parse_args(argv)
|
|
35
|
+
missing = [str(path) for path in args.reports if not path.is_file()]
|
|
36
|
+
if missing:
|
|
37
|
+
print(f"no such file: {', '.join(missing)}", file=sys.stderr)
|
|
38
|
+
return 2
|
|
39
|
+
try:
|
|
40
|
+
report = merge(
|
|
41
|
+
[parse_file(path) for path in args.reports],
|
|
42
|
+
on_duplicate=args.on_duplicate,
|
|
43
|
+
)
|
|
44
|
+
except ValueError as exc:
|
|
45
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
46
|
+
return 2
|
|
47
|
+
|
|
48
|
+
if args.out:
|
|
49
|
+
args.out.write_bytes(to_xml(report))
|
|
50
|
+
print(
|
|
51
|
+
f"{report.tests} tests, {report.failures} failures, "
|
|
52
|
+
f"{report.errors} errors, {report.skipped} skipped, {report.time:.2f}s"
|
|
53
|
+
)
|
|
54
|
+
if args.check and (report.failures or report.errors):
|
|
55
|
+
return 1
|
|
56
|
+
return 0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Tests for junit_merge."""
|
|
2
|
+
|
|
3
|
+
import xml.etree.ElementTree as ET
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from junit_merge import Case, Report, merge, merge_files, parse, parse_file, to_xml
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def suite(*cases, name="tests", props=None):
|
|
11
|
+
"""Build a JUnit document around the given testcase snippets."""
|
|
12
|
+
properties = ""
|
|
13
|
+
if props:
|
|
14
|
+
entries = "".join(f'<property name="{k}" value="{v}"/>' for k, v in props.items())
|
|
15
|
+
properties = f"<properties>{entries}</properties>"
|
|
16
|
+
return (
|
|
17
|
+
f'<testsuite name="{name}" tests="999" failures="999" errors="999" time="999">'
|
|
18
|
+
f"{properties}{''.join(cases)}</testsuite>"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TestParse:
|
|
23
|
+
def test_reads_a_bare_testsuite(self):
|
|
24
|
+
report = parse(suite('<testcase classname="t" name="a" time="0.5"/>'))
|
|
25
|
+
assert report.tests == 1
|
|
26
|
+
assert report.cases[0].node_id == "t::a"
|
|
27
|
+
assert report.cases[0].time == 0.5
|
|
28
|
+
|
|
29
|
+
def test_reads_a_testsuites_wrapper(self):
|
|
30
|
+
xml = "<testsuites>" + suite('<testcase classname="t" name="a"/>') + "</testsuites>"
|
|
31
|
+
assert parse(xml).tests == 1
|
|
32
|
+
|
|
33
|
+
def test_reads_several_suites(self):
|
|
34
|
+
xml = (
|
|
35
|
+
"<testsuites>"
|
|
36
|
+
+ suite('<testcase classname="t" name="a"/>')
|
|
37
|
+
+ suite('<testcase classname="t" name="b"/>')
|
|
38
|
+
+ "</testsuites>"
|
|
39
|
+
)
|
|
40
|
+
assert [c.name for c in parse(xml).cases] == ["a", "b"]
|
|
41
|
+
|
|
42
|
+
def test_accepts_bytes(self):
|
|
43
|
+
assert parse(suite('<testcase classname="t" name="a"/>').encode()).tests == 1
|
|
44
|
+
|
|
45
|
+
def test_status_is_taken_from_the_child_element(self):
|
|
46
|
+
xml = suite(
|
|
47
|
+
'<testcase classname="t" name="ok"/>',
|
|
48
|
+
'<testcase classname="t" name="bad"><failure message="boom">trace</failure></testcase>',
|
|
49
|
+
'<testcase classname="t" name="err"><error message="kaput"/></testcase>',
|
|
50
|
+
'<testcase classname="t" name="skip"><skipped message="no db"/></testcase>',
|
|
51
|
+
)
|
|
52
|
+
statuses = {c.name: c.status for c in parse(xml).cases}
|
|
53
|
+
assert statuses == {"ok": "passed", "bad": "failure", "err": "error", "skip": "skipped"}
|
|
54
|
+
|
|
55
|
+
def test_failure_message_and_detail_are_kept(self):
|
|
56
|
+
xml = suite(
|
|
57
|
+
'<testcase classname="t" name="bad"><failure message="boom">trace</failure></testcase>'
|
|
58
|
+
)
|
|
59
|
+
case = parse(xml).cases[0]
|
|
60
|
+
assert case.message == "boom"
|
|
61
|
+
assert case.detail == "trace"
|
|
62
|
+
|
|
63
|
+
def test_system_output_is_kept(self):
|
|
64
|
+
xml = suite('<testcase classname="t" name="a"><system-out>printed</system-out></testcase>')
|
|
65
|
+
assert parse(xml).cases[0].system_out == "printed"
|
|
66
|
+
|
|
67
|
+
def test_file_and_line_are_kept(self):
|
|
68
|
+
xml = suite('<testcase classname="t" name="a" file="t.py" line="12"/>')
|
|
69
|
+
case = parse(xml).cases[0]
|
|
70
|
+
assert (case.file, case.line) == ("t.py", 12)
|
|
71
|
+
|
|
72
|
+
def test_non_numeric_line_is_ignored(self):
|
|
73
|
+
xml = suite('<testcase classname="t" name="a" line="n/a"/>')
|
|
74
|
+
assert parse(xml).cases[0].line is None
|
|
75
|
+
|
|
76
|
+
def test_missing_time_is_zero(self):
|
|
77
|
+
xml = suite('<testcase classname="t" name="a"/>')
|
|
78
|
+
assert parse(xml).cases[0].time == 0.0
|
|
79
|
+
|
|
80
|
+
def test_garbage_time_is_zero(self):
|
|
81
|
+
xml = suite('<testcase classname="t" name="a" time="fast"/>')
|
|
82
|
+
assert parse(xml).cases[0].time == 0.0
|
|
83
|
+
|
|
84
|
+
def test_properties_are_collected(self):
|
|
85
|
+
report = parse(suite('<testcase classname="t" name="a"/>', props={"branch": "main"}))
|
|
86
|
+
assert report.properties == {"branch": "main"}
|
|
87
|
+
|
|
88
|
+
def test_namespaced_documents_are_understood(self):
|
|
89
|
+
xml = (
|
|
90
|
+
'<testsuite xmlns="urn:junit" name="t">'
|
|
91
|
+
'<testcase classname="t" name="a"><failure message="m">d</failure></testcase>'
|
|
92
|
+
"</testsuite>"
|
|
93
|
+
)
|
|
94
|
+
case = parse(xml).cases[0]
|
|
95
|
+
assert (case.status, case.message) == ("failure", "m")
|
|
96
|
+
|
|
97
|
+
def test_invalid_xml_raises_value_error(self):
|
|
98
|
+
with pytest.raises(ValueError, match="not valid JUnit XML"):
|
|
99
|
+
parse("<testsuite>")
|
|
100
|
+
|
|
101
|
+
def test_wrong_root_raises_value_error(self):
|
|
102
|
+
with pytest.raises(ValueError, match="not a JUnit report"):
|
|
103
|
+
parse("<report><testsuite/></report>")
|
|
104
|
+
|
|
105
|
+
def test_parse_file(self, tmp_path):
|
|
106
|
+
path = tmp_path / "junit.xml"
|
|
107
|
+
path.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
108
|
+
assert parse_file(path).tests == 1
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class TestCounts:
|
|
112
|
+
def test_counts_come_from_the_cases_not_the_attributes(self):
|
|
113
|
+
xml = suite(
|
|
114
|
+
'<testcase classname="t" name="a"/>',
|
|
115
|
+
'<testcase classname="t" name="b"><failure message="m"/></testcase>',
|
|
116
|
+
)
|
|
117
|
+
report = parse(xml)
|
|
118
|
+
assert report.counts() == {"tests": 2, "failures": 1, "errors": 0, "skipped": 0}
|
|
119
|
+
|
|
120
|
+
def test_errors_and_skips_are_counted_separately(self):
|
|
121
|
+
xml = suite(
|
|
122
|
+
'<testcase classname="t" name="a"><error message="e"/></testcase>',
|
|
123
|
+
'<testcase classname="t" name="b"><skipped/></testcase>',
|
|
124
|
+
)
|
|
125
|
+
report = parse(xml)
|
|
126
|
+
assert (report.tests, report.errors, report.skipped, report.failures) == (2, 1, 1, 0)
|
|
127
|
+
|
|
128
|
+
def test_time_is_summed(self):
|
|
129
|
+
xml = suite(
|
|
130
|
+
'<testcase classname="t" name="a" time="0.25"/>',
|
|
131
|
+
'<testcase classname="t" name="b" time="0.5"/>',
|
|
132
|
+
)
|
|
133
|
+
assert parse(xml).time == 0.75
|
|
134
|
+
|
|
135
|
+
def test_empty_report_has_zero_counts(self):
|
|
136
|
+
assert parse(suite()).counts() == {"tests": 0, "failures": 0, "errors": 0, "skipped": 0}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class TestMerge:
|
|
140
|
+
def test_combines_disjoint_cases(self):
|
|
141
|
+
first = parse(suite('<testcase classname="t" name="a"/>'))
|
|
142
|
+
second = parse(suite('<testcase classname="t" name="b"/>'))
|
|
143
|
+
merged = merge([first, second])
|
|
144
|
+
assert [c.name for c in merged.cases] == ["a", "b"]
|
|
145
|
+
|
|
146
|
+
def test_keeps_the_worst_outcome_by_default(self):
|
|
147
|
+
passed = parse(suite('<testcase classname="t" name="a"/>'))
|
|
148
|
+
failed = parse(
|
|
149
|
+
suite('<testcase classname="t" name="a"><failure message="boom"/></testcase>')
|
|
150
|
+
)
|
|
151
|
+
merged = merge([passed, failed])
|
|
152
|
+
assert merged.tests == 1
|
|
153
|
+
assert merged.failures == 1
|
|
154
|
+
|
|
155
|
+
def test_order_of_inputs_does_not_change_keep_worst(self):
|
|
156
|
+
passed = parse(suite('<testcase classname="t" name="a"/>'))
|
|
157
|
+
errored = parse(suite('<testcase classname="t" name="a"><error message="e"/></testcase>'))
|
|
158
|
+
assert merge([errored, passed]).cases[0].status == "error"
|
|
159
|
+
assert merge([passed, errored]).cases[0].status == "error"
|
|
160
|
+
|
|
161
|
+
def test_skipped_beats_passed(self):
|
|
162
|
+
passed = parse(suite('<testcase classname="t" name="a"/>'))
|
|
163
|
+
skipped = parse(suite('<testcase classname="t" name="a"><skipped/></testcase>'))
|
|
164
|
+
assert merge([passed, skipped]).cases[0].status == "skipped"
|
|
165
|
+
|
|
166
|
+
def test_keep_first(self):
|
|
167
|
+
first = parse(
|
|
168
|
+
suite('<testcase classname="t" name="a"><failure message="first"/></testcase>')
|
|
169
|
+
)
|
|
170
|
+
second = parse(
|
|
171
|
+
suite('<testcase classname="t" name="a"><failure message="second"/></testcase>')
|
|
172
|
+
)
|
|
173
|
+
assert merge([first, second], on_duplicate="keep-first").cases[0].message == "first"
|
|
174
|
+
|
|
175
|
+
def test_keep_last(self):
|
|
176
|
+
first = parse(
|
|
177
|
+
suite('<testcase classname="t" name="a"><failure message="first"/></testcase>')
|
|
178
|
+
)
|
|
179
|
+
second = parse(
|
|
180
|
+
suite('<testcase classname="t" name="a"><failure message="second"/></testcase>')
|
|
181
|
+
)
|
|
182
|
+
assert merge([first, second], on_duplicate="keep-last").cases[0].message == "second"
|
|
183
|
+
|
|
184
|
+
def test_keep_both(self):
|
|
185
|
+
first = parse(suite('<testcase classname="t" name="a"/>'))
|
|
186
|
+
second = parse(suite('<testcase classname="t" name="a"/>'))
|
|
187
|
+
assert merge([first, second], on_duplicate="keep-both").tests == 2
|
|
188
|
+
|
|
189
|
+
def test_fail_policy_names_the_test(self):
|
|
190
|
+
first = parse(suite('<testcase classname="t" name="a"/>'))
|
|
191
|
+
with pytest.raises(ValueError, match="t::a appears 2 times"):
|
|
192
|
+
merge([first, first], on_duplicate="fail")
|
|
193
|
+
|
|
194
|
+
def test_fail_policy_is_silent_without_duplicates(self):
|
|
195
|
+
first = parse(suite('<testcase classname="t" name="a"/>'))
|
|
196
|
+
second = parse(suite('<testcase classname="t" name="b"/>'))
|
|
197
|
+
assert merge([first, second], on_duplicate="fail").tests == 2
|
|
198
|
+
|
|
199
|
+
def test_unknown_policy_raises(self):
|
|
200
|
+
with pytest.raises(ValueError, match="duplicate policy must be one of"):
|
|
201
|
+
merge([Report()], on_duplicate="sometimes")
|
|
202
|
+
|
|
203
|
+
def test_cases_are_sorted_unless_disabled(self):
|
|
204
|
+
xml = suite('<testcase classname="b" name="z"/>', '<testcase classname="a" name="y"/>')
|
|
205
|
+
report = parse(xml)
|
|
206
|
+
assert [c.node_id for c in merge([report]).cases] == ["a::y", "b::z"]
|
|
207
|
+
assert [c.node_id for c in merge([report], sort=False).cases] == ["b::z", "a::y"]
|
|
208
|
+
|
|
209
|
+
def test_properties_are_unioned_first_wins(self):
|
|
210
|
+
first = parse(suite(props={"branch": "main"}))
|
|
211
|
+
second = parse(suite(props={"branch": "dev", "sha": "abc"}))
|
|
212
|
+
merged = merge([first, second])
|
|
213
|
+
assert merged.properties == {"branch": "main", "sha": "abc"}
|
|
214
|
+
|
|
215
|
+
def test_single_suite_name_is_kept(self):
|
|
216
|
+
report = parse(suite(name="pytest"))
|
|
217
|
+
assert merge([report]).suite_name == "pytest"
|
|
218
|
+
|
|
219
|
+
def test_different_suite_names_merge_to_one_name(self):
|
|
220
|
+
first = parse(suite(name="shard-1"))
|
|
221
|
+
second = parse(suite(name="shard-2"))
|
|
222
|
+
assert merge([first, second]).suite_name == "merged"
|
|
223
|
+
|
|
224
|
+
def test_merging_nothing_gives_an_empty_report(self):
|
|
225
|
+
merged = merge([])
|
|
226
|
+
assert (merged.tests, merged.suite_name) == (0, "pytest")
|
|
227
|
+
|
|
228
|
+
def test_merge_is_idempotent(self):
|
|
229
|
+
report = parse(suite('<testcase classname="t" name="a" time="1"/>'))
|
|
230
|
+
once = merge([report])
|
|
231
|
+
twice = merge([once])
|
|
232
|
+
assert once.cases == twice.cases
|
|
233
|
+
assert once.time == twice.time
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class TestXml:
|
|
237
|
+
def test_round_trips(self):
|
|
238
|
+
report = parse(
|
|
239
|
+
suite(
|
|
240
|
+
'<testcase classname="t" name="ok" time="0.5"/>',
|
|
241
|
+
'<testcase classname="t" name="bad">'
|
|
242
|
+
'<failure message="boom">trace</failure></testcase>',
|
|
243
|
+
'<testcase classname="t" name="skip"><skipped message="no db"/></testcase>',
|
|
244
|
+
props={"branch": "main"},
|
|
245
|
+
)
|
|
246
|
+
)
|
|
247
|
+
reparsed = parse(to_xml(report))
|
|
248
|
+
assert reparsed.cases == report.cases
|
|
249
|
+
assert reparsed.properties == report.properties
|
|
250
|
+
|
|
251
|
+
def test_output_is_well_formed_and_declares_its_encoding(self):
|
|
252
|
+
data = to_xml(parse(suite('<testcase classname="t" name="a"/>')))
|
|
253
|
+
assert data.startswith(b"<?xml version='1.0' encoding='utf-8'?>")
|
|
254
|
+
assert ET.fromstring(data).tag == "testsuites"
|
|
255
|
+
|
|
256
|
+
def test_counts_in_the_output_match_the_cases(self):
|
|
257
|
+
xml = suite(
|
|
258
|
+
'<testcase classname="t" name="a"/>',
|
|
259
|
+
'<testcase classname="t" name="b"><failure message="m"/></testcase>',
|
|
260
|
+
'<testcase classname="t" name="c"><error message="e"/></testcase>',
|
|
261
|
+
)
|
|
262
|
+
root = ET.fromstring(to_xml(parse(xml)))
|
|
263
|
+
assert (root.get("tests"), root.get("failures"), root.get("errors")) == ("3", "1", "1")
|
|
264
|
+
assert root.find("testsuite").get("tests") == "3"
|
|
265
|
+
|
|
266
|
+
def test_the_lying_attributes_of_the_input_do_not_leak(self):
|
|
267
|
+
root = ET.fromstring(to_xml(parse(suite('<testcase classname="t" name="a"/>'))))
|
|
268
|
+
assert root.get("tests") == "1"
|
|
269
|
+
assert root.get("failures") == "0"
|
|
270
|
+
|
|
271
|
+
def test_name_can_be_overridden(self):
|
|
272
|
+
root = ET.fromstring(to_xml(parse(suite(name="shard")), name="ci"))
|
|
273
|
+
assert root.find("testsuite").get("name") == "ci"
|
|
274
|
+
|
|
275
|
+
def test_system_output_survives(self):
|
|
276
|
+
xml = suite('<testcase classname="t" name="a"><system-out>hello</system-out></testcase>')
|
|
277
|
+
reparsed = parse(to_xml(parse(xml)))
|
|
278
|
+
assert reparsed.cases[0].system_out == "hello"
|
|
279
|
+
|
|
280
|
+
def test_unicode_survives(self):
|
|
281
|
+
xml = suite('<testcase classname="t" name="unicodé"/>')
|
|
282
|
+
data = to_xml(parse(xml))
|
|
283
|
+
assert parse(data).cases[0].name == "unicodé"
|
|
284
|
+
assert "unicodé".encode() in data
|
|
285
|
+
|
|
286
|
+
def test_markup_in_a_message_is_escaped(self):
|
|
287
|
+
report = Report(cases=[Case(name="a", status="failure", message="<not> & xml")])
|
|
288
|
+
assert parse(to_xml(report)).cases[0].message == "<not> & xml"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class TestMergeFiles:
|
|
292
|
+
def test_writes_the_merged_report(self, tmp_path):
|
|
293
|
+
first = tmp_path / "one.xml"
|
|
294
|
+
second = tmp_path / "two.xml"
|
|
295
|
+
out = tmp_path / "all.xml"
|
|
296
|
+
first.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
297
|
+
second.write_text(suite('<testcase classname="t" name="b"/>'), encoding="utf-8")
|
|
298
|
+
|
|
299
|
+
report = merge_files([first, second], out)
|
|
300
|
+
|
|
301
|
+
assert report.tests == 2
|
|
302
|
+
assert parse_file(out).tests == 2
|
|
303
|
+
|
|
304
|
+
def test_returns_the_report_when_no_output_is_given(self, tmp_path):
|
|
305
|
+
path = tmp_path / "one.xml"
|
|
306
|
+
path.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
307
|
+
assert merge_files([path]).tests == 1
|
|
308
|
+
|
|
309
|
+
def test_a_missing_file_raises(self, tmp_path):
|
|
310
|
+
with pytest.raises(FileNotFoundError):
|
|
311
|
+
merge_files([tmp_path / "nope.xml"])
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class TestCommandLine:
|
|
315
|
+
def run(self, argv):
|
|
316
|
+
from junit_merge.__main__ import main
|
|
317
|
+
|
|
318
|
+
return main(argv)
|
|
319
|
+
|
|
320
|
+
def test_writes_the_output_and_prints_a_summary(self, tmp_path, capsys):
|
|
321
|
+
first = tmp_path / "one.xml"
|
|
322
|
+
second = tmp_path / "two.xml"
|
|
323
|
+
out = tmp_path / "all.xml"
|
|
324
|
+
first.write_text(suite('<testcase classname="t" name="a" time="0.5"/>'), encoding="utf-8")
|
|
325
|
+
second.write_text(
|
|
326
|
+
suite('<testcase classname="t" name="b"><failure message="m"/></testcase>'),
|
|
327
|
+
encoding="utf-8",
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
assert self.run([str(first), str(second), "-o", str(out)]) == 0
|
|
331
|
+
|
|
332
|
+
assert "2 tests, 1 failures, 0 errors, 0 skipped, 0.50s" in capsys.readouterr().out
|
|
333
|
+
assert parse_file(out).tests == 2
|
|
334
|
+
|
|
335
|
+
def test_check_exits_one_when_there_are_failures(self, tmp_path):
|
|
336
|
+
path = tmp_path / "one.xml"
|
|
337
|
+
path.write_text(
|
|
338
|
+
suite('<testcase classname="t" name="a"><failure message="m"/></testcase>'),
|
|
339
|
+
encoding="utf-8",
|
|
340
|
+
)
|
|
341
|
+
assert self.run([str(path), "--check"]) == 1
|
|
342
|
+
|
|
343
|
+
def test_check_exits_zero_when_everything_passed(self, tmp_path):
|
|
344
|
+
path = tmp_path / "one.xml"
|
|
345
|
+
path.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
346
|
+
assert self.run([str(path), "--check"]) == 0
|
|
347
|
+
|
|
348
|
+
def test_missing_file_exits_two(self, tmp_path, capsys):
|
|
349
|
+
assert self.run([str(tmp_path / "nope.xml")]) == 2
|
|
350
|
+
assert "no such file" in capsys.readouterr().err
|
|
351
|
+
|
|
352
|
+
def test_bad_xml_exits_two(self, tmp_path, capsys):
|
|
353
|
+
path = tmp_path / "bad.xml"
|
|
354
|
+
path.write_text("<testsuite>", encoding="utf-8")
|
|
355
|
+
assert self.run([str(path)]) == 2
|
|
356
|
+
assert "not valid JUnit XML" in capsys.readouterr().err
|
|
357
|
+
|
|
358
|
+
def test_duplicate_policy_is_forwarded(self, tmp_path, capsys):
|
|
359
|
+
first = tmp_path / "one.xml"
|
|
360
|
+
second = tmp_path / "two.xml"
|
|
361
|
+
first.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
362
|
+
second.write_text(suite('<testcase classname="t" name="a"/>'), encoding="utf-8")
|
|
363
|
+
assert self.run([str(first), str(second), "--on-duplicate", "keep-both"]) == 0
|
|
364
|
+
assert "2 tests" in capsys.readouterr().out
|