atli 0.5.1__tar.gz → 0.6.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.
Files changed (55) hide show
  1. {atli-0.5.1 → atli-0.6.0}/PKG-INFO +1 -1
  2. {atli-0.5.1 → atli-0.6.0}/src/atli/__init__.py +1 -1
  3. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/client.py +100 -0
  4. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/commands.py +46 -0
  5. {atli-0.5.1 → atli-0.6.0}/src/atli/skills/atli-jira/SKILL.md +19 -1
  6. {atli-0.5.1 → atli-0.6.0}/src/atli/skills/using-atli/SKILL.md +1 -1
  7. atli-0.6.0/tests/test_jira_attachments.py +581 -0
  8. {atli-0.5.1 → atli-0.6.0}/.gitignore +0 -0
  9. {atli-0.5.1 → atli-0.6.0}/CHANGELOG.md +0 -0
  10. {atli-0.5.1 → atli-0.6.0}/LICENSE +0 -0
  11. {atli-0.5.1 → atli-0.6.0}/README.md +0 -0
  12. {atli-0.5.1 → atli-0.6.0}/pyproject.toml +0 -0
  13. {atli-0.5.1 → atli-0.6.0}/src/atli/__main__.py +0 -0
  14. {atli-0.5.1 → atli-0.6.0}/src/atli/cli.py +0 -0
  15. {atli-0.5.1 → atli-0.6.0}/src/atli/client.py +0 -0
  16. {atli-0.5.1 → atli-0.6.0}/src/atli/commands_util.py +0 -0
  17. {atli-0.5.1 → atli-0.6.0}/src/atli/config.py +0 -0
  18. {atli-0.5.1 → atli-0.6.0}/src/atli/config_commands.py +0 -0
  19. {atli-0.5.1 → atli-0.6.0}/src/atli/confluence/__init__.py +0 -0
  20. {atli-0.5.1 → atli-0.6.0}/src/atli/confluence/client.py +0 -0
  21. {atli-0.5.1 → atli-0.6.0}/src/atli/confluence/commands.py +0 -0
  22. {atli-0.5.1 → atli-0.6.0}/src/atli/confluence/markdown.py +0 -0
  23. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/__init__.py +0 -0
  24. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/agile.py +0 -0
  25. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/agile_commands.py +0 -0
  26. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/body.py +0 -0
  27. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/fields.py +0 -0
  28. {atli-0.5.1 → atli-0.6.0}/src/atli/jira/jql.py +0 -0
  29. {atli-0.5.1 → atli-0.6.0}/src/atli/output.py +0 -0
  30. {atli-0.5.1 → atli-0.6.0}/src/atli/skills/atli-confluence/SKILL.md +0 -0
  31. {atli-0.5.1 → atli-0.6.0}/src/atli/skills_commands.py +0 -0
  32. {atli-0.5.1 → atli-0.6.0}/tests/__init__.py +0 -0
  33. {atli-0.5.1 → atli-0.6.0}/tests/test_client.py +0 -0
  34. {atli-0.5.1 → atli-0.6.0}/tests/test_config.py +0 -0
  35. {atli-0.5.1 → atli-0.6.0}/tests/test_config_commands.py +0 -0
  36. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence.py +0 -0
  37. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence_attach.py +0 -0
  38. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence_attachment_dl.py +0 -0
  39. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence_labels.py +0 -0
  40. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence_property.py +0 -0
  41. {atli-0.5.1 → atli-0.6.0}/tests/test_confluence_space.py +0 -0
  42. {atli-0.5.1 → atli-0.6.0}/tests/test_followup_fixes.py +0 -0
  43. {atli-0.5.1 → atli-0.6.0}/tests/test_integration.py +0 -0
  44. {atli-0.5.1 → atli-0.6.0}/tests/test_jira.py +0 -0
  45. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_agile.py +0 -0
  46. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_bulk_meta.py +0 -0
  47. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_fields.py +0 -0
  48. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_helpers.py +0 -0
  49. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_jql.py +0 -0
  50. {atli-0.5.1 → atli-0.6.0}/tests/test_jira_p3.py +0 -0
  51. {atli-0.5.1 → atli-0.6.0}/tests/test_markdown.py +0 -0
  52. {atli-0.5.1 → atli-0.6.0}/tests/test_review_findings.py +0 -0
  53. {atli-0.5.1 → atli-0.6.0}/tests/test_skills.py +0 -0
  54. {atli-0.5.1 → atli-0.6.0}/tests/test_sprint_move_search.py +0 -0
  55. {atli-0.5.1 → atli-0.6.0}/tests/test_stage5_features.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: atli
3
- Version: 0.5.1
3
+ Version: 0.6.0
4
4
  Summary: Lightweight CLI for self-hosted Jira and Confluence (Server / Data Center)
5
5
  Project-URL: Homepage, https://github.com/yuanyuan06/atli-kit
6
6
  Project-URL: Repository, https://github.com/yuanyuan06/atli-kit
@@ -1,3 +1,3 @@
1
1
  """atli — Lightweight CLI for self-hosted Jira and Confluence."""
