abysshub 1.0.1.dev7__tar.gz → 1.0.1.dev9__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 (26) hide show
  1. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/pyproject.toml +4 -1
  3. abysshub-1.0.1.dev9/src/abysshub/__main__.py +4 -0
  4. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_async_client.py +9 -6
  5. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_client.py +29 -19
  6. abysshub-1.0.1.dev9/src/abysshub/_command.py +293 -0
  7. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/caller.py +6 -3
  8. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/fake_server.py +1 -1
  9. abysshub-1.0.1.dev9/tests/test_command.py +38 -0
  10. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_package.py +11 -0
  11. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_replay.py +3 -2
  12. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/.gitignore +0 -0
  13. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/LICENSE +0 -0
  14. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/README.md +0 -0
  15. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/__init__.py +0 -0
  16. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_error.py +0 -0
  17. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_files.py +0 -0
  18. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_http.py +0 -0
  19. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_run.py +0 -0
  20. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/_types.py +0 -0
  21. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/src/abysshub/py.typed +0 -0
  22. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/conftest.py +0 -0
  23. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_client.py +0 -0
  24. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_files.py +0 -0
  25. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_http.py +0 -0
  26. {abysshub-1.0.1.dev7 → abysshub-1.0.1.dev9}/tests/test_timeout.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: abysshub
3
- Version: 1.0.1.dev7
3
+ Version: 1.0.1.dev9
4
4
  Summary: Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API.
5
5
  Project-URL: Homepage, https://abysshub.com/docs#api
6
6
  Project-URL: Documentation, https://abysshub.com/docs
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "abysshub"
7
- version = "1.0.1.dev7"
7
+ version = "1.0.1.dev9"
8
8
  description = "Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API."
