pytest-testcube 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ """pytest-testcube: report pytest results to TestCube (MIT)."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,116 @@
1
+ """Minimal TestCube ingest client (stdlib only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import os
8
+ import random
9
+ import re
10
+ import time
11
+ import urllib.error
12
+ import urllib.request
13
+ import uuid
14
+ from typing import Any
15
+
16
+ from pytest_testcube import __version__
17
+
18
+ RETRYABLE = {408, 425, 429, 500, 502, 503, 504}
19
+
20
+
21
+ class TestCubeError(Exception):
22
+ __test__ = False
23
+
24
+ def __init__(self, status: int, message: str) -> None:
25
+ super().__init__(message)
26
+ self.status = status
27
+
28
+
29
+ def ci_run_key(env: dict[str, str] | None = None) -> str:
30
+ """Stable across retries of the same CI job, so re-uploads never duplicate results."""
31
+ env = dict(os.environ) if env is None else env
32
+ if env.get("GITHUB_RUN_ID"):
33
+ parts = [
34
+ "github",
35
+ env["GITHUB_RUN_ID"],
36
+ env.get("GITHUB_RUN_ATTEMPT"),
37
+ env.get("GITHUB_JOB"),
38
+ ]
39
+ elif env.get("GITLAB_CI"):
40
+ parts = ["gitlab", env.get("CI_PIPELINE_ID"), env.get("CI_JOB_ID")]
41
+ elif env.get("CIRCLECI"):
42
+ parts = [
43
+ "circle",
44
+ env.get("CIRCLE_WORKFLOW_ID"),
45
+ env.get("CIRCLE_JOB"),
46
+ env.get("CIRCLE_NODE_INDEX"),
47
+ ]
48
+ elif env.get("BUILDKITE"):
49
+ parts = ["buildkite", env.get("BUILDKITE_BUILD_ID"), env.get("BUILDKITE_JOB_ID")]
50
+ elif env.get("JENKINS_URL") and env.get("BUILD_TAG"):
51
+ parts = ["jenkins", env["BUILD_TAG"]]
52
+ else:
53
+ parts = ["local", str(uuid.uuid4())]
54
+ return ":".join(p for p in parts if p)[:200]
55
+
56
+
57
+ class Client:
58
+ def __init__(
59
+ self,
60
+ url: str,
61
+ token: str,
62
+ *,
63
+ retries: int = 5,
64
+ base_delay: float = 1.0,
65
+ timeout: float = 60.0,
66
+ ) -> None:
67
+ self.url = url.rstrip("/")
68
+ self.token = token
69
+ self.retries = retries
70
+ self.base_delay = base_delay
71
+ self.timeout = timeout
72
+
73
+ def request(self, method: str, path: str, body: Any = None) -> Any:
74
+ data = None if body is None else json.dumps(body).encode()
75
+ for attempt in range(self.retries + 1):
76
+ req = urllib.request.Request( # noqa: S310 (URL comes from the user's own config)
77
+ f"{self.url}/api/v1{path}",
78
+ data=data,
79
+ method=method,
80
+ headers={
81
+ "Authorization": f"Bearer {self.token}",
82
+ "Accept": "application/json",
83
+ "Content-Type": "application/json",
84
+ "User-Agent": f"pytest-testcube/{__version__}",
85
+ },
86
+ )
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310
89
+ raw = resp.read()
90
+ try:
91
+ return json.loads(raw or b"null")
92
+ except ValueError as exc: # a 200 that is not JSON: wrong URL, proxy, SPA fallback
93
+ raise TestCubeError(
94
+ 200, f"TestCube {method} {path} -> not JSON ({exc}); is TESTCUBE_URL right?"
95
+ ) from exc
96
+ except urllib.error.HTTPError as exc:
97
+ status, retry_after = exc.code, exc.headers.get("Retry-After")
98
+ detail = _detail(exc)
99
+ except (OSError, http.client.HTTPException) as exc:
100
+ # URLError, resets, timeouts (socket.timeout is not TimeoutError before 3.10),
101
+ # and truncated bodies (IncompleteRead)
102
+ status, retry_after, detail = 0, None, str(exc)
103
+ if (status and status not in RETRYABLE) or attempt == self.retries:
104
+ raise TestCubeError(
105
+ status, f"TestCube {method} {path} -> {status or 'network'}: {detail}"
106
+ )
107
+ delay = float(retry_after) if retry_after and re.fullmatch(r"\d+", retry_after) else 0
108
+ time.sleep(min(delay or self.base_delay * 2**attempt * (1 + random.random() / 5), 60)) # noqa: S311
109
+ raise AssertionError("unreachable")
110
+
111
+
112
+ def _detail(exc: urllib.error.HTTPError) -> str:
113
+ try:
114
+ return str(json.loads(exc.read()).get("detail") or exc.reason)
115
+ except (ValueError, AttributeError):
116
+ return str(exc.reason)
@@ -0,0 +1,219 @@
1
+ """pytest plugin: one TestCube ingest batch per pytest session.
2
+
3
+ Enable by setting TESTCUBE_URL, TESTCUBE_TOKEN and TESTCUBE_PROJECT (or --testcube-* options).
4
+ Link tests to cases with `@pytest.mark.testcube("WEB-12")` or `@WEB-12` in the test name.
5
+ Reporting problems never fail the test run unless TESTCUBE_STRICT=1.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ from typing import Any
13
+
14
+ import pytest
15
+
16
+ from pytest_testcube import __version__
17
+ from pytest_testcube.client import Client, TestCubeError, ci_run_key
18
+
19
+ CHUNK = 500
20
+ KEY = re.compile(r"(?:^|[\s(\[_@])@?([A-Za-z][A-Za-z0-9]{1,9}-\d{1,9})\b")
21
+ # Python names can't hold "-": test_checkout_WEB_12 links to WEB-12 (upper-case key only).
22
+ NAME_KEY = re.compile(r"_([A-Z][A-Z0-9]{1,9})_(\d{1,9})(?:$|\[)")
23
+ MESSAGE_LIMIT = 4000
24
+ STACK_LIMIT = 8192
25
+
26
+
27
+ def _truthy(value: str | None) -> bool:
28
+ return (value or "").lower() in ("1", "true", "yes", "on")
29
+
30
+
31
+ def pytest_addoption(parser: pytest.Parser) -> None:
32
+ group = parser.getgroup("testcube", "Report results to TestCube")
33
+ group.addoption("--testcube-project", help="Project key (TESTCUBE_PROJECT)")
34
+ group.addoption("--testcube-title", help="Run title (TESTCUBE_RUN_TITLE)")
35
+ group.addoption("--testcube-environment", help="Environment name (TESTCUBE_ENVIRONMENT)")
36
+ group.addoption(
37
+ "--testcube-plan", help="Plan title or id the run counts toward (TESTCUBE_PLAN)"
38
+ )
39
+ group.addoption("--testcube-run-id", help="Append to an existing run (TESTCUBE_RUN_ID)")
40
+ group.addoption(
41
+ "--testcube-auto-create",
42
+ action="store_true",
43
+ default=None,
44
+ help="Create Draft cases for unlinked tests (TESTCUBE_AUTO_CREATE)",
45
+ )
46
+ group.addoption("--no-testcube", action="store_true", help="Disable reporting")
47
+
48
+
49
+ def pytest_configure(config: pytest.Config) -> None:
50
+ config.addinivalue_line(
51
+ "markers", "testcube(key): link this test to a TestCube case, e.g. 'WEB-12'"
52
+ )
53
+ if config.getoption("--no-testcube") or hasattr(config, "workerinput"): # xdist workers
54
+ return
55
+ env = os.environ
56
+ url, token = env.get("TESTCUBE_URL", ""), env.get("TESTCUBE_TOKEN", "")
57
+ project = config.getoption("--testcube-project") or env.get("TESTCUBE_PROJECT", "")
58
+ if url and token and project:
59
+ config.pluginmanager.register(Reporter(config, url, token, project), "testcube-reporter")
60
+
61
+
62
+ def _case_key(item_markers: list[Any], name: str) -> str | None:
63
+ for mark in item_markers:
64
+ if mark.args:
65
+ return str(mark.args[0]).lstrip("@").upper()
66
+ found = KEY.search(name)
67
+ if found:
68
+ return found.group(1).upper()
69
+ named = NAME_KEY.search(name)
70
+ return f"{named.group(1)}-{named.group(2)}" if named else None
71
+
72
+
73
+ class Reporter:
74
+ def __init__(self, config: pytest.Config, url: str, token: str, project: str) -> None:
75
+ env = os.environ
76
+ self.config = config
77
+ self.client = Client(url, token)
78
+ self.project = project
79
+ self.strict = _truthy(env.get("TESTCUBE_STRICT"))
80
+ self.title = config.getoption("--testcube-title") or env.get("TESTCUBE_RUN_TITLE") or ""
81
+ self.environment = config.getoption("--testcube-environment") or env.get(
82
+ "TESTCUBE_ENVIRONMENT"
83
+ )
84
+ self.plan = config.getoption("--testcube-plan") or env.get("TESTCUBE_PLAN")
85
+ self.run_id = config.getoption("--testcube-run-id") or env.get("TESTCUBE_RUN_ID")
86
+ auto = config.getoption("--testcube-auto-create")
87
+ self.auto_create = (
88
+ bool(auto) if auto is not None else _truthy(env.get("TESTCUBE_AUTO_CREATE"))
89
+ )
90
+ self.key = env.get("TESTCUBE_IDEMPOTENCY_KEY") or ci_run_key()
91
+ self.complete_run = _truthy(env.get("TESTCUBE_COMPLETE_RUN", "1"))
92
+ self.results: dict[str, dict[str, Any]] = {}
93
+ self.attempts: dict[str, int] = {}
94
+ self.cases: dict[str, str | None] = {}
95
+ self.problem: Exception | None = None
96
+
97
+ # The hooks below are plain methods (no decorator): pluggy before 1.2 reads their argument
98
+ # names without following functools.wraps. A bug while recording must not fail the run.
99
+ @pytest.hookimpl(trylast=True)
100
+ def pytest_collection_modifyitems(self, items: list[pytest.Item]) -> None:
101
+ try:
102
+ for item in items:
103
+ self.cases[item.nodeid] = _case_key(list(item.iter_markers("testcube")), item.name)
104
+ except pytest.exit.Exception:
105
+ raise
106
+ except Exception as exc:
107
+ self._recording_problem(exc)
108
+
109
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
110
+ try:
111
+ self._record(report)
112
+ except pytest.exit.Exception:
113
+ raise
114
+ except Exception as exc:
115
+ self._recording_problem(exc)
116
+
117
+ def _recording_problem(self, exc: Exception) -> None:
118
+ if self.strict:
119
+ raise exc
120
+ self.problem = self.problem or exc
121
+
122
+ def _record(self, report: pytest.TestReport) -> None:
123
+ nodeid = report.nodeid
124
+ if report.outcome == "rerun": # pytest-rerunfailures
125
+ self.attempts[nodeid] = self.attempts.get(nodeid, 0) + 1
126
+ return
127
+ current = self.results.get(nodeid)
128
+ if report.when == "setup":
129
+ if report.skipped:
130
+ self._store(report, "skipped")
131
+ elif report.failed:
132
+ self._store(report, "blocked") # fixture/setup error: the test never ran
133
+ elif report.when == "call":
134
+ if hasattr(report, "wasxfail"):
135
+ self._store(report, "skipped" if report.skipped else "failed")
136
+ else:
137
+ self._store(
138
+ report, "passed" if report.passed else "skipped" if report.skipped else "failed"
139
+ )
140
+ elif (
141
+ report.when == "teardown"
142
+ and report.failed
143
+ and current
144
+ and current["status"] == "passed"
145
+ ):
146
+ self._store(report, "failed")
147
+ if report.when == "teardown" and current is not None:
148
+ current["duration_ms"] = int((current.get("duration_ms") or 0) + report.duration * 1000)
149
+
150
+ def _store(self, report: pytest.TestReport, status: str) -> None:
151
+ path, _, rest = report.nodeid.partition("::")
152
+ parts = rest.split("::") if rest else [report.nodeid]
153
+ text = report.longreprtext or ""
154
+ if status == "skipped" and isinstance(report.longrepr, tuple):
155
+ text = str(report.longrepr[2])
156
+ crash = getattr(getattr(report.longrepr, "reprcrash", None), "message", None)
157
+ message = str(crash) if crash else (text.strip().splitlines()[-1] if text.strip() else "")
158
+ self.results[report.nodeid] = {
159
+ "automation_id": report.nodeid[:500],
160
+ "title": parts[-1][:2000],
161
+ "status": status,
162
+ "case": self.cases.get(report.nodeid),
163
+ "duration_ms": int(report.duration * 1000),
164
+ "message": message[:MESSAGE_LIMIT],
165
+ "stack_trace": text[-STACK_LIMIT:] if status in ("failed", "blocked") else "",
166
+ "attempt": self.attempts.get(report.nodeid, 0),
167
+ "suite": [path, *parts[:-1]][:8],
168
+ }
169
+
170
+ def pytest_sessionfinish(self, session: pytest.Session) -> None:
171
+ reporter = session.config.pluginmanager.get_plugin("terminalreporter")
172
+ if self.problem is not None and reporter is not None:
173
+ reporter.write_line(
174
+ f"TestCube: a result was not recorded ({self.problem!r})", yellow=True
175
+ )
176
+ if not self.results:
177
+ return
178
+ try:
179
+ url = self._send(list(self.results.values()))
180
+ if reporter is not None:
181
+ reporter.write_line(f"TestCube: {len(self.results)} results -> {url}")
182
+ except pytest.exit.Exception:
183
+ raise
184
+ except Exception as exc: # reporting must never fail a green run
185
+ if self.strict:
186
+ raise
187
+ if reporter is not None:
188
+ reporter.write_line(f"TestCube: reporting skipped ({exc})", yellow=True)
189
+
190
+ def _send(self, results: list[dict[str, Any]]) -> str:
191
+ info = self.client.request("GET", "/token")
192
+ ws = info["workspace_id"]
193
+ projects = self.client.request("GET", f"/workspaces/{ws}/projects")
194
+ match = [p for p in projects if p["key"] == self.project.upper() or p["id"] == self.project]
195
+ if not match:
196
+ raise TestCubeError(404, f"Project {self.project} not found for this token")
197
+ base = f"/workspaces/{ws}/projects/{match[0]['id']}/ingest"
198
+ opened = self.client.request(
199
+ "POST",
200
+ base,
201
+ {
202
+ "idempotency_key": self.key,
203
+ "title": self.title,
204
+ "run_id": self.run_id,
205
+ "environment": self.environment,
206
+ "plan": self.plan,
207
+ "auto_create": self.auto_create,
208
+ "reporter": f"pytest-testcube/{__version__}",
209
+ },
210
+ )
211
+ batch = opened["batch"]["id"]
212
+ for seq, start in enumerate(range(0, len(results), CHUNK)):
213
+ self.client.request(
214
+ "PUT", f"{base}/{batch}/chunks/{seq}", {"results": results[start : start + CHUNK]}
215
+ )
216
+ done = self.client.request(
217
+ "POST", f"{base}/{batch}/complete", {"complete_run": self.complete_run}
218
+ )
219
+ return str(done["run_url"])
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytest-testcube
3
+ Version: 0.1.0
4
+ Summary: Report pytest results to TestCube
5
+ Project-URL: Homepage, https://testcube.greyboxed.dev
6
+ Project-URL: Documentation, https://testcube.greyboxed.dev
7
+ Project-URL: Support, https://greyboxed.dev/support/
8
+ Author: Greyboxed
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ci,pytest,test-management,test-reporter,testcube
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Pytest
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Software Development :: Testing
24
+ Requires-Python: >=3.9
25
+ Requires-Dist: pytest>=7
26
+ Description-Content-Type: text/markdown
27
+
28
+ # pytest-testcube
29
+
30
+ Report pytest results to [TestCube](https://testcube.greyboxed.dev). MIT licensed, no dependencies
31
+ beyond pytest.
32
+
33
+ ```sh
34
+ pip install pytest-testcube
35
+ export TESTCUBE_URL=https://testcube.example.com
36
+ export TESTCUBE_TOKEN="<tcs_… service-account token>" # Settings → Service accounts
37
+ export TESTCUBE_PROJECT=WEB # project key
38
+ pytest
39
+ ```
40
+
41
+ Each pytest session becomes one automated run. Link tests to cases with a marker or a key in the name:
42
+
43
+ ```python
44
+ @pytest.mark.testcube("WEB-12")
45
+ def test_login(): ...
46
+
47
+
48
+ def test_checkout_WEB_13(): ...
49
+ ```
50
+
51
+ | Variable / option | Meaning |
52
+ |---|---|
53
+ | `TESTCUBE_RUN_TITLE`, `--testcube-title` | Run title (defaults to the CI run) |
54
+ | `TESTCUBE_ENVIRONMENT`, `--testcube-environment` | Environment name in TestCube |
55
+ | `TESTCUBE_PLAN`, `--testcube-plan` | Plan title or id the run counts toward |
56
+ | `TESTCUBE_RUN_ID`, `--testcube-run-id` | Append to an existing run |
57
+ | `TESTCUBE_AUTO_CREATE=1`, `--testcube-auto-create` | Create Draft cases for unlinked tests |
58
+ | `TESTCUBE_IDEMPOTENCY_KEY` | Defaults to the CI run id, so retried uploads never duplicate |
59
+ | `TESTCUBE_COMPLETE_RUN=0` | Leave the run open |
60
+ | `TESTCUBE_STRICT=1` | Fail the session if reporting fails (off by default) |
61
+ | `--no-testcube` | Disable for one invocation |
62
+
63
+ Setup errors are reported as **blocked**, `pytest-rerunfailures` reruns as retry attempts, and
64
+ `pytest-xdist` works (the controller reports).
@@ -0,0 +1,8 @@
1
+ pytest_testcube/__init__.py,sha256=EgH2gypiXEOm2x2OsbVQt16QWLxBR5wtflmCJeNkMAc,87
2
+ pytest_testcube/client.py,sha256=kFSt_nuEzowFVm640wZABE34e1cDX5JjnAbh4O6E71c,4214
3
+ pytest_testcube/plugin.py,sha256=SQC_TFt9EDSUZLLojq-pYILCMKLN3VuuKt-eNuJ_Fpk,9430
4
+ pytest_testcube-0.1.0.dist-info/METADATA,sha256=Cgf3cRdg3nN4qC76HOO4ji5jjL10vm07304YFZJ-lLk,2500
5
+ pytest_testcube-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ pytest_testcube-0.1.0.dist-info/entry_points.txt,sha256=mXy7ZHWGXvouVh23JFqfsiRZk1Ws4mAnAPKei-hJFBU,45
7
+ pytest_testcube-0.1.0.dist-info/licenses/LICENSE,sha256=uq4KmswzOCpYFYh0uXqbDMA_UUhs5M_Xxn_Oda22Y1M,1066
8
+ pytest_testcube-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ testcube = pytest_testcube.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Greyboxed
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.