2
2
 
3
- __version__ = "0.5.1"
3
+ __version__ = "0.6.0"
@@ -2,10 +2,64 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import mimetypes
6
+ from pathlib import Path
5
7
  from typing import Any
6
8
 
7
9
  from atli.client import AtlassianAPIError, AtlassianClient
8
10
 
11
+ # Per-request timeout for attachment uploads. httpx applies this to each network
12
+ # phase (connect/write/read), not to the whole file: a slow but progressing
13
+ # upload is not cut off at this mark.
14
+ _UPLOAD_TIMEOUT = 120.0
15
+
16
+ _UNCONFIRMED_UPLOAD = (
17
+ "upload outcome could not be confirmed; the attachment may already be on "
18
+ "the issue — check the issue's attachments before retrying"
19
+ )
20
+
21
+ # An attachment object from an official example may omit ``id``; any of these
22
+ # identifies the attachment the server actually created.
23
+ _ATTACHMENT_IDENTITY_FIELDS = ("id", "self", "content")
24
+
25
+
26
+ def _non_empty_str(value: Any) -> bool:
27
+ return isinstance(value, str) and bool(value)
28
+
29
+
30
+ def _receipt_problem(data: Any) -> str | None:
31
+ """Explain why ``data`` is unusable as an upload receipt, or return ``None``.
32
+
33
+ A 200 can still carry an error envelope or empty objects, so each element
34
+ must look like an attachment: a filename, a size, and one of
35
+ ``id``/``self``/``content`` to identify what was created. Missing optional
36
+ fields are left alone — the receipt is reported verbatim, never reshaped.
37
+ """
38
+ if not isinstance(data, list):
39
+ return f"expected a JSON array, got {type(data).__name__}: {data!r:.120}"
40
+ if not data:
41
+ return "expected a non-empty array, got an empty array"
42
+ for index, item in enumerate(data):
43
+ if not isinstance(item, dict):
44
+ return (
45
+ f"element {index} is {type(item).__name__}, not an object: "
46
+ f"{item!r:.120}"
47
+ )
48
+ if not _non_empty_str(item.get("filename")):
49
+ return f"element {index} has no usable filename: {item!r:.120}"
50
+ size = item.get("size")
51
+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:
52
+ return f"element {index} has no usable size: {item!r:.120}"
53
+ if not any(
54
+ _non_empty_str(item.get(field)) for field in _ATTACHMENT_IDENTITY_FIELDS
55
+ ):
56
+ identity = "/".join(_ATTACHMENT_IDENTITY_FIELDS)
57
+ return (
58
+ f"element {index} has none of {identity} to identify the "
59
+ f"attachment: {item!r:.120}"
60
+ )
61
+ return None
62
+
9
63
 
10
64
  class JiraClient(AtlassianClient):
11
65
  API = "/rest/api/2"
@@ -87,6 +141,52 @@ class JiraClient(AtlassianClient):
87
141
  """Delete a comment by ID."""
88
142
  return self.delete(f"{self.API}/issue/{key}/comment/{comment_id}")
89
143
 
144
+ def add_attachment(self, key: str, file_path: str | Path) -> list[dict]:
145
+ """Upload one file to ``key`` and return Jira's attachment array.
146
+
147
+ The file is streamed with a guessed MIME type. Raises ``OSError`` when
148
+ the local file cannot be opened (nothing was sent); raises
149
+ ``AtlassianAPIError`` for HTTP errors and for any exchange whose
150
+ outcome cannot be read, since Jira documents no idempotency guarantee.
151
+ """
152
+ path = Path(file_path)
153
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
154
+ api_path = f"{self.API}/issue/{key}/attachments"
155
+ url = f"{self.base_url}{api_path}"
156
+
157
+ # Opened before the try below: an open failure means no request was
158
+ # sent, so it stays an unambiguous local error for the command layer.
159
+ with path.open("rb") as handle:
160
+ try:
161
+ data: Any = self.request(
162
+ "POST",
163
+ api_path,
164
+ headers={"X-Atlassian-Token": "no-check"},
165
+ files={"file": (path.name, handle, content_type)},
166
+ timeout=_UPLOAD_TIMEOUT,
167
+ )
168
+ except OSError as exc:
169
+ raise AtlassianAPIError(
170
+ 0, f"{_UNCONFIRMED_UPLOAD} (I/O error during upload: {exc})", url
171
+ ) from exc
172
+ except AtlassianAPIError as exc:
173
+ # Status 0 is a transport failure; a 2xx means the call
174
+ # succeeded but the body was not parseable as JSON. Both leave
175
+ # us without a receipt. HTTP error statuses pass through with
176
+ # Jira's status and message intact.
177
+ if exc.status == 0 or 200 <= exc.status < 300:
178
+ raise AtlassianAPIError(
179
+ exc.status,
180
+ f"{_UNCONFIRMED_UPLOAD} ({exc.message})",
181
+ exc.url or url,
182
+ ) from exc
183
+ raise
184
+
185
+ problem = _receipt_problem(data)
186
+ if problem is not None:
187
+ raise AtlassianAPIError(0, f"{_UNCONFIRMED_UPLOAD} ({problem})", url)
188
+ return data
189
+
90
190
  def get_transitions(self, key: str) -> list[dict]:
91
191
  data = self.get(f"{self.API}/issue/{key}/transitions")
92
192
  return list(data.get("transitions", []))
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from pathlib import Path
5
6
  from typing import Any
6
7
 
7
8
  import click
@@ -481,6 +482,51 @@ def comment_delete(
481
482
  emit_kv([("Issue", key), ("Comment", comment_id), ("Deleted", "yes")], json_mode=False)
482
483
 
483
484
 
485
+ @jira.group("attachment")
486
+ def attachment_group() -> None:
487
+ """Manage issue attachments."""
488
+
489
+
490
+ @attachment_group.command("add")
491
+ @click.argument("key")
492
+ @click.option(
493
+ "--file",
494
+ "file_path",
495
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
496
+ required=True,
497
+ help="File to upload",
498
+ )
499
+ @click.pass_context
500
+ def attachment_add(ctx: click.Context, key: str, file_path: Path) -> None:
501
+ """Upload one file to an issue."""
502
+ client = _client(ctx)
503
+ try:
504
+ attachments = client.add_attachment(key, file_path)
505
+ except OSError as e:
506
+ # Open failed before any request was sent — a local problem, not a
507
+ # possibly-completed upload.
508
+ fail(f"cannot read file {file_path}: {e}")
509
+ except AtlassianAPIError as e:
510
+ fail(str(e))
511
+
512
+ rows = [
513
+ [
514
+ a.get("id", ""),
515
+ a.get("filename", ""),
516
+ a.get("mimeType", ""),
517
+ a.get("size", ""),
518
+ a.get("self", ""),
519
+ ]
520
+ for a in attachments
521
+ ]
522
+ emit_table(
523
+ ["ID", "Filename", "Type", "Size", "Self"],
524
+ rows,
525
+ json_mode=ctx.obj["json"],
526
+ payload=attachments,
527
+ )
528
+
529
+
484
530
  @jira.command("transition")
485
531
  @click.argument("key")
486
532
  @click.option("--to", "target", required=True, help="Target status name (e.g. 'Done')")
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: atli-jira
3
- description: Use when operating Jira via the `atli` CLI — issues, links, epics/sprints/boards, worklogs, watchers, clone/delete. Covers JQL, Agile, and JSON-mode parsing.
3
+ description: Use when operating Jira via the `atli` CLI — issues, links, attachments, epics/sprints/boards, worklogs, watchers, clone/delete. Covers JQL, Agile, and JSON-mode parsing.
4
4
  ---
5
5
 
6
6
  # atli jira — Jira operations
@@ -37,6 +37,7 @@ atli jira comment add PROJ-123 (--text "..." | --file path) [--internal]
37
37
  atli jira comment list PROJ-123 [--limit 50]
38
38
  atli jira comment update PROJ-123 COMMENT_ID (--text "..." | --file path)
39
39
  atli jira comment delete PROJ-123 COMMENT_ID [--yes]
40
+ atli jira attachment add KEY --file PATH # one file per call; text shows the server receipt
40
41
  atli jira transition PROJ-123 --to "Done" [--comment "..."] [--resolution Fixed] [--assignee alice]
41
42
  atli jira project list
42
43
  atli jira board list [--project PROJ]
@@ -98,6 +99,23 @@ Sprints require a board id (`atli jira board list --project PROJ`). Prefer `--cu
98
99
 
99
100
  `--internal` on comments sets the Service Management property `sd.public.comment`; on plain Jira Software it may be ignored or rejected depending on plugins.
100
101
 
102
+ ## Attachments
103
+
104
+ `atli jira attachment add PROJ-123 --file ./report.pdf` uploads **one** file per call. There is no download, delete, rename, or batch command. Same-name files are neither replaced nor deduplicated: Jira decides whether to keep both, rename, or reject, so never promise an overwrite. The configured attachment size limit is instance-specific; attachments must be enabled and the user needs Create Attachments plus issue visibility.
105
+
106
+ `--json` prints Jira's top-level attachment array verbatim:
107
+
108
+ ```bash
109
+ atli --json jira attachment add PROJ-123 --file ./report.pdf \
110
+ | jq -r '.[0] | .id // .self, .filename, .size'
111
+ ```
112
+
113
+ An entry may carry only `self`/`filename`/`size` without `id` — report what came back rather than deriving one.
114
+
115
+ Exit 1 with "upload outcome could not be confirmed" means the CLI has no reliable receipt (network failure, timeout, or a response that is not a JSON attachment array). Jira documents no upload idempotency, so the file may already be attached: check the issue's attachments before deciding to retry. The CLI sends exactly one request and never retries by itself. HTTP errors keep the status and Jira's original message — `403`, `404` and `413` each have several possible causes (permissions, archived issue, instance limit, proxy), so read the message instead of assuming one.
116
+
117
+ A failure to open the local file (missing, unreadable, a directory) is reported as a local error and no request is sent.
118
+
101
119
  ## Pattern: create then transition
102
120
 
103
121
  ```bash
@@ -75,7 +75,7 @@ Use `--quiet` to suppress progress messages (e.g. markdown conversion info). Use
75
75
  ## Global constraints for all atli operations
76
76
 
77
77
  1. **When an operation is unsupported, explain why and provide evidence**
78
- - If `atli` does not support an operation (e.g. bulk edits, Confluence page moves, space creation, Jira Cloud), **clearly tell the user the operation cannot be done via `atli`**, explain the specific reason (command does not exist, API unsupported, outside CLI scope), and provide evidence (e.g. `atli --help` output, `atli jira --help` subcommand list, or Atlassian REST API docs reference). Issue linking, attachments (`conf upload`/`attach`), epics/sprints, and worklogs **are** supported — see **atli-jira** / **atli-confluence**.
78
+ - If `atli` does not support an operation (e.g. bulk edits, Confluence page moves, space creation, Jira Cloud), **clearly tell the user the operation cannot be done via `atli`**, explain the specific reason (command does not exist, API unsupported, outside CLI scope), and provide evidence (e.g. `atli --help` output, `atli jira --help` subcommand list, or Atlassian REST API docs reference). Issue linking, attachments (Jira `jira attachment add`; Confluence `conf upload`/`attach`), epics/sprints, and worklogs **are** supported — see **atli-jira** / **atli-confluence**.
79
79
  - **Do not** make unilateral decisions to bypass `atli` with alternatives (e.g. direct `curl`, web UI actions, script workarounds). You may **suggest** alternatives, but must get user confirmation before executing.
80
80
 
81
81
  2. **Ask for confirmation when instructions are ambiguous**
@@ -0,0 +1,581 @@
1
+ """Tests for `atli jira attachment add` (single-file upload).
2
+
3
+ Jira answers an upload with a top-level JSON array of attachment objects.
4
+ Anything else — a non-array, an empty array, or elements that are not
5
+ attachment objects carrying a filename, a size and an `id`/`self`/`content`
6
+ reference — is an unusable receipt: the request may still have created an
7
+ attachment, so the CLI reports an unconfirmed outcome instead of success.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import httpx
17
+ import pytest
18
+ import respx
19
+ from click.testing import CliRunner
20
+
21
+ from atli.cli import cli
22
+ from atli.client import AtlassianAPIError
23
+ from atli.jira.client import JiraClient
24
+ from atli.skills_commands import bundled_skills_root
25
+
26
+ JIRA_URL = "https://jira.example.com"
27
+ UPLOAD_URL = f"{JIRA_URL}/rest/api/2/issue/PROJ-1/attachments"
28
+ UNCONFIRMED = "could not be confirmed"
29
+
30
+
31
+ @pytest.fixture
32
+ def env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
33
+ monkeypatch.setenv("HOME", str(tmp_path))
34
+ monkeypatch.setenv("ATLI_JIRA_URL", JIRA_URL)
35
+ monkeypatch.setenv("ATLI_JIRA_TOKEN", "tok")
36
+
37
+
38
+ def _file(tmp_path: Path, name: str = "report.pdf", data: bytes = b"%PDF-1.4 fake") -> Path:
39
+ path = tmp_path / name
40
+ path.write_bytes(data)
41
+ return path
42
+
43
+
44
+ def _client() -> JiraClient:
45
+ return JiraClient(JIRA_URL, "tok")
46
+
47
+
48
+ def _receipt(**overrides: Any) -> dict:
49
+ """One attachment object shaped like Jira's response (id optional)."""
50
+ receipt: dict = {
51
+ "self": f"{JIRA_URL}/rest/api/2/attachment/10100",
52
+ "filename": "report.pdf",
53
+ "size": 13,
54
+ }
55
+ receipt.update(overrides)
56
+ return receipt
57
+
58
+
59
+ def _record_opens(monkeypatch: pytest.MonkeyPatch, opened: list["_RecordingHandle"]) -> None:
60
+ """Patch ``Path.open`` so the test can see whether the client closed the file."""
61
+ real_open = Path.open
62
+
63
+ def recording_open(self: Path, *args: Any, **kwargs: Any) -> "_RecordingHandle":
64
+ handle = _RecordingHandle(real_open(self, *args, **kwargs))
65
+ opened.append(handle)
66
+ return handle
67
+
68
+ monkeypatch.setattr(Path, "open", recording_open)
69
+
70
+
71
+ class _RecordingHandle:
72
+ """Proxy a real handle so a test can see whether the client closed it."""
73
+
74
+ def __init__(self, handle: Any) -> None:
75
+ self._handle = handle
76
+
77
+ def __getattr__(self, name: str) -> Any:
78
+ return getattr(self._handle, name)
79
+
80
+ def __enter__(self) -> "_RecordingHandle":
81
+ return self
82
+
83
+ def __exit__(self, *exc_info: Any) -> None:
84
+ self.close()
85
+
86
+ def close(self) -> None:
87
+ self._handle.close()
88
+
89
+
90
+ # ----------------------------- client: request shape -----------------------------
91
+
92
+
93
+ def test_add_attachment_posts_multipart_file(tmp_path: Path) -> None:
94
+ path = _file(tmp_path)
95
+ receipt = [{"id": "10100", "filename": "report.pdf", "size": 13}]
96
+ with respx.mock:
97
+ route = respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=receipt))
98
+ result = _client().add_attachment("PROJ-1", path)
99
+
100
+ assert result == receipt
101
+ request = route.calls.last.request
102
+ assert request.method == "POST"
103
+ assert str(request.url) == UPLOAD_URL
104
+ assert request.headers["authorization"] == "Bearer tok"
105
+ assert request.headers["x-atlassian-token"] == "no-check"
106
+ assert request.headers["content-type"].startswith("multipart/form-data; boundary=")
107
+ # Per-phase upload timeout, not the client's global 30s default.
108
+ assert request.extensions["timeout"]["read"] == 120.0
109
+
110
+ body = request.content
111
+ assert b'Content-Disposition: form-data; name="file"; filename="report.pdf"' in body
112
+ assert b"Content-Type: application/pdf" in body
113
+ assert b"%PDF-1.4 fake" in body
114
+ assert len(route.calls) == 1
115
+
116
+
117
+ def test_add_attachment_keeps_unicode_and_space_filename(tmp_path: Path) -> None:
118
+ path = _file(tmp_path, name="中文 报告 2026.txt", data="你好".encode())
119
+ with respx.mock:
120
+ route = respx.post(UPLOAD_URL).mock(
121
+ return_value=httpx.Response(200, json=[_receipt(filename=path.name)])
122
+ )
123
+ _client().add_attachment("PROJ-1", path)
124
+
125
+ body = route.calls.last.request.content
126
+ assert path.name.encode() in body
127
+ assert b'name="file"' in body
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ ("name", "data", "content_type"),
132
+ [
133
+ ("empty.txt", b"", b"text/plain"),
134
+ ("blob.bin", b"\x00\x01\xfe\xff\x7f", b"application/octet-stream"),
135
+ ],
136
+ ids=["zero-byte", "binary"],
137
+ )
138
+ def test_add_attachment_streams_file_bytes(
139
+ tmp_path: Path, name: str, data: bytes, content_type: bytes
140
+ ) -> None:
141
+ path = _file(tmp_path, name=name, data=data)
142
+ with respx.mock:
143
+ route = respx.post(UPLOAD_URL).mock(
144
+ return_value=httpx.Response(200, json=[_receipt(filename=name, size=len(data))])
145
+ )
146
+ _client().add_attachment("PROJ-1", path)
147
+
148
+ body = route.calls.last.request.content
149
+ boundary = body.split(b"\r\n", 1)[0] # "--<boundary>"
150
+ _, _, payload = body.partition(
151
+ f'filename="{name}"\r\nContent-Type: '.encode() + content_type + b"\r\n\r\n"
152
+ )
153
+ assert payload == data + b"\r\n" + boundary + b"--\r\n"
154
+
155
+
156
+ @pytest.mark.parametrize(
157
+ "identity",
158
+ [
159
+ {"self": f"{JIRA_URL}/rest/api/2/attachment/1"},
160
+ {"content": f"{JIRA_URL}/rest/api/2/attachment/1/content"},
161
+ {"id": "10100"},
162
+ ],
163
+ ids=["self-only", "content-only", "id-only"],
164
+ )
165
+ def test_add_attachment_accepts_any_identity_field(
166
+ tmp_path: Path, identity: dict
167
+ ) -> None:
168
+ """Official examples may omit ``id``; return the receipt as sent."""
169
+ path = _file(tmp_path)
170
+ receipt = [{"filename": "report.pdf", "size": 13, **identity}]
171
+ with respx.mock:
172
+ respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=receipt))
173
+ result = _client().add_attachment("PROJ-1", path)
174
+
175
+ assert result == receipt
176
+ assert result[0].keys() == receipt[0].keys()
177
+
178
+
179
+ # ----------------------------- client: unusable receipts -----------------------------
180
+
181
+
182
+ @pytest.mark.parametrize(
183
+ "response",
184
+ [
185
+ httpx.Response(200, json=[]),
186
+ httpx.Response(200, json={}),
187
+ httpx.Response(200, json={"results": [_receipt()]}),
188
+ httpx.Response(200, json=[_receipt(), "oops"]),
189
+ httpx.Response(200, json=[_receipt(), {}]),
190
+ # A 200 array whose elements are not attachment objects: the receipt
191
+ # cannot confirm which attachment was created.
192
+ httpx.Response(200, json=[{}]),
193
+ httpx.Response(200, json=[{"errorMessages": ["upload failed"]}]),
194
+ httpx.Response(200, json=[{"filename": None, "size": "invalid", "id": "1"}]),
195
+ httpx.Response(200, json=[{"filename": "report.pdf", "size": 13}]),
196
+ httpx.Response(200, json=[_receipt(size=True)]),
197
+ httpx.Response(200),
198
+ httpx.Response(200, text="<html>ok</html>"),
199
+ ],
200
+ ids=[
201
+ "empty-array",
202
+ "empty-object-body",
203
+ "wrapped-object",
204
+ "mixed-array",
205
+ "valid-then-empty-object",
206
+ "empty-object",
207
+ "error-object",
208
+ "wrong-field-types",
209
+ "no-identity",
210
+ "bool-size",
211
+ "empty-body",
212
+ "non-json",
213
+ ],
214
+ )
215
+ def test_add_attachment_rejects_unusable_receipt(
216
+ tmp_path: Path, response: httpx.Response
217
+ ) -> None:
218
+ path = _file(tmp_path)
219
+ client = _client()
220
+ with respx.mock:
221
+ route = respx.post(UPLOAD_URL).mock(return_value=response)
222
+ with pytest.raises(AtlassianAPIError) as excinfo:
223
+ client.add_attachment("PROJ-1", path)
224
+
225
+ message = str(excinfo.value)
226
+ assert UNCONFIRMED in message
227
+ assert "check the issue's attachments" in message
228
+ assert len(route.calls) == 1
229
+ assert client.client.headers["content-type"] == "application/json"
230
+
231
+
232
+ # ----------------------------- client: HTTP and transport failures -----------------------------
233
+
234
+
235
+ @pytest.mark.parametrize(
236
+ ("response", "status", "server_text"),
237
+ [
238
+ (
239
+ httpx.Response(413, json={"errorMessages": ["Attachment exceeds the 10 MB limit"]}),
240
+ 413,
241
+ "Attachment exceeds the 10 MB limit",
242
+ ),
243
+ (
244
+ httpx.Response(404, text="<html>Issue Does Not Exist</html>"),
245
+ 404,
246
+ "Issue Does Not Exist",
247
+ ),
248
+ ],
249
+ ids=["413-json", "404-html"],
250
+ )
251
+ def test_add_attachment_http_error_keeps_status_and_body(
252
+ tmp_path: Path, response: httpx.Response, status: int, server_text: str
253
+ ) -> None:
254
+ path = _file(tmp_path)
255
+ with respx.mock:
256
+ route = respx.post(UPLOAD_URL).mock(return_value=response)
257
+ with pytest.raises(AtlassianAPIError) as excinfo:
258
+ _client().add_attachment("PROJ-1", path)
259
+
260
+ error = excinfo.value
261
+ assert error.status == status
262
+ assert server_text in error.message
263
+ assert error.url == UPLOAD_URL
264
+ # A status is a receipt: do not claim the outcome is unknown, and do not retry.
265
+ assert UNCONFIRMED not in str(error)
266
+ assert len(route.calls) == 1
267
+
268
+
269
+ @pytest.mark.parametrize(
270
+ "error",
271
+ [httpx.ConnectError("connection refused"), httpx.ReadTimeout("timed out")],
272
+ ids=["connect", "timeout"],
273
+ )
274
+ def test_add_attachment_transport_failure_is_unknown_and_single_attempt(
275
+ tmp_path: Path, error: httpx.RequestError
276
+ ) -> None:
277
+ path = _file(tmp_path)
278
+ client = _client()
279
+ with respx.mock:
280
+ route = respx.post(UPLOAD_URL).mock(side_effect=error)
281
+ with pytest.raises(AtlassianAPIError) as excinfo:
282
+ client.add_attachment("PROJ-1", path)
283
+
284
+ assert excinfo.value.status == 0
285
+ assert UNCONFIRMED in str(excinfo.value)
286
+ assert len(route.calls) == 1
287
+ assert client.client.headers["content-type"] == "application/json"
288
+
289
+
290
+ # ----------------------------- client: local file failures -----------------------------
291
+
292
+
293
+ def test_add_attachment_open_failure_sends_nothing(
294
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
295
+ ) -> None:
296
+ path = _file(tmp_path)
297
+
298
+ def deny(self: Path, *args: Any, **kwargs: Any) -> Any:
299
+ raise PermissionError(13, "Permission denied", str(self))
300
+
301
+ monkeypatch.setattr(Path, "open", deny)
302
+ with respx.mock:
303
+ route = respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=[{}]))
304
+ with pytest.raises(OSError, match="Permission denied"):
305
+ _client().add_attachment("PROJ-1", path)
306
+ assert not route.called
307
+
308
+
309
+ class _FailingRead:
310
+ def __enter__(self) -> "_FailingRead":
311
+ return self
312
+
313
+ def __exit__(self, *exc_info: Any) -> None:
314
+ return None
315
+
316
+ def read(self, *args: Any) -> bytes:
317
+ raise OSError(5, "Input/output error")
318
+
319
+ def close(self) -> None:
320
+ return None
321
+
322
+
323
+ def test_add_attachment_read_failure_during_upload_is_unknown(
324
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
325
+ ) -> None:
326
+ path = _file(tmp_path)
327
+ monkeypatch.setattr(Path, "open", lambda self, *a, **k: _FailingRead())
328
+ with respx.mock:
329
+ with pytest.raises(AtlassianAPIError) as excinfo:
330
+ _client().add_attachment("PROJ-1", path)
331
+
332
+ assert excinfo.value.status == 0
333
+ assert UNCONFIRMED in str(excinfo.value)
334
+ assert "I/O error during upload" in str(excinfo.value)
335
+
336
+
337
+ # ----------------------------- client: resource cleanup -----------------------------
338
+
339
+
340
+ @pytest.mark.parametrize(
341
+ "response",
342
+ [
343
+ httpx.Response(200, json=[_receipt(id="1")]),
344
+ httpx.Response(413, json={"errorMessages": ["too large"]}),
345
+ ],
346
+ ids=["success", "http-error"],
347
+ )
348
+ def test_add_attachment_closes_file_and_restores_content_type(
349
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, response: httpx.Response
350
+ ) -> None:
351
+ path = _file(tmp_path)
352
+ opened: list[_RecordingHandle] = []
353
+ _record_opens(monkeypatch, opened)
354
+ client = _client()
355
+ with respx.mock:
356
+ respx.post(UPLOAD_URL).mock(return_value=response)
357
+ if response.status_code >= 400:
358
+ with pytest.raises(AtlassianAPIError):
359
+ client.add_attachment("PROJ-1", path)
360
+ else:
361
+ client.add_attachment("PROJ-1", path)
362
+
363
+ assert opened and opened[0]._handle.closed
364
+ assert client.client.headers["content-type"] == "application/json"
365
+
366
+
367
+ def test_add_attachment_closes_file_after_transport_failure(
368
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
369
+ ) -> None:
370
+ path = _file(tmp_path)
371
+ opened: list[_RecordingHandle] = []
372
+ _record_opens(monkeypatch, opened)
373
+ with respx.mock:
374
+ respx.post(UPLOAD_URL).mock(side_effect=httpx.ConnectError("refused"))
375
+ with pytest.raises(AtlassianAPIError):
376
+ _client().add_attachment("PROJ-1", path)
377
+
378
+ assert opened and opened[0]._handle.closed
379
+
380
+
381
+ # ----------------------------- CLI -----------------------------
382
+
383
+
384
+ def test_cli_attachment_add_text_shows_server_fields(env: None, tmp_path: Path) -> None:
385
+ path = _file(tmp_path, name="screenshot.png", data=b"\x89PNG\r\n\x1a\nfake")
386
+ with respx.mock:
387
+ route = respx.post(UPLOAD_URL).mock(
388
+ return_value=httpx.Response(
389
+ 200,
390
+ json=[
391
+ {
392
+ "id": "10200",
393
+ "filename": "screenshot.png",
394
+ "mimeType": "image/png",
395
+ "size": 12,
396
+ "self": f"{JIRA_URL}/rest/api/2/attachment/10200",
397
+ }
398
+ ],
399
+ )
400
+ )
401
+ result = CliRunner().invoke(
402
+ cli, ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
403
+ )
404
+
405
+ assert result.exit_code == 0, result.output
406
+ assert "10200" in result.output
407
+ assert "screenshot.png" in result.output
408
+ assert "image/png" in result.output
409
+ assert len(route.calls) == 1
410
+
411
+
412
+ def test_cli_attachment_add_json_emits_raw_array(env: None, tmp_path: Path) -> None:
413
+ path = _file(tmp_path)
414
+ receipt = [
415
+ {"self": f"{JIRA_URL}/rest/api/2/attachment/1", "filename": "report.pdf", "size": 13}
416
+ ]
417
+ with respx.mock:
418
+ respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=receipt))
419
+ result = CliRunner().invoke(
420
+ cli, ["--json", "jira", "attachment", "add", "PROJ-1", "--file", str(path)]
421
+ )
422
+
423
+ assert result.exit_code == 0, result.output
424
+ assert json.loads(result.output) == receipt
425
+
426
+
427
+ @pytest.mark.parametrize(
428
+ ("target", "expected"),
429
+ [
430
+ (None, "Missing option '--file'"),
431
+ ("absent", "does not exist"),
432
+ ("directory", "is a directory"),
433
+ ],
434
+ ids=["missing-option", "missing-file", "directory"],
435
+ )
436
+ def test_cli_attachment_add_rejects_bad_path(
437
+ env: None, tmp_path: Path, target: str | None, expected: str
438
+ ) -> None:
439
+ (tmp_path / "dir").mkdir()
440
+ argv = ["jira", "attachment", "add", "PROJ-1"]
441
+ if target == "absent":
442
+ argv += ["--file", str(tmp_path / "absent.pdf")]
443
+ elif target == "directory":
444
+ argv += ["--file", str(tmp_path / "dir")]
445
+
446
+ with respx.mock:
447
+ route = respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=[{}]))
448
+ result = CliRunner().invoke(cli, argv)
449
+ assert not route.called
450
+
451
+ assert result.exit_code == 2
452
+ assert expected in result.stderr
453
+
454
+
455
+ def test_cli_attachment_add_unreadable_file_stays_local(
456
+ env: None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
457
+ ) -> None:
458
+ path = _file(tmp_path)
459
+
460
+ def deny(self: Path, *args: Any, **kwargs: Any) -> Any:
461
+ raise PermissionError(13, "Permission denied", str(self))
462
+
463
+ monkeypatch.setattr(Path, "open", deny)
464
+ with respx.mock:
465
+ route = respx.post(UPLOAD_URL).mock(return_value=httpx.Response(200, json=[{}]))
466
+ result = CliRunner().invoke(
467
+ cli, ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
468
+ )
469
+ assert not route.called
470
+
471
+ assert result.exit_code == 1
472
+ assert "cannot read file" in result.stderr
473
+ assert UNCONFIRMED not in result.stderr
474
+ assert "Traceback" not in result.output + result.stderr
475
+
476
+
477
+ def test_cli_attachment_add_network_failure_warns_before_retry(
478
+ env: None, tmp_path: Path
479
+ ) -> None:
480
+ path = _file(tmp_path)
481
+ with respx.mock:
482
+ route = respx.post(UPLOAD_URL).mock(side_effect=httpx.ConnectError("refused"))
483
+ result = CliRunner().invoke(
484
+ cli, ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
485
+ )
486
+
487
+ assert result.exit_code == 1
488
+ assert UNCONFIRMED in result.stderr
489
+ assert "check the issue's attachments" in result.stderr
490
+ assert len(route.calls) == 1
491
+
492
+
493
+ def test_cli_attachment_add_http_error_keeps_upstream_message(
494
+ env: None, tmp_path: Path
495
+ ) -> None:
496
+ path = _file(tmp_path)
497
+ with respx.mock:
498
+ route = respx.post(UPLOAD_URL).mock(
499
+ return_value=httpx.Response(
500
+ 404,
501
+ json={
502
+ "errorMessages": [
503
+ "Issue does not exist or you do not have permission to see it."
504
+ ]
505
+ },
506
+ )
507
+ )
508
+ result = CliRunner().invoke(
509
+ cli, ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
510
+ )
511
+
512
+ assert result.exit_code == 1
513
+ assert "HTTP 404" in result.stderr
514
+ assert "Issue does not exist or you do not have permission" in result.stderr
515
+ assert UNCONFIRMED not in result.stderr
516
+ assert len(route.calls) == 1
517
+
518
+
519
+ def test_cli_attachment_add_unusable_receipt_fails(env: None, tmp_path: Path) -> None:
520
+ path = _file(tmp_path)
521
+ with respx.mock:
522
+ respx.post(UPLOAD_URL).mock(
523
+ return_value=httpx.Response(200, json={"results": [_receipt()]})
524
+ )
525
+ result = CliRunner().invoke(
526
+ cli, ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
527
+ )
528
+
529
+ assert result.exit_code == 1
530
+ assert UNCONFIRMED in result.stderr
531
+ assert result.stdout.strip() == ""
532
+
533
+
534
+ @pytest.mark.parametrize(
535
+ ("payload", "json_mode"),
536
+ [
537
+ ([{}], False),
538
+ ([{"errorMessages": ["upload failed"]}], False),
539
+ ([{"filename": None, "size": "invalid", "id": "1"}], False),
540
+ ([{"filename": "report.pdf", "size": 13}], False),
541
+ ([_receipt(id="10100"), {}], False),
542
+ ([_receipt(), {}], True),
543
+ ],
544
+ ids=[
545
+ "empty-object",
546
+ "error-object",
547
+ "wrong-field-types",
548
+ "no-identity",
549
+ "valid-then-empty-object",
550
+ "valid-then-empty-object-json",
551
+ ],
552
+ )
553
+ def test_cli_attachment_add_malformed_receipt_fails(
554
+ env: None, tmp_path: Path, payload: list[dict], json_mode: bool
555
+ ) -> None:
556
+ path = _file(tmp_path)
557
+ argv = ["jira", "attachment", "add", "PROJ-1", "--file", str(path)]
558
+ if json_mode:
559
+ argv.insert(0, "--json")
560
+ with respx.mock:
561
+ route = respx.post(UPLOAD_URL).mock(
562
+ return_value=httpx.Response(200, json=payload)
563
+ )
564
+ result = CliRunner().invoke(cli, argv)
565
+
566
+ assert result.exit_code == 1, result.output
567
+ assert UNCONFIRMED in result.stderr
568
+ assert "check the issue's attachments" in result.stderr
569
+ assert result.stdout.strip() == ""
570
+ assert len(route.calls) == 1
571
+
572
+
573
+
574
+ def test_help_and_skill_agree_on_attachment_add() -> None:
575
+ result = CliRunner().invoke(cli, ["jira", "attachment", "add", "--help"])
576
+ assert result.exit_code == 0
577
+ assert "KEY" in result.output
578
+ assert "--file" in result.output
579
+
580
+ skill = (bundled_skills_root() / "atli-jira" / "SKILL.md").read_text(encoding="utf-8")
581
+ assert "atli jira attachment add KEY --file PATH" in skill
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes