moz-testrail-client 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,62 @@
1
+ *model
2
+ *model.zst
3
+ *model.zst.etag
4
+ *data_X
5
+ *data_y
6
+ *data_X.zst
7
+ *data_X.zst.etag
8
+ *data_y.zst
9
+ *data_y.zst.etag
10
+ feature_importance.png
11
+ importance.html
12
+ importances.json
13
+ metrics.json
14
+ probs.json
15
+ services/bugbug-api/models/*model*
16
+
17
+ data/
18
+ sheets/
19
+
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ *.pyc
23
+ .coverage
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ build/
28
+ develop-eggs/
29
+ dist/
30
+ downloads/
31
+ eggs/
32
+ .eggs/
33
+ lib/
34
+ lib64/
35
+ parts/
36
+ sdist/
37
+ var/
38
+ wheels/
39
+ pip-wheel-metadata/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+ cache/
46
+ node_modules/
47
+
48
+ # Logs
49
+ *.log
50
+ # Desktop Service Store
51
+ *.DS_Store
52
+
53
+ # Local env files
54
+ .env
55
+ /services/bugbug-api/docker-compose.override.yml
56
+
57
+ # Local files
58
+ *.local.*
59
+
60
+ # Claude Code local state
61
+ .claude/worktrees/
62
+ .claude/.cc-writes/
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.5
2
+ Name: moz-testrail-client
3
+ Version: 0.1.0
4
+ Summary: Small shared TestRail API client (httpx-based)
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: httpx>=0.26.0
7
+ Requires-Dist: pydantic-settings>=2.1.0
8
+ Provides-Extra: dev
9
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
10
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "moz-testrail-client"
3
+ dynamic = ["version"]
4
+ description = "Small shared TestRail API client (httpx-based)"
5
+ requires-python = ">=3.14"
6
+ dependencies = [
7
+ "httpx>=0.26.0",
8
+ "pydantic-settings>=2.1.0",
9
+ ]
10
+
11
+ [project.optional-dependencies]
12
+ dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"]
13
+
14
+ [build-system]
15
+ requires = ["hatchling"]
16
+ build-backend = "hatchling.build"
17
+
18
+ [tool.hatch.version]
19
+ path = "VERSION"
20
+ pattern = "(?P<version>.+)"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["testrail_client"]
24
+
25
+ [tool.pytest.ini_options]
26
+ asyncio_mode = "auto"
27
+ testpaths = ["tests"]
@@ -0,0 +1,29 @@
1
+ from testrail_client.client import TestRailClient
2
+ from testrail_client.config import TestRailSettings
3
+ from testrail_client.models import (
4
+ Case,
5
+ CaseResult,
6
+ CaseStep,
7
+ CaseType,
8
+ Result,
9
+ Run,
10
+ Section,
11
+ Status,
12
+ Suite,
13
+ Template,
14
+ )
15
+
16
+ __all__ = [
17
+ "Case",
18
+ "CaseResult",
19
+ "CaseStep",
20
+ "CaseType",
21
+ "Result",
22
+ "Run",
23
+ "Section",
24
+ "Status",
25
+ "Suite",
26
+ "Template",
27
+ "TestRailClient",
28
+ "TestRailSettings",
29
+ ]
@@ -0,0 +1,144 @@
1
+ """Small shared TestRail API client."""
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from testrail_client.config import TestRailSettings
8
+ from testrail_client.models import (
9
+ Case,
10
+ CaseResult,
11
+ CaseStep,
12
+ CaseType,
13
+ Result,
14
+ Run,
15
+ Section,
16
+ Status,
17
+ Suite,
18
+ Template,
19
+ _CaseTypesResponse,
20
+ _ResultsResponse,
21
+ _StatusesResponse,
22
+ _TemplatesResponse,
23
+ )
24
+
25
+
26
+ class TestRailClient:
27
+ def __init__(self, settings: TestRailSettings | None = None) -> None:
28
+ self.settings = settings or TestRailSettings.from_env()
29
+
30
+ @property
31
+ def base_url(self) -> str:
32
+ return self.settings.url.rstrip("/")
33
+
34
+ def suite_url(self, suite_id: int) -> str:
35
+ return f"{self.base_url}/index.php?/suites/view/{suite_id}"
36
+
37
+ def _api_url(self, endpoint: str) -> str:
38
+ return f"{self.base_url}/index.php?/api/v2/{endpoint.lstrip('/')}"
39
+
40
+ async def request(
41
+ self, method: str, endpoint: str, data: dict[str, Any] | None = None
42
+ ) -> dict[str, Any] | list[Any]:
43
+ async with httpx.AsyncClient(timeout=self.settings.timeout_seconds) as client:
44
+ response = await client.request(
45
+ method,
46
+ self._api_url(endpoint),
47
+ auth=(self.settings.username, self.settings.api_key),
48
+ json=data,
49
+ headers={"Content-Type": "application/json"},
50
+ )
51
+ response.raise_for_status()
52
+ if not response.content:
53
+ return {}
54
+ result = response.json()
55
+ if not isinstance(result, (dict, list)):
56
+ raise RuntimeError("TestRail returned an unexpected response")
57
+ return result
58
+
59
+ async def get_case_types(self) -> list[CaseType]:
60
+ response = await self.request("GET", "get_case_types")
61
+ return _CaseTypesResponse.model_validate(response).root
62
+
63
+ async def get_templates(self) -> list[Template]:
64
+ response = await self.request(
65
+ "GET", f"get_templates/{self.settings.project_id}"
66
+ )
67
+ return _TemplatesResponse.model_validate(response).root
68
+
69
+ async def get_statuses(self) -> list[Status]:
70
+ response = await self.request("GET", "get_statuses")
71
+ return _StatusesResponse.model_validate(response).root
72
+
73
+ async def add_suite(self, name: str) -> Suite:
74
+ response = await self.request(
75
+ "POST",
76
+ f"add_suite/{self.settings.project_id}",
77
+ {"name": name},
78
+ )
79
+ return Suite.model_validate(response)
80
+
81
+ async def add_section(self, suite_id: int, name: str) -> Section:
82
+ response = await self.request(
83
+ "POST",
84
+ f"add_section/{self.settings.project_id}",
85
+ {"suite_id": suite_id, "name": name},
86
+ )
87
+ return Section.model_validate(response)
88
+
89
+ async def add_case(
90
+ self,
91
+ section_id: int,
92
+ *,
93
+ title: str,
94
+ type_id: int,
95
+ template_id: int,
96
+ steps: list[CaseStep],
97
+ preconditions: str | None = None,
98
+ labels: list[str] | None = None,
99
+ ) -> Case:
100
+ payload: dict[str, Any] = {
101
+ "title": title,
102
+ "type_id": type_id,
103
+ "template_id": template_id,
104
+ "custom_steps_separated": [step.model_dump() for step in steps],
105
+ }
106
+ if preconditions:
107
+ payload["custom_preconds"] = preconditions
108
+ if labels:
109
+ payload["labels"] = labels
110
+ response = await self.request("POST", f"add_case/{section_id}", payload)
111
+ return Case.model_validate(response)
112
+
113
+ async def add_run(
114
+ self,
115
+ *,
116
+ suite_id: int,
117
+ case_ids: list[int],
118
+ name: str,
119
+ description: str | None = None,
120
+ ) -> Run:
121
+ payload: dict[str, Any] = {
122
+ "name": name,
123
+ "suite_id": suite_id,
124
+ "include_all": False,
125
+ "case_ids": case_ids,
126
+ }
127
+ if description:
128
+ payload["description"] = description
129
+ response = await self.request(
130
+ "POST",
131
+ f"add_run/{self.settings.project_id}",
132
+ payload,
133
+ )
134
+ return Run.model_validate(response)
135
+
136
+ async def add_results_for_cases(
137
+ self, run_id: int, results: list[CaseResult]
138
+ ) -> list[Result]:
139
+ response = await self.request(
140
+ "POST",
141
+ f"add_results_for_cases/{run_id}",
142
+ {"results": [result.model_dump() for result in results]},
143
+ )
144
+ return _ResultsResponse.model_validate(response).root
@@ -0,0 +1,22 @@
1
+ """Configuration for :class:`TestRailClient`."""
2
+
3
+ from typing import Annotated
4
+
5
+ from pydantic import BaseModel, Field
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+
9
+ class TestRailSettings(BaseModel):
10
+ username: Annotated[str, Field(min_length=1)]
11
+ api_key: Annotated[str, Field(min_length=1)]
12
+ project_id: int
13
+ url: str = "https://mozilla.testrail.io"
14
+ timeout_seconds: int = 30
15
+
16
+ @classmethod
17
+ def from_env(cls) -> TestRailSettings:
18
+ return _TestRailEnvSettings()
19
+
20
+
21
+ class _TestRailEnvSettings(TestRailSettings, BaseSettings):
22
+ model_config = SettingsConfigDict(env_prefix="TESTRAIL_", extra="ignore")
@@ -0,0 +1,89 @@
1
+ """Typed TestRail domain models used by the client."""
2
+
3
+ from pydantic import BaseModel, ConfigDict, RootModel
4
+
5
+
6
+ class _Model(BaseModel):
7
+ model_config = ConfigDict(extra="ignore")
8
+
9
+
10
+ class CaseType(_Model):
11
+ """A test case type configured in TestRail."""
12
+
13
+ id: int
14
+ name: str
15
+
16
+
17
+ class Template(_Model):
18
+ """A test case template configured in TestRail."""
19
+
20
+ id: int
21
+ name: str
22
+
23
+
24
+ class Status(_Model):
25
+ """A test result status configured in TestRail."""
26
+
27
+ id: int
28
+ name: str
29
+
30
+
31
+ class Suite(_Model):
32
+ """A test suite created in TestRail."""
33
+
34
+ id: int
35
+
36
+
37
+ class Section(_Model):
38
+ """A section created inside a TestRail test suite."""
39
+
40
+ id: int
41
+
42
+
43
+ class Case(_Model):
44
+ """A test case created in TestRail."""
45
+
46
+ id: int
47
+
48
+
49
+ class Run(_Model):
50
+ """A test run created in TestRail."""
51
+
52
+ id: int
53
+
54
+
55
+ class Result(_Model):
56
+ """A test result recorded in TestRail."""
57
+
58
+ id: int
59
+
60
+
61
+ class CaseStep(_Model):
62
+ """One step of a test case, with its expected outcome."""
63
+
64
+ content: str
65
+ expected: str = ""
66
+
67
+
68
+ class CaseResult(_Model):
69
+ """A result to record for one test case in a run."""
70
+
71
+ case_id: int
72
+ status_id: int
73
+ comment: str = ""
74
+
75
+
76
+ class _CaseTypesResponse(RootModel[list[CaseType]]):
77
+ pass
78
+
79
+
80
+ class _TemplatesResponse(RootModel[list[Template]]):
81
+ pass
82
+
83
+
84
+ class _StatusesResponse(RootModel[list[Status]]):
85
+ pass
86
+
87
+
88
+ class _ResultsResponse(RootModel[list[Result]]):
89
+ pass
@@ -0,0 +1,297 @@
1
+ """Tests for the shared TestRail client."""
2
+
3
+ import httpx
4
+ import pytest
5
+ from pydantic import ValidationError
6
+ from testrail_client import CaseResult, CaseStep, CaseType, Suite
7
+ from testrail_client import TestRailClient as Client
8
+ from testrail_client import TestRailSettings as Settings
9
+ from testrail_client import client as client_module
10
+
11
+
12
+ class _FakeResponse:
13
+ def __init__(self, payload=None, content: bytes | None = None):
14
+ self._payload = payload
15
+ self.content = b"{}" if content is None else content
16
+
17
+ def raise_for_status(self) -> None:
18
+ pass
19
+
20
+ def json(self):
21
+ return self._payload
22
+
23
+
24
+ def _settings(**kwargs) -> Settings:
25
+ defaults = {
26
+ "username": "qa@example.com",
27
+ "api_key": "secret",
28
+ "project_id": 73,
29
+ }
30
+ defaults.update(kwargs)
31
+ return Settings(**defaults)
32
+
33
+
34
+ def _client(**kwargs) -> Client:
35
+ return Client(_settings(**kwargs))
36
+
37
+
38
+ def _capture_request(monkeypatch, payload) -> dict:
39
+ captured: dict = {}
40
+
41
+ class _FakeAsyncClient:
42
+ def __init__(self, timeout=None):
43
+ captured["timeout"] = timeout
44
+
45
+ async def __aenter__(self):
46
+ return self
47
+
48
+ async def __aexit__(self, *exc):
49
+ return False
50
+
51
+ async def request(self, method, url, **kwargs):
52
+ captured.update(method=method, url=url, **kwargs)
53
+ return _FakeResponse(payload(url) if callable(payload) else payload)
54
+
55
+ monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)
56
+ return captured
57
+
58
+
59
+ async def test_request_uses_basic_authentication(monkeypatch):
60
+ captured = _capture_request(monkeypatch, {"id": 10})
61
+
62
+ result = await _client(url="https://testrail.example/").request(
63
+ "POST", "add_suite/73", {"name": "Suite"}
64
+ )
65
+
66
+ assert result == {"id": 10}
67
+ assert captured["url"] == (
68
+ "https://testrail.example/index.php?/api/v2/add_suite/73"
69
+ )
70
+ assert captured["auth"] == ("qa@example.com", "secret")
71
+ assert captured["json"] == {"name": "Suite"}
72
+ assert captured["timeout"] == 30
73
+
74
+
75
+ async def test_request_allows_empty_response(monkeypatch):
76
+ captured: dict = {}
77
+
78
+ class _FakeAsyncClient:
79
+ def __init__(self, timeout=None):
80
+ captured["timeout"] = timeout
81
+
82
+ async def __aenter__(self):
83
+ return self
84
+
85
+ async def __aexit__(self, *exc):
86
+ return False
87
+
88
+ async def request(self, method, url, **kwargs):
89
+ return _FakeResponse(content=b"")
90
+
91
+ monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)
92
+
93
+ assert await _client().request("POST", "add_suite/73") == {}
94
+
95
+
96
+ async def test_request_requires_json_object_or_array(monkeypatch):
97
+ _capture_request(monkeypatch, "not-json-object")
98
+
99
+ with pytest.raises(RuntimeError, match="unexpected response"):
100
+ await _client().request("GET", "get_projects")
101
+
102
+
103
+ async def test_endpoint_response_is_typed(monkeypatch):
104
+ _capture_request(
105
+ monkeypatch,
106
+ [{"id": "6", "name": "Functional", "future": True}],
107
+ )
108
+
109
+ result = await _client().get_case_types()
110
+
111
+ assert result == [CaseType(id=6, name="Functional")]
112
+
113
+
114
+ async def test_single_resource_response_is_typed(monkeypatch):
115
+ _capture_request(monkeypatch, {"id": "10", "name": "Suite"})
116
+
117
+ assert await _client().add_suite("Suite") == Suite(id=10)
118
+
119
+
120
+ async def test_endpoint_response_is_validated(monkeypatch):
121
+ _capture_request(monkeypatch, [{"name": "Functional"}])
122
+
123
+ with pytest.raises(ValidationError):
124
+ await _client().get_case_types()
125
+
126
+
127
+ @pytest.mark.parametrize(
128
+ ("method_name", "response"),
129
+ [
130
+ ("get_case_types", {"case_types": [{"id": 1, "name": "Functional"}]}),
131
+ ("get_templates", {"templates": [{"id": 1, "name": "Steps"}]}),
132
+ ("get_statuses", {"statuses": [{"id": 1, "name": "passed"}]}),
133
+ ("add_results_for_cases", {"results": [{"id": 1}]}),
134
+ ],
135
+ )
136
+ async def test_list_endpoints_reject_unexpected_response_shape(
137
+ monkeypatch, method_name, response
138
+ ):
139
+ _capture_request(monkeypatch, response)
140
+ client = _client()
141
+
142
+ with pytest.raises(ValidationError):
143
+ if method_name == "add_results_for_cases":
144
+ await client.add_results_for_cases(1, [])
145
+ else:
146
+ await getattr(client, method_name)()
147
+
148
+
149
+ async def test_endpoint_wrappers(monkeypatch):
150
+ captured = _capture_request(
151
+ monkeypatch,
152
+ lambda url: (
153
+ [{"id": 10, "name": "Functional"}]
154
+ if "/get_" in url or "/add_results_for_cases/" in url
155
+ else {"id": 10}
156
+ ),
157
+ )
158
+ client = _client()
159
+
160
+ await client.get_case_types()
161
+ assert captured["method"] == "GET"
162
+ assert captured["url"].endswith("/get_case_types")
163
+
164
+ await client.get_templates()
165
+ assert captured["url"].endswith("/get_templates/73")
166
+
167
+ await client.get_statuses()
168
+ assert captured["url"].endswith("/get_statuses")
169
+
170
+ await client.add_suite("Suite")
171
+ assert captured["url"].endswith("/add_suite/73")
172
+ assert captured["json"] == {"name": "Suite"}
173
+
174
+ await client.add_section(10, "Cases")
175
+ assert captured["url"].endswith("/add_section/73")
176
+ assert captured["json"] == {"suite_id": 10, "name": "Cases"}
177
+
178
+ await client.add_case(
179
+ 20,
180
+ title="Case",
181
+ type_id=6,
182
+ template_id=2,
183
+ steps=[CaseStep(content="Open", expected="It opens")],
184
+ preconditions="A PDF is available.",
185
+ labels=["AI Generated"],
186
+ )
187
+ assert captured["url"].endswith("/add_case/20")
188
+ assert captured["json"] == {
189
+ "title": "Case",
190
+ "type_id": 6,
191
+ "template_id": 2,
192
+ "custom_steps_separated": [{"content": "Open", "expected": "It opens"}],
193
+ "custom_preconds": "A PDF is available.",
194
+ "labels": ["AI Generated"],
195
+ }
196
+
197
+ await client.add_run(suite_id=10, case_ids=[101], name="Run", description="Summary")
198
+ assert captured["url"].endswith("/add_run/73")
199
+ assert captured["json"] == {
200
+ "name": "Run",
201
+ "suite_id": 10,
202
+ "include_all": False,
203
+ "case_ids": [101],
204
+ "description": "Summary",
205
+ }
206
+
207
+ await client.add_results_for_cases(
208
+ 301, [CaseResult(case_id=101, status_id=1, comment="ok")]
209
+ )
210
+ assert captured["url"].endswith("/add_results_for_cases/301")
211
+ assert captured["json"] == {
212
+ "results": [{"case_id": 101, "status_id": 1, "comment": "ok"}]
213
+ }
214
+
215
+
216
+ async def test_optional_fields_are_left_out_when_empty(monkeypatch):
217
+ captured = _capture_request(monkeypatch, {"id": 10})
218
+ client = _client()
219
+
220
+ await client.add_case(20, title="Case", type_id=6, template_id=2, steps=[])
221
+ assert captured["json"] == {
222
+ "title": "Case",
223
+ "type_id": 6,
224
+ "template_id": 2,
225
+ "custom_steps_separated": [],
226
+ }
227
+
228
+ await client.add_run(suite_id=10, case_ids=[101], name="Run", description="")
229
+ assert "description" not in captured["json"]
230
+
231
+
232
+ def test_suite_url_default_base():
233
+ assert (
234
+ _client().suite_url(42)
235
+ == "https://mozilla.testrail.io/index.php?/suites/view/42"
236
+ )
237
+
238
+
239
+ def test_suite_url_injected_base():
240
+ assert (
241
+ _client(url="https://testrail.example/").suite_url(42)
242
+ == "https://testrail.example/index.php?/suites/view/42"
243
+ )
244
+
245
+
246
+ def test_from_env_reads_environment(monkeypatch):
247
+ monkeypatch.setenv("TESTRAIL_USERNAME", "qa@example.com")
248
+ monkeypatch.setenv("TESTRAIL_API_KEY", "secret")
249
+ monkeypatch.setenv("TESTRAIL_PROJECT_ID", "73")
250
+ monkeypatch.setenv("TESTRAIL_URL", "https://testrail.env.example")
251
+
252
+ settings = Settings.from_env()
253
+
254
+ assert isinstance(settings, Settings)
255
+ assert settings.username == "qa@example.com"
256
+ assert settings.api_key == "secret"
257
+ assert settings.project_id == 73
258
+ assert settings.url == "https://testrail.env.example"
259
+
260
+
261
+ def test_missing_required_env_rejected(monkeypatch):
262
+ monkeypatch.delenv("TESTRAIL_USERNAME", raising=False)
263
+ monkeypatch.delenv("TESTRAIL_API_KEY", raising=False)
264
+ monkeypatch.delenv("TESTRAIL_PROJECT_ID", raising=False)
265
+
266
+ with pytest.raises(ValidationError):
267
+ Settings.from_env()
268
+
269
+
270
+ def test_invalid_project_id_rejected():
271
+ with pytest.raises(ValidationError):
272
+ Settings(
273
+ username="qa@example.com",
274
+ api_key="secret",
275
+ project_id="grave-yard",
276
+ )
277
+
278
+
279
+ async def test_custom_timeout_is_passed(monkeypatch):
280
+ captured = _capture_request(monkeypatch, {})
281
+ await _client(timeout_seconds=5).request("GET", "get_projects")
282
+ assert captured["timeout"] == 5
283
+
284
+
285
+ def test_defaults_from_env_when_no_settings(monkeypatch):
286
+ monkeypatch.setenv("TESTRAIL_USERNAME", "qa@example.com")
287
+ monkeypatch.setenv("TESTRAIL_API_KEY", "secret")
288
+ monkeypatch.setenv("TESTRAIL_PROJECT_ID", "73")
289
+
290
+ client = Client()
291
+
292
+ assert client.settings.username == "qa@example.com"
293
+ assert client.settings.project_id == 73
294
+
295
+
296
+ def test_client_uses_httpx():
297
+ assert client_module.httpx is httpx