bugzilla-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,8 @@
1
+ Metadata-Version: 2.5
2
+ Name: bugzilla-client
3
+ Version: 0.1.0
4
+ Summary: Small shared Bugzilla REST client (httpx-based)
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: httpx>=0.26.0
7
+ Requires-Dist: pydantic-settings>=2.1.0
8
+ Requires-Dist: tenacity>=9.1.0
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,4 @@
1
+ from bugzilla_client.client import BugzillaClient, BugzillaError, BugzillaResponse
2
+ from bugzilla_client.config import BugzillaSettings
3
+
4
+ __all__ = ["BugzillaClient", "BugzillaError", "BugzillaResponse", "BugzillaSettings"]
@@ -0,0 +1,391 @@
1
+ """Small shared Bugzilla REST client.
2
+
3
+ A minimal ``httpx``-based client for the handful of calls hackbot makes, in
4
+ place of the mix of ``requests`` and raw ``httpx`` used today. It
5
+ deliberately avoids ``libmozdata``'s bulk, futures-oriented client, which suits
6
+ the bugbug data pipelines but not single-bug reads and writes from an event
7
+ loop.
8
+
9
+ Config is injected: pass a :class:`BugzillaSettings`, or let the client load
10
+ one from the environment (via ``BugzillaSettings.from_env``) when none is
11
+ provided. The API is asynchronous.
12
+
13
+ The client reuses one connection pool across requests. Close it when done,
14
+ either with ``async with`` or by calling :meth:`BugzillaClient.close`.
15
+ """
16
+
17
+ import base64
18
+ import logging
19
+ from collections.abc import Collection
20
+ from dataclasses import dataclass
21
+ from datetime import datetime
22
+ from types import TracebackType
23
+ from typing import Any, Self
24
+
25
+ import httpx
26
+ from tenacity import (
27
+ RetryCallState,
28
+ before_sleep_log,
29
+ retry,
30
+ stop_after_attempt,
31
+ wait_exponential_jitter,
32
+ )
33
+
34
+ from bugzilla_client.config import BugzillaSettings
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+
39
+ class BugzillaError(Exception):
40
+ """Bugzilla rejected a request, or answered with something that is not JSON.
41
+
42
+ ``code`` is Bugzilla's own error code (e.g. 101 "bug does not exist", 102
43
+ "access denied") when the response carried one.
44
+ """
45
+
46
+ def __init__(
47
+ self, message: str, *, code: int | None = None, status: int | None = None
48
+ ) -> None:
49
+ super().__init__(message)
50
+ self.message = message
51
+ self.code = code
52
+ self.status = status
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class BugzillaResponse:
57
+ """What a resource method returns; ``data`` is Bugzilla's JSON body.
58
+
59
+ A wrapper rather than the bare body, so typed results can be added later
60
+ without breaking callers.
61
+ """
62
+
63
+ data: dict[str, Any]
64
+
65
+
66
+ def _should_retry(state: RetryCallState) -> bool:
67
+ """Tenacity's retry check for ``request``: is the failed call worth resending?"""
68
+ exc = state.outcome.exception() if state.outcome else None
69
+ if exc is None:
70
+ return False
71
+ # ``request(self, method, path, /, ...)``: ``method`` is always positional.
72
+ is_read = state.args[1].upper() == "GET"
73
+ return _is_transient(exc, is_read=is_read)
74
+
75
+
76
+ def _is_transient(exc: BaseException, *, is_read: bool) -> bool:
77
+ """Whether a failed request is worth sending again.
78
+
79
+ A write is only resent when Bugzilla surely did not apply it: a rate limit,
80
+ or a connection that was never made. After a gateway error or a dropped
81
+ response the write may have landed, and resending could post a comment
82
+ twice.
83
+ """
84
+ if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
85
+ return True
86
+ if isinstance(exc, httpx.TransportError):
87
+ return is_read
88
+ # Rate limiting and gateway failures: the request was not processed.
89
+ if isinstance(exc, BugzillaError) and exc.status in {429, 502, 503, 504}:
90
+ return is_read or exc.status == 429
91
+ return False
92
+
93
+
94
+ class BugzillaClient:
95
+ def __init__(self, settings: BugzillaSettings | None = None) -> None:
96
+ self._settings = settings or BugzillaSettings.from_env()
97
+ headers = {
98
+ "X-Bugzilla-API-Key": self._settings.api_key,
99
+ "User-Agent": self._settings.user_agent,
100
+ }
101
+ if self._settings.edge_key:
102
+ headers["Mozilla-Edge-Key"] = self._settings.edge_key
103
+ self._http = httpx.AsyncClient(
104
+ base_url=f"{self.api_url}/",
105
+ headers=headers,
106
+ timeout=self._settings.timeout_seconds,
107
+ )
108
+ # One resource per section from the REST API docs.
109
+ self.bugs = _Bugs(self)
110
+ self.comments = _Comments(self)
111
+ self.attachments = _Attachments(self)
112
+ self.users = _Users(self)
113
+
114
+ async def close(self) -> None:
115
+ await self._http.aclose()
116
+
117
+ async def __aenter__(self) -> Self:
118
+ return self
119
+
120
+ async def __aexit__(
121
+ self,
122
+ exc_type: type[BaseException] | None,
123
+ exc: BaseException | None,
124
+ tb: TracebackType | None,
125
+ ) -> None:
126
+ await self.close()
127
+
128
+ @property
129
+ def api_url(self) -> str:
130
+ return self._settings.api_url.rstrip("/")
131
+
132
+ def bug_url(self, bug_id: int) -> str:
133
+ site = self.api_url.removesuffix("/rest")
134
+ return f"{site}/show_bug.cgi?id={bug_id}"
135
+
136
+ @retry(
137
+ retry=_should_retry,
138
+ stop=stop_after_attempt(4),
139
+ wait=wait_exponential_jitter(max=15),
140
+ before_sleep=before_sleep_log(log, logging.WARNING),
141
+ reraise=True,
142
+ )
143
+ async def request(
144
+ self,
145
+ method: str,
146
+ path: str,
147
+ /,
148
+ *,
149
+ params: dict[str, Any] | None = None,
150
+ json: dict[str, Any] | None = None,
151
+ ) -> dict[str, Any]:
152
+ """Call a REST endpoint (relative to ``api_url``) and return its JSON body.
153
+
154
+ Rate limits and gateway errors are retried with exponential backoff.
155
+ Reads are also retried on network errors; writes only when the
156
+ connection was never made, so a comment is never posted twice.
157
+
158
+ Raises :class:`BugzillaError` for a Bugzilla-level error or a non-JSON
159
+ answer (e.g. a misconfigured URL serving HTML).
160
+ """
161
+ response = await self._http.request(method, path, params=params, json=json)
162
+ return _parse(response)
163
+
164
+
165
+ class _Resource:
166
+ def __init__(self, client: BugzillaClient) -> None:
167
+ self._client = client
168
+
169
+
170
+ class _Bugs(_Resource):
171
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/bug.html."""
172
+
173
+ async def get(
174
+ self, ids: Collection[int], *, include_fields: Collection[str] | None = None
175
+ ) -> BugzillaResponse:
176
+ """Fetch bugs by id in one request.
177
+
178
+ Bugs the API key cannot see are left out of the result rather than
179
+ failing the request, so callers must not assume one bug per id.
180
+ """
181
+ if not ids:
182
+ raise ValueError("ids must not be empty")
183
+ params: dict[str, Any] = {"id": ",".join(str(i) for i in ids)}
184
+ if include_fields:
185
+ params["include_fields"] = ",".join(include_fields)
186
+ result = await self._client.request("GET", "bug", params=params)
187
+ return BugzillaResponse(result)
188
+
189
+ async def search(
190
+ self,
191
+ params: dict[str, Any],
192
+ *,
193
+ include_fields: Collection[str] | None = None,
194
+ ) -> BugzillaResponse:
195
+ """Find bugs matching search criteria (``GET /bug``).
196
+
197
+ ``params`` are Bugzilla search fields, e.g.
198
+ ``{"product": "Core", "status": "NEW", "keywords": "regression"}``.
199
+ Results are capped by the server (10,000 by default); page with
200
+ ``limit`` and ``offset``. Use :meth:`get` when the ids are known.
201
+ ``include_fields`` overrides the same key in ``params``.
202
+ """
203
+ if include_fields:
204
+ params = {**params, "include_fields": ",".join(include_fields)}
205
+ result = await self._client.request("GET", "bug", params=params)
206
+ return BugzillaResponse(result)
207
+
208
+ async def create(self, fields: dict[str, Any]) -> BugzillaResponse:
209
+ """File a bug; Bugzilla answers ``{"id": ...}``."""
210
+ result = await self._client.request("POST", "bug", json=fields)
211
+ return BugzillaResponse(result)
212
+
213
+ async def update(self, bug_id: int, changes: dict[str, Any]) -> BugzillaResponse:
214
+ """Apply field changes and/or a comment in one ``PUT /bug/{id}``.
215
+
216
+ Bugzilla applies the whole body as a single transaction (one bugmail,
217
+ one history entry). Each entry in the answer's ``bugs`` lists what
218
+ actually changed in ``changes``; empty when every field already had
219
+ its value (a comment is not a change).
220
+
221
+ Updates one bug only: do not pass ``ids`` in ``changes``.
222
+ """
223
+ result = await self._client.request("PUT", f"bug/{bug_id}", json=changes)
224
+ return BugzillaResponse(result)
225
+
226
+
227
+ class _Comments(_Resource):
228
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/comment.html."""
229
+
230
+ async def get(
231
+ self,
232
+ *,
233
+ bug_ids: Collection[int] = (),
234
+ comment_ids: Collection[int] = (),
235
+ new_since: datetime | None = None,
236
+ include_fields: Collection[str] | None = None,
237
+ skip_private: bool = False,
238
+ ) -> BugzillaResponse:
239
+ """Comments by bug and/or by comment id, fetched in one request.
240
+
241
+ Bugzilla answers ``{"bugs": {bug_id: {"comments": [...]}}, "comments":
242
+ {comment_id: comment}}``, keyed by id strings. ``new_since`` only filters the
243
+ comments of ``bug_ids``; ``skip_private`` skips bugs the API key cannot
244
+ see instead of failing.
245
+ """
246
+ if not bug_ids and not comment_ids:
247
+ raise ValueError("bug_ids or comment_ids must not be empty")
248
+ # The path takes one id, the rest go in the query. Ids are repeated
249
+ # (``ids=2&ids=3``): Bugzilla rejects comma-joined ids here.
250
+ params: dict[str, Any]
251
+ if bug_ids:
252
+ first, *rest = bug_ids
253
+ path = f"bug/{first}/comment"
254
+ params = {"ids": rest, "comment_ids": list(comment_ids)}
255
+ else:
256
+ first, *rest = comment_ids
257
+ path = f"bug/comment/{first}"
258
+ params = {"comment_ids": rest}
259
+ if new_since:
260
+ params["new_since"] = new_since.isoformat()
261
+ if include_fields:
262
+ params["include_fields"] = ",".join(include_fields)
263
+ if skip_private:
264
+ params["skip_private"] = 1
265
+ result = await self._client.request("GET", path, params=params)
266
+ return BugzillaResponse(result)
267
+
268
+
269
+ class _Attachments(_Resource):
270
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/attachment.html."""
271
+
272
+ async def get(
273
+ self,
274
+ *,
275
+ bug_ids: Collection[int] = (),
276
+ attachment_ids: Collection[int] = (),
277
+ include_data: bool = False,
278
+ ) -> BugzillaResponse:
279
+ """Attachments by bug and/or by attachment id, fetched in one request.
280
+
281
+ Bugzilla answers ``{"bugs": {bug_id: [attachment, ...]}, "attachments":
282
+ {attachment_id: attachment}}``, keyed by id strings, without the
283
+ file content unless ``include_data``. BMO leaves unknown attachment
284
+ ids out of the result rather than failing.
285
+ """
286
+ if not bug_ids and not attachment_ids:
287
+ raise ValueError("bug_ids or attachment_ids must not be empty")
288
+ # The path takes one id, the rest go in the query. Ids are repeated
289
+ # (``ids=2&ids=3``): Bugzilla rejects comma-joined ids here.
290
+ if bug_ids:
291
+ first, *rest = bug_ids
292
+ path = f"bug/{first}/attachment"
293
+ params: dict[str, Any] = {
294
+ "ids": rest,
295
+ "attachment_ids": list(attachment_ids),
296
+ }
297
+ else:
298
+ first, *rest = attachment_ids
299
+ path = f"bug/attachment/{first}"
300
+ params = {"attachment_ids": rest}
301
+ if not include_data:
302
+ params["exclude_fields"] = "data"
303
+ result = await self._client.request("GET", path, params=params)
304
+ return BugzillaResponse(result)
305
+
306
+ async def create(
307
+ self, bug_id: int, data: bytes, fields: dict[str, Any]
308
+ ) -> BugzillaResponse:
309
+ """Attach a file to a bug.
310
+
311
+ Bugzilla answers ``{"attachments": {attachment_id: attachment}}``.
312
+
313
+ ``fields`` are the other Create Attachment fields, e.g. ``file_name``,
314
+ ``summary``, ``content_type``, ``is_patch`` or ``comment``. ``data`` is
315
+ the raw file content; it is base64-encoded here.
316
+ """
317
+ body = {
318
+ **fields,
319
+ "ids": [bug_id],
320
+ "data": base64.b64encode(data).decode("ascii"),
321
+ }
322
+ result = await self._client.request(
323
+ "POST", f"bug/{bug_id}/attachment", json=body
324
+ )
325
+ return BugzillaResponse(result)
326
+
327
+
328
+ class _Users(_Resource):
329
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/user.html."""
330
+
331
+ async def get(
332
+ self,
333
+ *,
334
+ ids: Collection[int] = (),
335
+ names: Collection[str] = (),
336
+ match: Collection[str] = (),
337
+ limit: int | None = None,
338
+ group_ids: Collection[int] = (),
339
+ groups: Collection[str] = (),
340
+ include_disabled: bool = False,
341
+ permissive: bool = False,
342
+ ) -> BugzillaResponse:
343
+ """Users by id, login name, or a ``match`` search.
344
+
345
+ ``limit`` and ``include_disabled`` only apply to ``match``;
346
+ ``permissive`` reports unknown ``names`` in ``faults`` instead of
347
+ failing. ``group_ids`` and ``groups`` keep only members of any of them.
348
+ """
349
+ if not ids and not names and not match:
350
+ raise ValueError("ids, names or match must not be empty")
351
+ # Lists are repeated (``names=a&names=b``): Bugzilla rejects commas here.
352
+ params: dict[str, Any] = {
353
+ "ids": list(ids),
354
+ "names": list(names),
355
+ "match": list(match),
356
+ "group_ids": list(group_ids),
357
+ "groups": list(groups),
358
+ }
359
+ if limit is not None:
360
+ params["limit"] = limit
361
+ if include_disabled:
362
+ params["include_disabled"] = 1
363
+ if permissive:
364
+ params["permissive"] = 1
365
+ result = await self._client.request("GET", "user", params=params)
366
+ return BugzillaResponse(result)
367
+
368
+
369
+ def _parse(response: httpx.Response) -> dict[str, Any]:
370
+ """Return the JSON body, raising :class:`BugzillaError` for any error.
371
+
372
+ Bugzilla reports errors as ``{"error": true, "code": ..., "message": ...}``;
373
+ anything else that is not a JSON success (e.g. a proxy's HTML error page)
374
+ is reported by its HTTP status.
375
+ """
376
+ unexpected = (
377
+ f"Unexpected Bugzilla response: HTTP {response.status_code} "
378
+ f"for {response.request.url}"
379
+ )
380
+ try:
381
+ data = response.json()
382
+ except ValueError as exc:
383
+ raise BugzillaError(unexpected, status=response.status_code) from exc
384
+
385
+ if isinstance(data, dict) and data.get("error"):
386
+ raise BugzillaError(
387
+ data["message"], code=data["code"], status=response.status_code
388
+ )
389
+ if response.is_error or not isinstance(data, dict):
390
+ raise BugzillaError(unexpected, status=response.status_code)
391
+ return data
@@ -0,0 +1,40 @@
1
+ """Configuration for :class:`BugzillaClient`.
2
+
3
+ ``BugzillaSettings`` is a plain, validated config model with no env I/O, so it
4
+ can be embedded in a larger settings object without triggering a second
5
+ environment parse. Use :meth:`BugzillaSettings.from_env` for standalone,
6
+ env-driven config (``BUGZILLA_API_URL``, ``BUGZILLA_API_KEY``, ...). It also
7
+ accepts the site root as ``BUGZILLA_URL`` when ``BUGZILLA_API_URL`` is unset.
8
+ """
9
+
10
+ from importlib.metadata import version
11
+ from typing import Annotated, Self
12
+
13
+ from pydantic import BaseModel, Field, model_validator
14
+ from pydantic_settings import BaseSettings, SettingsConfigDict
15
+
16
+
17
+ class BugzillaSettings(BaseModel):
18
+ # Bugzilla generates API keys as 40 random letters and digits.
19
+ api_key: Annotated[str, Field(min_length=40, max_length=40)]
20
+ # The REST API base, used as is for API calls.
21
+ api_url: str = "https://bugzilla.mozilla.org/rest"
22
+ timeout_seconds: float = 30
23
+ edge_key: str | None = None
24
+ user_agent: str = f"Bugbug-BugzillaClient/{version('bugzilla-client')}"
25
+
26
+ @classmethod
27
+ def from_env(cls) -> BugzillaSettings:
28
+ return _BugzillaEnvSettings()
29
+
30
+
31
+ class _BugzillaEnvSettings(BugzillaSettings, BaseSettings):
32
+ model_config = SettingsConfigDict(env_prefix="BUGZILLA_", extra="ignore")
33
+ # The site root, as older configs set it; used when BUGZILLA_API_URL is unset.
34
+ url: str | None = None
35
+
36
+ @model_validator(mode="after")
37
+ def _api_url_from_site_root(self) -> Self:
38
+ if "api_url" not in self.model_fields_set and self.url:
39
+ self.api_url = self.url.rstrip("/") + "/rest"
40
+ return self
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "bugzilla-client"
3
+ dynamic = ["version"]
4
+ description = "Small shared Bugzilla REST client (httpx-based)"
5
+ requires-python = ">=3.14"
6
+ dependencies = [
7
+ "httpx>=0.26.0",
8
+ "pydantic-settings>=2.1.0",
9
+ "tenacity>=9.1.0",
10
+ ]
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.version]
17
+ path = "VERSION"
18
+ pattern = "(?P<version>.+)"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["bugzilla_client"]
22
+
23
+ [tool.pytest.ini_options]
24
+ asyncio_mode = "auto"
25
+ testpaths = ["tests"]
@@ -0,0 +1,276 @@
1
+ """Tests for the shared Bugzilla REST client."""
2
+
3
+ import base64
4
+ import json
5
+
6
+ import httpx
7
+ import pytest
8
+ from bugzilla_client import BugzillaClient, BugzillaError, BugzillaSettings
9
+ from bugzilla_client import client as client_module
10
+ from tenacity import wait_none
11
+
12
+
13
+ @pytest.fixture(autouse=True)
14
+ def _no_retry_wait(monkeypatch):
15
+ """Retry at once instead of backing off, to keep the tests fast."""
16
+ monkeypatch.setattr(BugzillaClient.request.retry, "wait", wait_none())
17
+
18
+
19
+ @pytest.fixture
20
+ async def bugzilla(monkeypatch):
21
+ """Build a client whose HTTP calls are answered by ``handler``, not the network."""
22
+ clients: list[BugzillaClient] = []
23
+
24
+ def make(handler, **settings) -> BugzillaClient:
25
+ real_async_client = httpx.AsyncClient
26
+
27
+ def fake_async_client(**kwargs):
28
+ return real_async_client(transport=httpx.MockTransport(handler), **kwargs)
29
+
30
+ monkeypatch.setattr(client_module.httpx, "AsyncClient", fake_async_client)
31
+ settings.setdefault("api_key", VALID_KEY)
32
+ client = BugzillaClient(BugzillaSettings(**settings))
33
+ clients.append(client)
34
+ return client
35
+
36
+ yield make
37
+ for client in clients:
38
+ await client.close()
39
+
40
+
41
+ # A syntactically valid Bugzilla API key: 40 letters and digits.
42
+ VALID_KEY = "a" * 40
43
+
44
+
45
+ def _recorder(*responses: httpx.Response | Exception):
46
+ """A handler answering with ``responses`` in turn, recording each request."""
47
+ requests: list[httpx.Request] = []
48
+ queue = list(responses)
49
+
50
+ def handler(request: httpx.Request) -> httpx.Response:
51
+ requests.append(request)
52
+ answer = queue.pop(0)
53
+ if isinstance(answer, Exception):
54
+ raise answer
55
+ return answer
56
+
57
+ return handler, requests
58
+
59
+
60
+ def _no_changes(bug_id: int) -> dict:
61
+ """A ``PUT /bug/{id}`` answer for an update that changed no field."""
62
+ return {"bugs": [{"id": bug_id, "changes": {}}]}
63
+
64
+
65
+ def _comment(id: int, bug_id: int) -> dict:
66
+ return {
67
+ "id": id,
68
+ "bug_id": bug_id,
69
+ "count": 0,
70
+ "text": "hello",
71
+ "creator": "a@example.com",
72
+ "creation_time": "2026-01-01T00:00:00Z",
73
+ }
74
+
75
+
76
+ def _attachment(id: int, bug_id: int, **extra) -> dict:
77
+ return {
78
+ "id": id,
79
+ "bug_id": bug_id,
80
+ "file_name": "a.txt",
81
+ "summary": "a file",
82
+ "content_type": "text/plain",
83
+ **extra,
84
+ }
85
+
86
+
87
+ @pytest.mark.parametrize(
88
+ ("env", "api_url"),
89
+ [
90
+ (
91
+ {
92
+ "BUGZILLA_API_URL": "https://api.example.com/rest",
93
+ "BUGZILLA_URL": "https://site.example.com",
94
+ },
95
+ "https://api.example.com/rest",
96
+ ),
97
+ (
98
+ {"BUGZILLA_URL": "https://site.example.com/"},
99
+ "https://site.example.com/rest",
100
+ ),
101
+ ({}, "https://bugzilla.mozilla.org/rest"),
102
+ ],
103
+ ids=["api-url-wins", "site-root-fallback", "default"],
104
+ )
105
+ def test_from_env_reads_api_url_or_falls_back_to_site_root(monkeypatch, env, api_url):
106
+ monkeypatch.delenv("BUGZILLA_API_URL", raising=False)
107
+ monkeypatch.delenv("BUGZILLA_URL", raising=False)
108
+ monkeypatch.setenv("BUGZILLA_API_KEY", VALID_KEY)
109
+ for name, value in env.items():
110
+ monkeypatch.setenv(name, value)
111
+
112
+ assert BugzillaSettings.from_env().api_url == api_url
113
+
114
+
115
+ async def test_sends_auth_headers_and_uses_rest_base(bugzilla):
116
+ handler, requests = _recorder(httpx.Response(200, json={"version": "20260101.1"}))
117
+ client = bugzilla(
118
+ handler, api_url="https://bugzilla.example.com/rest", edge_key="edge"
119
+ )
120
+
121
+ assert await client.request("GET", "version") == {"version": "20260101.1"}
122
+
123
+ (request,) = requests
124
+ assert str(request.url) == "https://bugzilla.example.com/rest/version"
125
+ assert request.headers["X-Bugzilla-API-Key"] == VALID_KEY
126
+ assert request.headers["Mozilla-Edge-Key"] == "edge"
127
+ assert request.headers["User-Agent"].startswith("Bugbug-BugzillaClient/")
128
+
129
+
130
+ async def test_context_manager_closes_client():
131
+ async with BugzillaClient(BugzillaSettings(api_key=VALID_KEY)) as client:
132
+ pass
133
+ with pytest.raises(RuntimeError):
134
+ await client.request("GET", "version")
135
+
136
+
137
+ async def test_bugzilla_error_body_raises_with_code(bugzilla):
138
+ body = {"error": True, "code": 102, "message": "You are not authorized"}
139
+ handler, _ = _recorder(httpx.Response(401, json=body))
140
+ with pytest.raises(BugzillaError) as exc_info:
141
+ await bugzilla(handler).bugs.get([1])
142
+ assert exc_info.value.code == 102
143
+ assert exc_info.value.status == 401
144
+ assert "not authorized" in str(exc_info.value)
145
+
146
+
147
+ @pytest.mark.parametrize(
148
+ "response",
149
+ [
150
+ httpx.Response(200, text="<html>login</html>"),
151
+ httpx.Response(503, text="<html>Service down</html>"),
152
+ ],
153
+ ids=["html-success", "html-error-page"],
154
+ )
155
+ async def test_non_json_response_raises_with_status(bugzilla, response):
156
+ handler, _ = _recorder(response)
157
+ with pytest.raises(BugzillaError) as exc_info:
158
+ # A write, so the 503 is not retried.
159
+ await bugzilla(handler).bugs.update(1, {"status": "NEW"})
160
+ assert exc_info.value.status == response.status_code
161
+ assert f"HTTP {response.status_code}" in str(exc_info.value)
162
+
163
+
164
+ async def test_read_retries_on_rate_limit_then_succeeds(bugzilla):
165
+ handler, requests = _recorder(
166
+ httpx.Response(429),
167
+ httpx.Response(503),
168
+ httpx.Response(200, json={"version": "1"}),
169
+ )
170
+ assert await bugzilla(handler).request("GET", "version") == {"version": "1"}
171
+ assert len(requests) == 3
172
+
173
+
174
+ @pytest.mark.parametrize(
175
+ "failure",
176
+ [httpx.Response(503), httpx.ReadTimeout("slow")],
177
+ ids=["gateway-error", "read-timeout"],
178
+ )
179
+ async def test_write_not_retried_when_it_may_have_landed(failure, bugzilla):
180
+ # The PUT may have been applied; retrying could post the comment twice.
181
+ handler, requests = _recorder(failure, httpx.Response(200, json=_no_changes(1)))
182
+ with pytest.raises((BugzillaError, httpx.ReadTimeout)):
183
+ await bugzilla(handler).bugs.update(1, {"comment": {"body": "hi"}})
184
+ assert len(requests) == 1
185
+
186
+
187
+ async def test_bugs_get_sends_ids(bugzilla):
188
+ body = {"bugs": [{"id": 1, "summary": "one"}, {"id": 2, "summary": "two"}]}
189
+ handler, requests = _recorder(httpx.Response(200, json=body))
190
+
191
+ bugs = await bugzilla(handler).bugs.get([1, 2, 3], include_fields=["id", "summary"])
192
+
193
+ assert bugs.data == body
194
+ params = requests[0].url.params
195
+ assert params["id"] == "1,2,3"
196
+ assert params["include_fields"] == "id,summary"
197
+
198
+
199
+ async def test_comments_get_by_bugs_and_comment_ids_in_one_request(bugzilla):
200
+ body = {
201
+ "bugs": {
202
+ "1": {"comments": [_comment(10, 1)]},
203
+ "2": {"comments": [_comment(20, 2), _comment(21, 2)]},
204
+ "3": {"comments": []},
205
+ },
206
+ "comments": {"30": _comment(30, 4)},
207
+ }
208
+ handler, requests = _recorder(httpx.Response(200, json=body))
209
+
210
+ response = await bugzilla(handler).comments.get(bug_ids=[1, 2, 3], comment_ids=[30])
211
+
212
+ assert response.data == body
213
+ (request,) = requests
214
+ assert request.url.path == "/rest/bug/1/comment"
215
+ # Repeated, not comma-joined: Bugzilla rejects ``ids=2,3``.
216
+ assert request.url.params.get_list("ids") == ["2", "3"]
217
+ assert request.url.params.get_list("comment_ids") == ["30"]
218
+
219
+
220
+ async def test_attachments_get_by_bugs_and_attachment_ids_in_one_request(bugzilla):
221
+ body = {
222
+ "bugs": {"1": [_attachment(10, 1)], "2": []},
223
+ "attachments": {"30": _attachment(30, 4)},
224
+ }
225
+ handler, requests = _recorder(httpx.Response(200, json=body))
226
+
227
+ response = await bugzilla(handler).attachments.get(
228
+ bug_ids=[1, 2], attachment_ids=[30]
229
+ )
230
+
231
+ assert response.data == body
232
+ (request,) = requests
233
+ assert request.url.path == "/rest/bug/1/attachment"
234
+ assert request.url.params.get_list("ids") == ["2"]
235
+ assert request.url.params.get_list("attachment_ids") == ["30"]
236
+ assert request.url.params["exclude_fields"] == "data"
237
+
238
+
239
+ async def test_update_bug_returns_changes(bugzilla):
240
+ changes = {"status": {"added": "RESOLVED", "removed": "NEW"}}
241
+ answer = {"bugs": [{"id": 1, "changes": changes}]}
242
+ handler, requests = _recorder(httpx.Response(200, json=answer))
243
+ update = {"status": "RESOLVED", "comment": {"body": "done"}}
244
+
245
+ response = await bugzilla(handler).bugs.update(1, update)
246
+ assert response.data == answer
247
+
248
+ (request,) = requests
249
+ assert request.method == "PUT"
250
+ assert request.url.path == "/rest/bug/1"
251
+ assert json.loads(request.content) == update
252
+
253
+
254
+ async def test_add_attachment_encodes_data(bugzilla):
255
+ # BMO's answer: attachments keyed by id.
256
+ body = {"attachments": {"300": _attachment(300, 5)}}
257
+ handler, requests = _recorder(httpx.Response(201, json=body))
258
+
259
+ response = await bugzilla(handler).attachments.create(
260
+ 5,
261
+ b"\xff\xfe\x00",
262
+ {
263
+ "file_name": "fix.patch",
264
+ "summary": "Fix",
265
+ "content_type": "text/plain",
266
+ "is_patch": True,
267
+ "comment": "See patch",
268
+ },
269
+ )
270
+
271
+ assert response.data == body
272
+ body = json.loads(requests[0].content)
273
+ assert base64.b64decode(body["data"]) == b"\xff\xfe\x00"
274
+ assert body["ids"] == [5]
275
+ assert body["is_patch"] is True
276
+ assert body["comment"] == "See patch"