9
9
  keywords = [
10
10
  "abyss",
@@ -28,6 +28,9 @@ classifiers = [
28
28
  "Typing :: Typed",
29
29
  ]
30
30
 
31
+ [project.scripts]
32
+ abysshub = "abysshub._command:main"
33
+
31
34
  [project.optional-dependencies]
32
35
  dev = ["pytest"]
33
36
 
@@ -0,0 +1,4 @@
1
+ """``python -m abysshub``: the ``abysshub`` command."""
2
+ from ._command import main
3
+
4
+ raise SystemExit(main())
@@ -207,18 +207,21 @@ class AsyncAbyss(_Base[AsyncRun]):
207
207
  async def _upload(self, call: _Call, widget_url: str, field: str, filename: str, data: bytes) -> str:
208
208
  """Asks for an upload, sends the file to storage and answers the upload's id."""
209
209
  grant = await self._grant(call, widget_url, field, filename, len(data))
210
+ await self._store(call, grant.upload.url, grant.upload.fields, field, filename, data)
211
+ return grant.id
212
+
213
+ async def _store(
214
+ self, call: _Call, url: str, fields: dict[str, str], param: str, filename: str, data: bytes
215
+ ) -> None:
216
+ """Sends a file to storage with an S3 POST form: every entry of ``fields``, then the file."""
210
217
  stored: httpx.Response | httpx.TransportError
211
218
  try:
212
219
  stored = await self._http.post(
213
- grant.upload.url,
214
- data=grant.upload.fields,
215
- files={"file": (filename, data)},
216
- timeout=self._timeouts(call),
220
+ url, data=fields, files={"file": (filename, data)}, timeout=self._timeouts(call)
217
221
  )
218
222
  except httpx.TransportError as error:
219
223
  stored = error
220
- self._stored(call, field, filename, stored)
221
- return grant.id
224
+ self._stored(call, param, filename, stored)
222
225
 
223
226
  async def _download(self, url: str, range_header: str | None) -> tuple[int, Callable[[], Awaitable[bytes]]]:
224
227
  """Opens an output file in storage, without the API key, with a ``Range`` header or
@@ -228,23 +228,29 @@ class _Base(Generic[R]):
228
228
  max_price: float | None,
229
229
  idempotency_key: str | None,
230
230
  hold: bool,
231
+ version: int | None = None,
231
232
  ) -> tuple[dict[str, str], bytes]:
232
- """The press's headers and body, with ``"wait": false`` unless it holds."""
233
+ """The press's headers and body, with ``"wait": false`` unless it holds, and a
234
+ Test Run's ``version``."""
233
235
  body: dict[str, Any] = {"input": input}
234
236
  if max_price is not None:
235
237
  body["max_price"] = max_price
236
238
  if not hold:
237
239
  body["wait"] = False
240
+ if version is not None:
241
+ body["version"] = version
238
242
  headers = {
239
243
  "Content-Type": "application/json",
240
244
  "Idempotency-Key": idempotency_key if idempotency_key is not None else str(uuid.uuid4()),
241
245
  }
242
246
  return headers, json.dumps(body).encode()
243
247
 
244
- def _grant_body(self, field: str, filename: str, size: int | None) -> bytes:
248
+ def _grant_body(self, field: str, filename: str, size: int | None, version: int | None = None) -> bytes:
245
249
  body: dict[str, Any] = {"field": field, "filename": filename}
246
250
  if size is not None:
247
251
  body["size"] = size
252
+ if version is not None:
253
+ body["version"] = version
248
254
  return json.dumps(body).encode()
249
255
 
250
256
  def _stored(self, call: _Call, field: str, filename: str, stored: httpx.Response | httpx.TransportError) -> None:
@@ -320,7 +326,7 @@ class _Base(Generic[R]):
320
326
  Every other refusal raises at once."""
321
327
  request_id = answer.headers.get("request-id")
322
328
  parsed = _parse(answer.text)
323
- if answer.status in (200, 202):
329
+ if 200 <= answer.status < 300:
324
330
  run = parsed if _is_run(parsed) else None
325
331
  if run is not None:
326
332
  call.seen = run
@@ -421,38 +427,42 @@ class Abyss(_Base[Run]):
421
427
  max_price: float | None,
422
428
  idempotency_key: str | None,
423
429
  hold: bool,
430
+ version: int | None = None,
424
431
  ) -> _Reply:
425
432
  """Uploads the input's files and sends the press, with ``"wait": false`` unless it
426
- holds. Its retries send the same body and ``Idempotency-Key``, so the uploads are
427
- never redone."""
433
+ holds, and with ``version`` as a Test Run of that Candidate. Its retries send the
434
+ same body and ``Idempotency-Key``, so the uploads are never redone."""
428
435
  widget_url = self._widget_url(widget)
429
436
  uploaded = upload_files(
430
- input, lambda field, filename, data: self._upload(call, widget_url, field, filename, data)
437
+ input, lambda field, filename, data: self._upload(call, widget_url, field, filename, data, version)
431
438
  )
432
- headers, body = self._press_request(uploaded, max_price, idempotency_key, hold)
439
+ headers, body = self._press_request(uploaded, max_price, idempotency_key, hold, version)
433
440
  return self._send(call, "POST", f"{widget_url}/runs", headers, body)
434
441
 
435
- def _grant(self, call: _Call, widget_url: str, field: str, filename: str, size: int | None) -> Upload:
442
+ def _grant(
443
+ self, call: _Call, widget_url: str, field: str, filename: str, size: int | None, version: int | None = None
444
+ ) -> Upload:
436
445
  """Asks for an upload with ``POST /v1/widgets/{widget}/uploads``."""
437
- body = self._grant_body(field, filename, size)
446
+ body = self._grant_body(field, filename, size, version)
438
447
  grant = self._send(call, "POST", f"{widget_url}/uploads", {"Content-Type": "application/json"}, body)
439
448
  return parse_upload(_expect(grant, _is_upload, "The upload answered without an id and a form."))
440
449
 
441
- def _upload(self, call: _Call, widget_url: str, field: str, filename: str, data: bytes) -> str:
450
+ def _upload(
451
+ self, call: _Call, widget_url: str, field: str, filename: str, data: bytes, version: int | None = None
452
+ ) -> str:
442
453
  """Asks for an upload, sends the file to storage and answers the upload's id."""
443
- grant = self._grant(call, widget_url, field, filename, len(data))
454
+ grant = self._grant(call, widget_url, field, filename, len(data), version)
455
+ self._store(call, grant.upload.url, grant.upload.fields, field, filename, data)
456
+ return grant.id
457
+
458
+ def _store(self, call: _Call, url: str, fields: dict[str, str], param: str, filename: str, data: bytes) -> None:
459
+ """Sends a file to storage with an S3 POST form: every entry of ``fields``, then the file."""
444
460
  stored: httpx.Response | httpx.TransportError
445
461
  try:
446
- stored = self._http.post(
447
- grant.upload.url,
448
- data=grant.upload.fields,
449
- files={"file": (filename, data)},
450
- timeout=self._timeouts(call),
451
- )
462
+ stored = self._http.post(url, data=fields, files={"file": (filename, data)}, timeout=self._timeouts(call))
452
463
  except httpx.TransportError as error:
453
464
  stored = error
454
- self._stored(call, field, filename, stored)
455
- return grant.id
465
+ self._stored(call, param, filename, stored)
456
466
 
457
467
  def _download(self, url: str, range_header: str | None) -> tuple[int, Callable[[], bytes]]:
458
468
  """Opens an output file in storage, without the API key, with a ``Range`` header or
@@ -0,0 +1,293 @@
1
+ """The ``abysshub`` command. ``abysshub publish <folder>`` does what a person does on the
2
+ website's Publish page, through `/v1`'s routes that change a Widget. It asks nothing at a
3
+ prompt: it stops or it goes, and every stop exits non-zero with its ``code``."""
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sys
10
+ from fnmatch import fnmatchcase
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ._client import Abyss, _expect, _has_ended, _is_upload, _is_widget
15
+ from ._error import AbyssError
16
+ from ._files import file
17
+ from ._types import parse_upload
18
+
19
+ PUBLISH_FILE = "abyss.json"
20
+ TEST_INPUTS = "test_inputs.json"
21
+ INTERFACE = "interface.json"
22
+ ROOT_ENV = (".env", ".env.*")
23
+ """A root ``.env`` and its variants: never content, whatever the Junk list says."""
24
+ LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_runs")
25
+ """The Listing Fields the Publish File holds, beside its thumbnail."""
26
+ JSON = {"Content-Type": "application/json"}
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ """Runs the command and answers its exit code."""
31
+ parser = argparse.ArgumentParser(prog="abysshub", description="Publish a Widget folder to Abyss.")
32
+ verbs = parser.add_subparsers(dest="verb", metavar="<verb>")
33
+ verbs.required = True
34
+ publish_verb = verbs.add_parser(
35
+ "publish",
36
+ help="publish a Widget folder and print its link",
37
+ description=f"Publish a Widget folder, with its {PUBLISH_FILE} and {TEST_INPUTS}, and print its link.",
38
+ )
39
+ publish_verb.add_argument("folder", type=Path)
40
+ args = parser.parse_args(argv)
41
+ try:
42
+ with Abyss() as abyss:
43
+ print(publish(abyss, args.folder))
44
+ except AbyssError as error:
45
+ print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
46
+ if error.request_id:
47
+ print(f"request_id: {error.request_id}", file=sys.stderr)
48
+ return 1
49
+ except OSError as error:
50
+ # A file the folder names, such as the thumbnail or a Test Input, is missing or unreadable.
51
+ print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
52
+ return 1
53
+ return 0
54
+
55
+
56
+ def publish(abyss: Abyss, folder: Path) -> str:
57
+ """Publishes a folder that was never published, and answers the Widget's link.
58
+
59
+ A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
60
+ number once committed, so a publish that stops is taken up again on the same Draft.
61
+ """
62
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file_invalid")
63
+ if not isinstance(publish_file, dict):
64
+ raise AbyssError("publish_file_invalid", f"{PUBLISH_FILE} is not a JSON object.")
65
+ test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs_invalid") if (folder / TEST_INPUTS).is_file() else {}
66
+ if not isinstance(test_inputs, dict):
67
+ raise AbyssError("test_inputs_invalid", f"{TEST_INPUTS} is not a JSON object.")
68
+ interface = _read_json(folder / INTERFACE, "interface_invalid") if (folder / INTERFACE).is_file() else None
69
+ block = publish_file.get("widget") or {}
70
+ if not isinstance(block, dict):
71
+ raise AbyssError("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object.")
72
+ if "version" in block:
73
+ raise AbyssError(
74
+ "widget_published",
75
+ f"This folder is {block.get('id')}, published already; this abysshub publishes a new Widget only.",
76
+ )
77
+
78
+ widget = block.get("id")
79
+ if widget is None:
80
+ draft = _expect(
81
+ abyss._send(abyss._start(None), "POST", f"{abyss.base_url}/v1/widgets", retries=0),
82
+ _is_widget,
83
+ "The Draft answered without an id.",
84
+ )
85
+ widget = draft["id"]
86
+ _write_block(folder, publish_file, {"id": widget})
87
+ print(f"Made the Draft {widget}.")
88
+ else:
89
+ print(f"Publishing the Draft {widget}.")
90
+ widget_url = abyss._widget_url(widget)
91
+
92
+ base = json.dumps({"base_version": block.get("candidate")}).encode()
93
+ opened = _expect(
94
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions", JSON, base),
95
+ _is_project_version,
96
+ "The version answered without its number, form and Junk list.",
97
+ )
98
+ sent, left_out = _folder_files(folder, opened["junk"], publish_file.get("thumbnail"))
99
+ for path in left_out:
100
+ print(f"Left out {path}")
101
+ upload = opened["upload"]
102
+ for path in sent:
103
+ fields = {**upload["fields"], "key": f"{upload['prefix']}/{path}"}
104
+ data = (folder / path).read_bytes()
105
+ abyss._store(abyss._start(None), upload["url"], fields, path, Path(path).name, data)
106
+ print(f"Sent {len(sent)} files.")
107
+
108
+ version = opened["version"]
109
+ commit = json.dumps({} if interface is None else {"interface": interface}).encode()
110
+ candidate = _expect(
111
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions/{version}/commit", JSON, commit),
112
+ _is_candidate,
113
+ "The commit answered without a Candidate.",
114
+ )
115
+ _write_block(folder, publish_file, {"id": widget, "candidate": candidate["version"]})
116
+
117
+ print(f"Test Run of version {candidate['version']}...")
118
+ run = _test_run(abyss, folder, widget, candidate["version"], test_inputs, interface)
119
+ if run["status"] == "failed":
120
+ _print_logs(run.get("logs"))
121
+ error = run.get("error") or {}
122
+ raise AbyssError(
123
+ error.get("code", "platform_fault"),
124
+ f"The Test Run {run['id']} failed, so nothing was published. {error.get('message', '')}".rstrip(),
125
+ run_id=run["id"],
126
+ )
127
+
128
+ listing = _save_listing(abyss, folder, widget, publish_file)
129
+ published = _expect(
130
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/publish"),
131
+ _is_widget,
132
+ "The publish answered without the Widget.",
133
+ )
134
+ _write_block(
135
+ folder,
136
+ publish_file,
137
+ {"id": widget, "version": candidate["version"], "listing_revision": listing["listing_revision"]},
138
+ )
139
+ return str(published["url"])
140
+
141
+
142
+ def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
143
+ """The folder's files to send, and what it leaves out, by their paths in the folder:
144
+ what the Junk list names, the Publish File, its thumbnail, and a root ``.env`` with its
145
+ variants. A folder that is left out is named once, with a ``/``."""
146
+ names = junk.get("names") or []
147
+ markers = junk.get("markers") or []
148
+ root_names = [*(junk.get("root") or []), *ROOT_ENV]
149
+ skipped = {PUBLISH_FILE}
150
+ if thumbnail:
151
+ skipped.add(Path(thumbnail).as_posix())
152
+ sent: list[str] = []
153
+ left_out: list[str] = []
154
+ for top, dirs, files in os.walk(folder):
155
+ here = Path(top)
156
+ at_root = here == folder
157
+ kept_dirs = []
158
+ for name in sorted(dirs):
159
+ path = here / name
160
+ if any(fnmatchcase(name, pattern) for pattern in names) or _holds_marker(path, markers):
161
+ left_out.append(f"{path.relative_to(folder).as_posix()}/")
162
+ else:
163
+ kept_dirs.append(name)
164
+ dirs[:] = kept_dirs
165
+ for name in sorted(files):
166
+ relative = (here / name).relative_to(folder).as_posix()
167
+ if (
168
+ any(fnmatchcase(name, pattern) for pattern in names)
169
+ or (at_root and any(fnmatchcase(name, pattern) for pattern in root_names))
170
+ or relative in skipped
171
+ ):
172
+ left_out.append(relative)
173
+ else:
174
+ sent.append(relative)
175
+ return sent, left_out
176
+
177
+
178
+ def _test_run(
179
+ abyss: Abyss,
180
+ folder: Path,
181
+ widget: str,
182
+ version: int,
183
+ test_inputs: dict[str, Any],
184
+ interface: list[Any] | None,
185
+ ) -> dict[str, Any]:
186
+ """Makes the Test Run of the Candidate from the Test Inputs and waits for its ending,
187
+ as ``run()`` waits. A file Field's value is a path in the folder, uploaded for that
188
+ Candidate. Answers the run, failed or not."""
189
+ file_fields = {
190
+ field.get("name") for field in interface or [] if isinstance(field, dict) and field.get("type") == "file"
191
+ }
192
+
193
+ def value(name: str, item: Any) -> Any:
194
+ if name not in file_fields:
195
+ return item
196
+ if isinstance(item, list):
197
+ return [file(str(folder / path)) if isinstance(path, str) else path for path in item]
198
+ return file(str(folder / item)) if isinstance(item, str) else item
199
+
200
+ input = {name: value(name, item) for name, item in test_inputs.items()}
201
+ call = abyss._start(None)
202
+ press = abyss._press(call, widget, input, None, None, hold=True, version=version)
203
+ reply = press if _has_ended(press) else abyss._hold(call, abyss._wait_url(press), _has_ended)
204
+ assert reply.run is not None
205
+ return reply.run
206
+
207
+
208
+ def _save_listing(abyss: Abyss, folder: Path, widget: str, publish_file: dict[str, Any]) -> dict[str, Any]:
209
+ """Saves the Publish File's Listing Fields, ``private`` unless it says, and sends the
210
+ thumbnail it names first. Answers the listing as saved."""
211
+ widget_url = abyss._widget_url(widget)
212
+ save = {name: publish_file[name] for name in LISTING_FIELDS if name in publish_file}
213
+ save.setdefault("visibility", "private")
214
+ thumbnail = publish_file.get("thumbnail")
215
+ if thumbnail:
216
+ path = folder / thumbnail
217
+ data = path.read_bytes()
218
+ call = abyss._start(None)
219
+ body = json.dumps({"filename": path.name, "size": len(data)}).encode()
220
+ grant = parse_upload(
221
+ _expect(
222
+ abyss._send(call, "POST", f"{widget_url}/listing/thumbnail", JSON, body),
223
+ _is_upload,
224
+ "The thumbnail answered without an id and a form.",
225
+ )
226
+ )
227
+ abyss._store(call, grant.upload.url, grant.upload.fields, "thumbnail", path.name, data)
228
+ save["thumbnail"] = grant.id
229
+ return _expect(
230
+ abyss._send(abyss._start(None), "PATCH", f"{widget_url}/listing", JSON, json.dumps(save).encode()),
231
+ _is_listing,
232
+ "The listing answered without its revision.",
233
+ )
234
+
235
+
236
+ def _read_json(path: Path, code: str) -> Any:
237
+ try:
238
+ return json.loads(path.read_text("utf-8"))
239
+ except FileNotFoundError:
240
+ raise AbyssError(code, f"{path} is missing.") from None
241
+ except ValueError as error:
242
+ raise AbyssError(code, f"{path} is not valid JSON: {error}") from None
243
+
244
+
245
+ def _write_block(folder: Path, publish_file: dict[str, Any], block: dict[str, Any]) -> None:
246
+ """Writes the ``widget`` block into the Publish File: which Widget the folder is."""
247
+ publish_file["widget"] = block
248
+ (folder / PUBLISH_FILE).write_text(json.dumps(publish_file, indent=2, ensure_ascii=False) + "\n", "utf-8")
249
+
250
+
251
+ def _holds_marker(path: Path, markers: list[str]) -> bool:
252
+ """Whether a folder holds a marker of a virtual environment: a file, or a folder when it ends in ``/``."""
253
+ for marker in markers:
254
+ if marker.endswith("/") and (path / marker.rstrip("/")).is_dir():
255
+ return True
256
+ if not marker.endswith("/") and (path / marker).is_file():
257
+ return True
258
+ return False
259
+
260
+
261
+ def _print_logs(logs: Any) -> None:
262
+ """Prints a Test Run's logs, which may be any JSON value."""
263
+ print("The Test Run's logs:", file=sys.stderr)
264
+ if logs is None:
265
+ print("(none)", file=sys.stderr)
266
+ elif isinstance(logs, str):
267
+ print(logs, file=sys.stderr)
268
+ elif isinstance(logs, list):
269
+ for line in logs:
270
+ print(line if isinstance(line, str) else json.dumps(line, ensure_ascii=False), file=sys.stderr)
271
+ else:
272
+ print(json.dumps(logs, indent=2, ensure_ascii=False), file=sys.stderr)
273
+
274
+
275
+ def _is_project_version(value: Any) -> bool:
276
+ if not isinstance(value, dict) or not isinstance(value.get("version"), int):
277
+ return False
278
+ upload = value.get("upload")
279
+ return (
280
+ isinstance(upload, dict)
281
+ and isinstance(upload.get("url"), str)
282
+ and isinstance(upload.get("fields"), dict)
283
+ and isinstance(upload.get("prefix"), str)
284
+ and isinstance(value.get("junk"), dict)
285
+ )
286
+
287
+
288
+ def _is_candidate(value: Any) -> bool:
289
+ return isinstance(value, dict) and isinstance(value.get("version"), int)
290
+
291
+
292
+ def _is_listing(value: Any) -> bool:
293
+ return isinstance(value, dict) and isinstance(value.get("listing_revision"), str)
@@ -1,6 +1,7 @@
1
1
  """What a recorded call's caller holds: its files on disk, and its input as a caller writes it."""
2
2
  from __future__ import annotations
3
3
 
4
+ import json
4
5
  from collections.abc import Iterator
5
6
  from contextlib import contextmanager
6
7
  from pathlib import Path
@@ -25,12 +26,14 @@ def caller_input(input: dict[str, Any], dir: Path, files: dict[str, str]) -> dic
25
26
 
26
27
 
27
28
  @contextmanager
28
- def with_files(files: dict[str, str]) -> Iterator[Path]:
29
- """A folder holding the caller's files, removed afterwards."""
29
+ def with_files(files: dict[str, Any]) -> Iterator[Path]:
30
+ """A folder holding the caller's files, removed afterwards. A file's path may name
31
+ sub-folders, and a content that is not text is written as JSON."""
30
32
  with TemporaryDirectory(prefix="abysshub-") as name:
31
33
  dir = Path(name)
32
34
  for path, content in files.items():
33
- (dir / path).write_bytes(content.encode())
35
+ (dir / path).parent.mkdir(parents=True, exist_ok=True)
36
+ (dir / path).write_bytes((content if isinstance(content, str) else json.dumps(content)).encode())
34
37
  yield dir
35
38
 
36
39
 
@@ -60,7 +60,7 @@ class Replay:
60
60
  # The caller stopped listening, as a timeout does during a hold.
61
61
  self.close_connection = True
62
62
 
63
- do_POST = do_GET
63
+ do_POST = do_PATCH = do_GET
64
64
 
65
65
  self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
66
66
  self._server.daemon_threads = True
@@ -0,0 +1,38 @@
1
+ """Every recorded command, run as ``abysshub`` with its folder against the fake server.
2
+ A command is the Python package's alone, so only pytest replays these recordings."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from caller import with_files
10
+ from fake_server import Replay, load_exchanges
11
+ from test_replay import KEY, assert_fields
12
+
13
+ from abysshub._command import main
14
+
15
+ COMMANDS = [recording for recording in load_exchanges() if "command" in recording["call"]]
16
+
17
+
18
+ @pytest.mark.parametrize("recording", COMMANDS, ids=[r["name"] for r in COMMANDS])
19
+ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
20
+ call = recording["call"]
21
+ outcome = recording["outcome"]
22
+ server = Replay(recording, KEY)
23
+ try:
24
+ with with_files(call["files"]) as dir:
25
+ monkeypatch.setenv("ABYSS_API_KEY", KEY)
26
+ monkeypatch.setenv("ABYSS_BASE_URL", server.base)
27
+ exit = main([*call["command"], str(dir)])
28
+ printed = capsys.readouterr()
29
+
30
+ assert server.problems == []
31
+ assert server.remaining() == 0, "every recorded request was sent"
32
+ assert exit == outcome["exit"], printed.err
33
+ for text in outcome["printed"]:
34
+ assert text in printed.out + printed.err, f"printed {text}"
35
+ for path, fields in outcome["written"].items():
36
+ assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
37
+ finally:
38
+ server.close()
@@ -1,4 +1,7 @@
1
+ import subprocess
2
+ import sys
1
3
  from importlib.metadata import metadata, requires
4
+ from pathlib import Path
2
5
 
3
6
  from packaging.requirements import Requirement
4
7
 
@@ -14,3 +17,11 @@ def test_pypi_page_says_the_job_carries_keywords_and_links_to_the_docs():
14
17
  assert "Abyss Widget" in meta["Summary"]
15
18
  assert {"abyss", "abysshub", "widget"} <= set(meta["Keywords"].split(","))
16
19
  assert "Homepage, https://abysshub.com/docs#api" in meta.get_all("Project-URL")
20
+
21
+
22
+ def test_the_command_runs_as_abysshub_and_as_python_m_abysshub():
23
+ script = Path(sys.executable).parent / "abysshub"
24
+ for command in ([str(script)], [sys.executable, "-m", "abysshub"]):
25
+ done = subprocess.run([*command, "publish", "--help"], capture_output=True, text=True)
26
+ assert done.returncode == 0, done.stderr
27
+ assert "folder" in done.stdout
@@ -1,5 +1,6 @@
1
1
  """Every recorded exchange the Python library covers, replayed through the fake server,
2
- by ``Abyss`` and by ``AsyncAbyss``. Each must reach the same outcome as in JS."""
2
+ by ``Abyss`` and by ``AsyncAbyss``. Each must reach the same outcome as in JS. A
3
+ recorded command is the Python package's alone, and ``test_command.py`` replays it."""
3
4
  from __future__ import annotations
4
5
 
5
6
  import asyncio
@@ -15,7 +16,7 @@ from abysshub import Abyss, AbyssError, AsyncAbyss, AsyncRun, FilesAsleepError,
15
16
  KEY = "abyss_sk_fake_for_tests"
16
17
  FILES_ASLEEP = {"files_asleep", "files_waking"}
17
18
  """The codes ``run.save()`` raises as ``FilesAsleepError``."""
18
- RECORDINGS = load_exchanges()
19
+ RECORDINGS = [recording for recording in load_exchanges() if "command" not in recording["call"]]
19
20
 
20
21
 
21
22
  def assert_fields(actual: Any, expected: Any, where: str) -> None:
File without changes
File without changes
File without changes