pytest-testcube 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.
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ dist/
@@ -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.
@@ -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,37 @@
1
+ # pytest-testcube
2
+
3
+ Report pytest results to [TestCube](https://testcube.greyboxed.dev). MIT licensed, no dependencies
4
+ beyond pytest.
5
+
6
+ ```sh
7
+ pip install pytest-testcube
8
+ export TESTCUBE_URL=https://testcube.example.com
9
+ export TESTCUBE_TOKEN="<tcs_… service-account token>" # Settings → Service accounts
10
+ export TESTCUBE_PROJECT=WEB # project key
11
+ pytest
12
+ ```
13
+
14
+ Each pytest session becomes one automated run. Link tests to cases with a marker or a key in the name:
15
+
16
+ ```python
17
+ @pytest.mark.testcube("WEB-12")
18
+ def test_login(): ...
19
+
20
+
21
+ def test_checkout_WEB_13(): ...
22
+ ```
23
+
24
+ | Variable / option | Meaning |
25
+ |---|---|
26
+ | `TESTCUBE_RUN_TITLE`, `--testcube-title` | Run title (defaults to the CI run) |
27
+ | `TESTCUBE_ENVIRONMENT`, `--testcube-environment` | Environment name in TestCube |
28
+ | `TESTCUBE_PLAN`, `--testcube-plan` | Plan title or id the run counts toward |
29
+ | `TESTCUBE_RUN_ID`, `--testcube-run-id` | Append to an existing run |
30
+ | `TESTCUBE_AUTO_CREATE=1`, `--testcube-auto-create` | Create Draft cases for unlinked tests |
31
+ | `TESTCUBE_IDEMPOTENCY_KEY` | Defaults to the CI run id, so retried uploads never duplicate |
32
+ | `TESTCUBE_COMPLETE_RUN=0` | Leave the run open |
33
+ | `TESTCUBE_STRICT=1` | Fail the session if reporting fails (off by default) |
34
+ | `--no-testcube` | Disable for one invocation |
35
+
36
+ Setup errors are reported as **blocked**, `pytest-rerunfailures` reruns as retry attempts, and
37
+ `pytest-xdist` works (the controller reports).
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "pytest-testcube"
3
+ dynamic = ["version"]
4
+ description = "Report pytest results to TestCube"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.9"
8
+ authors = [{ name = "Greyboxed" }]
9
+ keywords = ["pytest", "testcube", "test-management", "test-reporter", "ci"]
10
+ dependencies = ["pytest>=7"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Framework :: Pytest",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.9",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Software Development :: Testing",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://testcube.greyboxed.dev"
28
+ Documentation = "https://testcube.greyboxed.dev"
29
+ Support = "https://greyboxed.dev/support/"
30
+
31
+ [project.entry-points.pytest11]
32
+ testcube = "pytest_testcube.plugin"
33
+
34
+ [build-system]
35
+ requires = ["hatchling>=1.27"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.hatch.version]
39
+ path = "src/pytest_testcube/__init__.py"
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ exclude = ["/ruff.toml"] # points outside the package (extend = "../../pyproject.toml")
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/pytest_testcube"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -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 @@
1
+ pytest_plugins = ["pytester"]
@@ -0,0 +1,311 @@
1
+ """pytest-testcube against an in-process fake TestCube API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ import socket
8
+ import struct
9
+ import threading
10
+ import time
11
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
12
+ from typing import Any
13
+
14
+ import pytest
15
+
16
+ from pytest_testcube.client import ci_run_key
17
+ from pytest_testcube.plugin import Reporter
18
+
19
+
20
+ class FakeApi:
21
+ def __init__(self) -> None:
22
+ self.calls: list[tuple[str, str, Any]] = []
23
+ self.fail_chunks = 0
24
+ api = self
25
+
26
+ class Handler(BaseHTTPRequestHandler):
27
+ def _reply(self, status: int, body: Any, headers: dict[str, str] | None = None) -> None:
28
+ data = json.dumps(body).encode()
29
+ self.send_response(status)
30
+ for k, v in (headers or {}).items():
31
+ self.send_header(k, v)
32
+ self.send_header("Content-Type", "application/json")
33
+ self.send_header("Content-Length", str(len(data)))
34
+ self.end_headers()
35
+ self.wfile.write(data)
36
+
37
+ def _handle(self) -> None:
38
+ length = int(self.headers.get("Content-Length") or 0)
39
+ body = json.loads(self.rfile.read(length)) if length else None
40
+ api.calls.append((self.command, self.path, body))
41
+ assert self.headers["Authorization"] == "Bearer tcs_test"
42
+ if self.path.endswith("/token"):
43
+ return self._reply(200, {"workspace_id": "ws", "kind": "service"})
44
+ if self.path.endswith("/projects"):
45
+ return self._reply(200, [{"id": "p1", "key": "WEB"}])
46
+ if self.path.endswith("/ingest"):
47
+ return self._reply(200, {"batch": {"id": "b1"}})
48
+ if "/chunks/" in self.path:
49
+ if api.fail_chunks:
50
+ api.fail_chunks -= 1
51
+ return self._reply(503, {"detail": "busy"}, {"Retry-After": "0"})
52
+ return self._reply(200, {"accepted": len(body["results"])})
53
+ if self.path.endswith("/complete"):
54
+ return self._reply(200, {"run_url": "http://tc/run/1"})
55
+ return self._reply(404, {"detail": "no"})
56
+
57
+ do_GET = do_POST = do_PUT = _handle
58
+
59
+ def log_message(self, *args: Any) -> None:
60
+ pass
61
+
62
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
63
+ self.url = f"http://127.0.0.1:{self.server.server_port}"
64
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
65
+
66
+ def results(self) -> list[dict[str, Any]]:
67
+ out: list[dict[str, Any]] = []
68
+ seen: set[str] = set()
69
+ for method, path, body in self.calls:
70
+ if method == "PUT" and path not in seen:
71
+ seen.add(path)
72
+ out.extend(body["results"])
73
+ return out
74
+
75
+
76
+ @pytest.fixture
77
+ def api(monkeypatch: pytest.MonkeyPatch):
78
+ fake = FakeApi()
79
+ monkeypatch.setenv("TESTCUBE_URL", fake.url)
80
+ monkeypatch.setenv("TESTCUBE_TOKEN", "tcs_test")
81
+ monkeypatch.setenv("TESTCUBE_PROJECT", "web")
82
+ monkeypatch.setenv("TESTCUBE_IDEMPOTENCY_KEY", "k1")
83
+ yield fake
84
+ fake.server.shutdown()
85
+
86
+
87
+ SUITE = """
88
+ import pytest
89
+
90
+ @pytest.mark.testcube("WEB-1")
91
+ def test_login():
92
+ assert True
93
+
94
+ def test_checkout_WEB_2():
95
+ assert 1 == 2, "totals differ"
96
+
97
+ class TestCart:
98
+ def test_add_item(self):
99
+ pass
100
+
101
+ @pytest.mark.skip(reason="not yet")
102
+ def test_remove(self):
103
+ pass
104
+
105
+ @pytest.fixture
106
+ def broken():
107
+ raise RuntimeError("db down")
108
+
109
+ def test_needs_db(broken):
110
+ pass
111
+
112
+ @pytest.mark.parametrize("currency", ["INR", "USD"])
113
+ def test_pay(currency):
114
+ pass
115
+ """
116
+
117
+
118
+ def test_reports_every_outcome(pytester: pytest.Pytester, api: FakeApi, monkeypatch) -> None:
119
+ monkeypatch.setenv("TESTCUBE_PLAN", "Release 4.2")
120
+ pytester.makepyfile(test_shop=SUITE)
121
+ result = pytester.runpytest()
122
+ result.assert_outcomes(passed=4, failed=1, skipped=1, errors=1)
123
+ result.stdout.fnmatch_lines(["*TestCube: 7 results -> http://tc/run/1*"])
124
+ by_id = {r["automation_id"]: r for r in api.results()}
125
+ assert by_id["test_shop.py::test_login"]["case"] == "WEB-1"
126
+ checkout = by_id["test_shop.py::test_checkout_WEB_2"]
127
+ assert checkout["status"] == "failed" and checkout["case"] == "WEB-2"
128
+ assert "totals differ" in checkout["message"] and "assert 1 == 2" in checkout["stack_trace"]
129
+ assert by_id["test_shop.py::TestCart::test_add_item"]["suite"] == ["test_shop.py", "TestCart"]
130
+ assert by_id["test_shop.py::TestCart::test_remove"]["status"] == "skipped"
131
+ assert by_id["test_shop.py::test_needs_db"]["status"] == "blocked"
132
+ assert by_id["test_shop.py::test_pay[INR]"]["title"] == "test_pay[INR]"
133
+ opened = next(body for method, path, body in api.calls if path.endswith("/ingest"))
134
+ assert opened["idempotency_key"] == "k1" and opened["reporter"].startswith("pytest-testcube")
135
+ assert opened["plan"] == "Release 4.2"
136
+
137
+
138
+ def test_chunks_and_retries(pytester: pytest.Pytester, api: FakeApi, monkeypatch) -> None:
139
+ monkeypatch.setattr("pytest_testcube.plugin.CHUNK", 3)
140
+ pytester.makepyfile(test_many="\n".join(f"def test_{i}(): pass" for i in range(7)))
141
+ api.fail_chunks = 1
142
+ result = pytester.runpytest_inprocess()
143
+ result.assert_outcomes(passed=7)
144
+ chunk_paths = [p for m, p, _ in api.calls if m == "PUT"]
145
+ assert [p.rsplit("/", 1)[1] for p in chunk_paths] == ["0", "0", "1", "2"]
146
+ assert len(api.results()) == 7
147
+
148
+
149
+ def test_api_errors_never_fail_the_run(pytester: pytest.Pytester, monkeypatch) -> None:
150
+ monkeypatch.setenv("TESTCUBE_URL", "http://127.0.0.1:9")
151
+ monkeypatch.setenv("TESTCUBE_TOKEN", "t")
152
+ monkeypatch.setenv("TESTCUBE_PROJECT", "WEB")
153
+ monkeypatch.setattr(
154
+ "pytest_testcube.client.Client.__init__.__kwdefaults__",
155
+ {"retries": 0, "base_delay": 0.0, "timeout": 5.0},
156
+ )
157
+ pytester.makepyfile("def test_ok(): pass")
158
+ result = pytester.runpytest_inprocess()
159
+ assert result.ret == 0
160
+ result.stdout.fnmatch_lines(["*TestCube: reporting skipped*"])
161
+
162
+
163
+ class BadServer:
164
+ """Answers every request the wrong way: `html`, `reset` (RST mid-body) or `stall` (never finishes)."""
165
+
166
+ def __init__(self, mode: str) -> None:
167
+ class Handler(BaseHTTPRequestHandler):
168
+ def _handle(self) -> None:
169
+ length = int(self.headers.get("Content-Length") or 0)
170
+ self.rfile.read(length)
171
+ if mode == "html":
172
+ data = b"<html>single page app</html>"
173
+ self.send_response(200)
174
+ self.send_header("Content-Type", "text/html")
175
+ self.send_header("Content-Length", str(len(data)))
176
+ self.end_headers()
177
+ self.wfile.write(data)
178
+ return
179
+ self.send_response(200)
180
+ self.send_header("Content-Length", "1000")
181
+ self.end_headers()
182
+ self.wfile.write(b"{")
183
+ self.wfile.flush()
184
+ if mode == "reset":
185
+ linger = struct.pack("ii", 1, 0) # close() sends RST instead of FIN
186
+ self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger)
187
+ self.close_connection = True
188
+ self.connection.close()
189
+ else:
190
+ time.sleep(2)
191
+
192
+ do_GET = do_POST = do_PUT = _handle
193
+
194
+ def log_message(self, *args: Any) -> None:
195
+ pass
196
+
197
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
198
+ self.url = f"http://127.0.0.1:{self.server.server_port}"
199
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
200
+
201
+
202
+ @pytest.mark.parametrize("mode", ["html", "reset", "stall"])
203
+ def test_bad_server_answers_never_fail_the_run(
204
+ pytester: pytest.Pytester, monkeypatch, mode: str
205
+ ) -> None:
206
+ bad = BadServer(mode)
207
+ monkeypatch.setenv("TESTCUBE_URL", bad.url)
208
+ monkeypatch.setenv("TESTCUBE_TOKEN", "t")
209
+ monkeypatch.setenv("TESTCUBE_PROJECT", "WEB")
210
+ monkeypatch.setattr(
211
+ "pytest_testcube.client.Client.__init__.__kwdefaults__",
212
+ {"retries": 0, "base_delay": 0.0, "timeout": 0.3},
213
+ )
214
+ pytester.makepyfile("def test_ok(): pass")
215
+ try:
216
+ result = pytester.runpytest_inprocess()
217
+ finally:
218
+ bad.server.shutdown()
219
+ assert result.ret == 0
220
+ result.assert_outcomes(passed=1)
221
+ result.stdout.fnmatch_lines(["*TestCube: reporting skipped*"])
222
+ assert "Traceback" not in result.stdout.str() + result.stderr.str()
223
+
224
+
225
+ def test_strict_mode_still_fails_the_run(pytester: pytest.Pytester, monkeypatch) -> None:
226
+ bad = BadServer("html")
227
+ monkeypatch.setenv("TESTCUBE_URL", bad.url)
228
+ monkeypatch.setenv("TESTCUBE_TOKEN", "t")
229
+ monkeypatch.setenv("TESTCUBE_PROJECT", "WEB")
230
+ monkeypatch.setenv("TESTCUBE_STRICT", "1")
231
+ monkeypatch.setattr(
232
+ "pytest_testcube.client.Client.__init__.__kwdefaults__",
233
+ {"retries": 0, "base_delay": 0.0, "timeout": 0.3},
234
+ )
235
+ pytester.makepyfile("def test_ok(): pass")
236
+ try:
237
+ result = pytester.runpytest_inprocess()
238
+ finally:
239
+ bad.server.shutdown()
240
+ assert result.ret != 0
241
+
242
+
243
+ def test_a_recording_bug_never_fails_the_run(
244
+ pytester: pytest.Pytester, api: FakeApi, monkeypatch
245
+ ) -> None:
246
+ def boom(*args: Any) -> None:
247
+ raise RuntimeError("boom")
248
+
249
+ monkeypatch.setattr("pytest_testcube.plugin.Reporter._store", boom)
250
+ pytester.makepyfile("def test_ok(): pass")
251
+ result = pytester.runpytest_inprocess()
252
+ assert result.ret == 0
253
+ result.stdout.fnmatch_lines(["*TestCube: a result was not recorded*boom*"])
254
+
255
+
256
+ def test_pytest_exit_is_not_swallowed(pytester: pytest.Pytester, api: FakeApi, monkeypatch) -> None:
257
+ def stop(*args: Any) -> None:
258
+ pytest.exit("stop-now", returncode=7)
259
+
260
+ monkeypatch.setattr("pytest_testcube.plugin.Reporter._send", stop)
261
+ pytester.makepyfile("def test_ok(): pass")
262
+ result = pytester.runpytest_inprocess()
263
+ assert result.ret == 7
264
+ assert "reporting skipped" not in result.stdout.str()
265
+
266
+
267
+ def test_pytest_exit_in_a_recording_hook_is_not_swallowed(
268
+ pytester: pytest.Pytester, api: FakeApi, monkeypatch
269
+ ) -> None:
270
+ def stop(*args: Any) -> None:
271
+ pytest.exit("stop-now", returncode=7)
272
+
273
+ monkeypatch.setattr("pytest_testcube.plugin.Reporter._store", stop)
274
+ pytester.makepyfile("def test_ok(): pass")
275
+ assert pytester.runpytest_inprocess().ret == 7
276
+
277
+
278
+ @pytest.mark.parametrize(
279
+ "hook",
280
+ [
281
+ "pytest_collection_modifyitems",
282
+ "pytest_runtest_logreport",
283
+ "pytest_sessionfinish",
284
+ ],
285
+ )
286
+ def test_hooks_keep_their_real_signatures(hook: str) -> None:
287
+ """pluggy < 1.2 reads argument names without following functools.wraps, so a decorator
288
+ around a hook makes pytest call it with no arguments (and nothing is reported)."""
289
+ import _pytest.hookspec as hookspec
290
+
291
+ impl = getattr(Reporter, hook)
292
+ assert not hasattr(impl, "__wrapped__"), "a wrapper hides the hook's arguments from pluggy"
293
+ wanted = set(inspect.signature(getattr(hookspec, hook)).parameters)
294
+ got = set(inspect.signature(impl, follow_wrapped=False).parameters) - {"self"}
295
+ assert got and got <= wanted, (got, wanted)
296
+
297
+
298
+ def test_disabled_without_config(pytester: pytest.Pytester, monkeypatch) -> None:
299
+ for name in ("TESTCUBE_URL", "TESTCUBE_TOKEN", "TESTCUBE_PROJECT"):
300
+ monkeypatch.delenv(name, raising=False)
301
+ pytester.makepyfile("def test_ok(): pass")
302
+ result = pytester.runpytest_inprocess()
303
+ assert result.ret == 0 and "TestCube" not in result.stdout.str()
304
+
305
+
306
+ def test_ci_run_key() -> None:
307
+ assert (
308
+ ci_run_key({"GITHUB_RUN_ID": "5", "GITHUB_RUN_ATTEMPT": "1", "GITHUB_JOB": "unit"})
309
+ == "github:5:1:unit"
310
+ )
311
+ assert ci_run_key({}).startswith("local:")