abysshub 1.0.1.dev8__tar.gz → 1.0.1.dev10__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.dev8 → abysshub-1.0.1.dev10}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/pyproject.toml +4 -1
  3. abysshub-1.0.1.dev10/src/abysshub/__main__.py +4 -0
  4. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_async_client.py +9 -6
  5. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_client.py +29 -19
  6. abysshub-1.0.1.dev10/src/abysshub/_command.py +416 -0
  7. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/caller.py +6 -3
  8. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/fake_server.py +1 -1
  9. abysshub-1.0.1.dev10/tests/test_command.py +57 -0
  10. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/test_package.py +11 -0
  11. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/test_replay.py +3 -2
  12. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/.gitignore +0 -0
  13. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/LICENSE +0 -0
  14. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/README.md +0 -0
  15. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/__init__.py +0 -0
  16. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_error.py +0 -0
  17. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_files.py +0 -0
  18. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_http.py +0 -0
  19. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_run.py +0 -0
  20. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/_types.py +0 -0
  21. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/src/abysshub/py.typed +0 -0
  22. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/conftest.py +0 -0
  23. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/test_client.py +0 -0
  24. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/test_files.py +0 -0
  25. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/tests/test_http.py +0 -0
  26. {abysshub-1.0.1.dev8 → abysshub-1.0.1.dev10}/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.dev8
3
+ Version: 1.0.1.dev10
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.dev8"
7
+ version = "1.0.1.dev10"
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,416 @@
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 dataclasses import dataclass
11
+ from fnmatch import fnmatchcase
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
16
+ from ._error import AbyssError
17
+ from ._files import file
18
+ from ._types import parse_upload
19
+
20
+ PUBLISH_FILE = "abyss.json"
21
+ TEST_INPUTS = "test_inputs.json"
22
+ INTERFACE = "interface.json"
23
+ ROOT_ENV = (".env", ".env.*")
24
+ """A root ``.env`` and its variants: never content, whatever the Junk list says."""
25
+ LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_runs")
26
+ """The Listing Fields the Publish File holds, beside its thumbnail."""
27
+ IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
28
+ """The extensions a thumbnail may have: an image's."""
29
+ JSON = {"Content-Type": "application/json"}
30
+
31
+
32
+ def main(argv: list[str] | None = None) -> int:
33
+ """Runs the command and answers its exit code."""
34
+ parser = argparse.ArgumentParser(prog="abysshub", description="Publish a Widget folder to Abyss.")
35
+ verbs = parser.add_subparsers(dest="verb", metavar="<verb>")
36
+ verbs.required = True
37
+ publish_verb = verbs.add_parser(
38
+ "publish",
39
+ help="publish a Widget folder and print its link",
40
+ description=f"Publish a Widget folder, with its {PUBLISH_FILE} and {TEST_INPUTS}, and print its link.",
41
+ )
42
+ publish_verb.add_argument("folder", type=Path)
43
+ args = parser.parse_args(argv)
44
+ widget_folder, faults = _read_folder(args.folder)
45
+ try:
46
+ abyss = Abyss()
47
+ except AbyssError as error:
48
+ return _stop([*faults, (error.code, error.message)])
49
+ with abyss:
50
+ faults.extend(_key_faults(abyss))
51
+ if faults:
52
+ return _stop(faults)
53
+ try:
54
+ print(publish(abyss, args.folder, widget_folder))
55
+ except AbyssError as error:
56
+ print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
57
+ if error.request_id:
58
+ print(f"request_id: {error.request_id}", file=sys.stderr)
59
+ return 1
60
+ except OSError as error:
61
+ # A file the folder names changed or became unreadable after the check.
62
+ print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
63
+ return 1
64
+ return 0
65
+
66
+
67
+ @dataclass
68
+ class _Folder:
69
+ """A Widget folder as the command read it, before it sent anything."""
70
+
71
+ publish_file: dict[str, Any]
72
+ interface: list[Any] | None
73
+ test_input: dict[str, Any]
74
+ """The Test Run's input: the Test Inputs, and the default of each Field they leave out."""
75
+
76
+
77
+ def _stop(faults: list[tuple[str, str]]) -> int:
78
+ """Prints every fault, one line each with its code, and answers the exit code."""
79
+ for code, message in faults:
80
+ print(f"abysshub: stopped: {code}: {message}", file=sys.stderr)
81
+ return 1
82
+
83
+
84
+ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
85
+ """Reads the folder and finds every fault it shows on its own, all of them and not
86
+ only the first, without a request: a publish takes minutes, a fault stops it now."""
87
+ faults: list[tuple[str, str]] = []
88
+ for name, code in (("run.py", "run_py_missing"), ("requirements.txt", "requirements_missing")):
89
+ if not (folder / name).is_file():
90
+ faults.append((code, f"The folder has no {name}."))
91
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file", dict, faults)
92
+ if publish_file is not None:
93
+ _check_listing(folder, publish_file, faults)
94
+ has_interface = (folder / INTERFACE).is_file()
95
+ interface = _read_json(folder / INTERFACE, "interface", list, faults) if has_interface else None
96
+ test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs", dict, faults) if (folder / TEST_INPUTS).is_file() else {}
97
+ test_input: dict[str, Any] = {}
98
+ # An invalid interface.json skips the Field checks rather than calling every Test Input unknown.
99
+ if test_inputs is not None and (interface is not None or not has_interface):
100
+ test_input = _check_test_inputs(folder, interface or [], test_inputs, faults)
101
+ return _Folder(publish_file or {}, interface, test_input), faults
102
+
103
+
104
+ def _check_listing(folder: Path, publish_file: dict[str, Any], faults: list[tuple[str, str]]) -> None:
105
+ """The Publish File's faults: no title, no tag, and a thumbnail that is missing on a
106
+ first publish or names no image file in the folder."""
107
+ block = publish_file.get("widget") or {}
108
+ if not isinstance(block, dict):
109
+ faults.append(("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object."))
110
+ title = publish_file.get("title")
111
+ if not isinstance(title, str) or not title.strip():
112
+ faults.append(("title_missing", f"{PUBLISH_FILE} has no title."))
113
+ tags = publish_file.get("tags")
114
+ if not isinstance(tags, list) or not any(isinstance(tag, str) and tag.strip() for tag in tags):
115
+ faults.append(("tag_missing", f"{PUBLISH_FILE} has no tag in tags."))
116
+ thumbnail = publish_file.get("thumbnail")
117
+ if not thumbnail:
118
+ if not (isinstance(block, dict) and "version" in block):
119
+ faults.append(("thumbnail_missing", f"A first publish needs a thumbnail, and {PUBLISH_FILE} names none."))
120
+ elif not (isinstance(thumbnail, str) and Path(thumbnail).suffix.lower() in IMAGES and _names_file(folder, thumbnail)):
121
+ faults.append(
122
+ ("thumbnail_not_image", f"The thumbnail {thumbnail!r} names no image file ({', '.join(IMAGES)}) in the folder.")
123
+ )
124
+
125
+
126
+ def _check_test_inputs(
127
+ folder: Path, interface: list[Any], test_inputs: dict[str, Any], faults: list[tuple[str, str]]
128
+ ) -> dict[str, Any]:
129
+ """The Test Inputs' faults against ``interface.json``: a name that is no Field, a
130
+ required Field with no value and no default, and a file Field's value that names no
131
+ file in the folder. Answers the Test Run's input, with the defaults filled in."""
132
+ fields = {
133
+ field["name"]: field for field in interface if isinstance(field, dict) and isinstance(field.get("name"), str)
134
+ }
135
+ for name in test_inputs:
136
+ if name not in fields:
137
+ faults.append(("test_input_unknown", f"{TEST_INPUTS} names {name!r}, which {INTERFACE} has no Field for."))
138
+ defaults = {name: field["default"] for name, field in fields.items() if "default" in field}
139
+ test_input = {**defaults, **test_inputs}
140
+ for name, field in fields.items():
141
+ value = test_input.get(name)
142
+ if value is None:
143
+ # A Field without isRequired counts as required.
144
+ if field.get("isRequired", True) is not False:
145
+ faults.append(("test_input_missing", f"The required Field {name!r} has no value in {TEST_INPUTS} and no default."))
146
+ elif field.get("type") == "file":
147
+ for path in value if isinstance(value, list) else [value]:
148
+ if not _names_file(folder, path):
149
+ faults.append(("test_input_file_missing", f"The file Field {name!r} names {path!r}, no file inside the folder."))
150
+ return test_input
151
+
152
+
153
+ def _key_faults(abyss: Abyss) -> list[tuple[str, str]]:
154
+ """The key's fault, read with ``GET /v1/key``: it is refused, or it does not manage Widgets."""
155
+ try:
156
+ key = abyss._get(abyss._start(None), f"{abyss.base_url}/v1/key", _is_key, "The key answered without a key.")
157
+ except AbyssError as error:
158
+ return [(error.code, error.message)]
159
+ if key.get("manage_widgets") is not True:
160
+ return [
161
+ (
162
+ "manage_widgets_required",
163
+ f"The key {key.get('key')} does not manage Widgets. Make a new key in your Cave, under Your API keys, "
164
+ "with Create a key and Manage Widgets switched on: a key is never given it after it is made.",
165
+ )
166
+ ]
167
+ return []
168
+
169
+
170
+ def _names_file(folder: Path, path: Any) -> bool:
171
+ """Whether ``path`` names a file inside the folder."""
172
+ if not isinstance(path, str) or not path:
173
+ return False
174
+ target = (folder / path).resolve()
175
+ return target.is_file() and folder.resolve() in target.parents
176
+
177
+
178
+ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder) -> str:
179
+ """Publishes a folder that was never published, and answers the Widget's link.
180
+
181
+ A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
182
+ number once committed, so a publish that stops is taken up again on the same Draft.
183
+ """
184
+ publish_file = widget_folder.publish_file
185
+ interface = widget_folder.interface
186
+ block = publish_file.get("widget") or {}
187
+ if "version" in block:
188
+ raise AbyssError(
189
+ "widget_published",
190
+ f"This folder is {block.get('id')}, published already; this abysshub publishes a new Widget only.",
191
+ )
192
+
193
+ widget = block.get("id")
194
+ if widget is None:
195
+ draft = _expect(
196
+ abyss._send(abyss._start(None), "POST", f"{abyss.base_url}/v1/widgets", retries=0),
197
+ _is_widget,
198
+ "The Draft answered without an id.",
199
+ )
200
+ widget = draft["id"]
201
+ _write_block(folder, publish_file, {"id": widget})
202
+ print(f"Made the Draft {widget}.")
203
+ else:
204
+ print(f"Publishing the Draft {widget}.")
205
+ widget_url = abyss._widget_url(widget)
206
+
207
+ base = json.dumps({"base_version": block.get("candidate")}).encode()
208
+ opened = _expect(
209
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions", JSON, base),
210
+ _is_project_version,
211
+ "The version answered without its number, form and Junk list.",
212
+ )
213
+ sent, left_out = _folder_files(folder, opened["junk"], publish_file.get("thumbnail"))
214
+ for path in left_out:
215
+ print(f"Left out {path}")
216
+ upload = opened["upload"]
217
+ for path in sent:
218
+ fields = {**upload["fields"], "key": f"{upload['prefix']}/{path}"}
219
+ data = (folder / path).read_bytes()
220
+ abyss._store(abyss._start(None), upload["url"], fields, path, Path(path).name, data)
221
+ print(f"Sent {len(sent)} files.")
222
+
223
+ version = opened["version"]
224
+ commit = json.dumps({} if interface is None else {"interface": interface}).encode()
225
+ candidate = _expect(
226
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions/{version}/commit", JSON, commit),
227
+ _is_candidate,
228
+ "The commit answered without a Candidate.",
229
+ )
230
+ _write_block(folder, publish_file, {"id": widget, "candidate": candidate["version"]})
231
+
232
+ print(f"Test Run of version {candidate['version']}...")
233
+ run = _test_run(abyss, folder, widget, candidate["version"], widget_folder.test_input, interface)
234
+ if run["status"] == "failed":
235
+ _print_logs(run.get("logs"))
236
+ error = run.get("error") or {}
237
+ raise AbyssError(
238
+ error.get("code", "platform_fault"),
239
+ f"The Test Run {run['id']} failed, so nothing was published. {error.get('message', '')}".rstrip(),
240
+ run_id=run["id"],
241
+ )
242
+
243
+ listing = _save_listing(abyss, folder, widget, publish_file)
244
+ published = _expect(
245
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/publish"),
246
+ _is_widget,
247
+ "The publish answered without the Widget.",
248
+ )
249
+ _write_block(
250
+ folder,
251
+ publish_file,
252
+ {"id": widget, "version": candidate["version"], "listing_revision": listing["listing_revision"]},
253
+ )
254
+ return str(published["url"])
255
+
256
+
257
+ def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
258
+ """The folder's files to send, and what it leaves out, by their paths in the folder:
259
+ what the Junk list names, the Publish File, its thumbnail, and a root ``.env`` with its
260
+ variants. A folder that is left out is named once, with a ``/``."""
261
+ names = junk.get("names") or []
262
+ markers = junk.get("markers") or []
263
+ root_names = [*(junk.get("root") or []), *ROOT_ENV]
264
+ skipped = {PUBLISH_FILE}
265
+ if thumbnail:
266
+ skipped.add(Path(thumbnail).as_posix())
267
+ sent: list[str] = []
268
+ left_out: list[str] = []
269
+ for top, dirs, files in os.walk(folder):
270
+ here = Path(top)
271
+ at_root = here == folder
272
+ kept_dirs = []
273
+ for name in sorted(dirs):
274
+ path = here / name
275
+ if any(fnmatchcase(name, pattern) for pattern in names) or _holds_marker(path, markers):
276
+ left_out.append(f"{path.relative_to(folder).as_posix()}/")
277
+ else:
278
+ kept_dirs.append(name)
279
+ dirs[:] = kept_dirs
280
+ for name in sorted(files):
281
+ relative = (here / name).relative_to(folder).as_posix()
282
+ if (
283
+ any(fnmatchcase(name, pattern) for pattern in names)
284
+ or (at_root and any(fnmatchcase(name, pattern) for pattern in root_names))
285
+ or relative in skipped
286
+ ):
287
+ left_out.append(relative)
288
+ else:
289
+ sent.append(relative)
290
+ return sent, left_out
291
+
292
+
293
+ def _test_run(
294
+ abyss: Abyss,
295
+ folder: Path,
296
+ widget: str,
297
+ version: int,
298
+ test_input: dict[str, Any],
299
+ interface: list[Any] | None,
300
+ ) -> dict[str, Any]:
301
+ """Makes the Test Run of the Candidate from its input and waits for its ending,
302
+ as ``run()`` waits. A file Field's value is a path in the folder, uploaded for that
303
+ Candidate. Answers the run, failed or not."""
304
+ file_fields = {
305
+ field.get("name") for field in interface or [] if isinstance(field, dict) and field.get("type") == "file"
306
+ }
307
+
308
+ def value(name: str, item: Any) -> Any:
309
+ if name not in file_fields:
310
+ return item
311
+ if isinstance(item, list):
312
+ return [file(str(folder / path)) if isinstance(path, str) else path for path in item]
313
+ return file(str(folder / item)) if isinstance(item, str) else item
314
+
315
+ input = {name: value(name, item) for name, item in test_input.items()}
316
+ call = abyss._start(None)
317
+ press = abyss._press(call, widget, input, None, None, hold=True, version=version)
318
+ reply = press if _has_ended(press) else abyss._hold(call, abyss._wait_url(press), _has_ended)
319
+ assert reply.run is not None
320
+ return reply.run
321
+
322
+
323
+ def _save_listing(abyss: Abyss, folder: Path, widget: str, publish_file: dict[str, Any]) -> dict[str, Any]:
324
+ """Saves the Publish File's Listing Fields, ``private`` unless it says, and sends the
325
+ thumbnail it names first. Answers the listing as saved."""
326
+ widget_url = abyss._widget_url(widget)
327
+ save = {name: publish_file[name] for name in LISTING_FIELDS if name in publish_file}
328
+ save.setdefault("visibility", "private")
329
+ thumbnail = publish_file.get("thumbnail")
330
+ if thumbnail:
331
+ path = folder / thumbnail
332
+ data = path.read_bytes()
333
+ call = abyss._start(None)
334
+ body = json.dumps({"filename": path.name, "size": len(data)}).encode()
335
+ grant = parse_upload(
336
+ _expect(
337
+ abyss._send(call, "POST", f"{widget_url}/listing/thumbnail", JSON, body),
338
+ _is_upload,
339
+ "The thumbnail answered without an id and a form.",
340
+ )
341
+ )
342
+ abyss._store(call, grant.upload.url, grant.upload.fields, "thumbnail", path.name, data)
343
+ save["thumbnail"] = grant.id
344
+ return _expect(
345
+ abyss._send(abyss._start(None), "PATCH", f"{widget_url}/listing", JSON, json.dumps(save).encode()),
346
+ _is_listing,
347
+ "The listing answered without its revision.",
348
+ )
349
+
350
+
351
+ def _read_json(path: Path, kind: str, shape: type, faults: list[tuple[str, str]]) -> Any:
352
+ """Reads a JSON file of the folder, or adds its fault and answers None: ``<kind>_missing``
353
+ when it is absent, ``<kind>_invalid`` when it is not JSON of that shape."""
354
+ try:
355
+ value = json.loads(path.read_text("utf-8"))
356
+ except FileNotFoundError:
357
+ faults.append((f"{kind}_missing", f"The folder has no {path.name}."))
358
+ return None
359
+ except (OSError, ValueError) as error:
360
+ faults.append((f"{kind}_invalid", f"{path.name} is not valid JSON: {error}"))
361
+ return None
362
+ if not isinstance(value, shape):
363
+ faults.append((f"{kind}_invalid", f"{path.name} is not a JSON {'object' if shape is dict else 'array'}."))
364
+ return None
365
+ return value
366
+
367
+
368
+ def _write_block(folder: Path, publish_file: dict[str, Any], block: dict[str, Any]) -> None:
369
+ """Writes the ``widget`` block into the Publish File: which Widget the folder is."""
370
+ publish_file["widget"] = block
371
+ (folder / PUBLISH_FILE).write_text(json.dumps(publish_file, indent=2, ensure_ascii=False) + "\n", "utf-8")
372
+
373
+
374
+ def _holds_marker(path: Path, markers: list[str]) -> bool:
375
+ """Whether a folder holds a marker of a virtual environment: a file, or a folder when it ends in ``/``."""
376
+ for marker in markers:
377
+ if marker.endswith("/") and (path / marker.rstrip("/")).is_dir():
378
+ return True
379
+ if not marker.endswith("/") and (path / marker).is_file():
380
+ return True
381
+ return False
382
+
383
+
384
+ def _print_logs(logs: Any) -> None:
385
+ """Prints a Test Run's logs, which may be any JSON value."""
386
+ print("The Test Run's logs:", file=sys.stderr)
387
+ if logs is None:
388
+ print("(none)", file=sys.stderr)
389
+ elif isinstance(logs, str):
390
+ print(logs, file=sys.stderr)
391
+ elif isinstance(logs, list):
392
+ for line in logs:
393
+ print(line if isinstance(line, str) else json.dumps(line, ensure_ascii=False), file=sys.stderr)
394
+ else:
395
+ print(json.dumps(logs, indent=2, ensure_ascii=False), file=sys.stderr)
396
+
397
+
398
+ def _is_project_version(value: Any) -> bool:
399
+ if not isinstance(value, dict) or not isinstance(value.get("version"), int):
400
+ return False
401
+ upload = value.get("upload")
402
+ return (
403
+ isinstance(upload, dict)
404
+ and isinstance(upload.get("url"), str)
405
+ and isinstance(upload.get("fields"), dict)
406
+ and isinstance(upload.get("prefix"), str)
407
+ and isinstance(value.get("junk"), dict)
408
+ )
409
+
410
+
411
+ def _is_candidate(value: Any) -> bool:
412
+ return isinstance(value, dict) and isinstance(value.get("version"), int)
413
+
414
+
415
+ def _is_listing(value: Any) -> bool:
416
+ 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,57 @@
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()
39
+
40
+
41
+ def test_publish_without_a_key_prints_every_fault_and_sends_nothing(
42
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
43
+ ) -> None:
44
+ server = Replay({"exchanges": []}, KEY)
45
+ try:
46
+ with with_files({"run.py": "print('words')\n", "requirements.txt": "\n"}) as dir:
47
+ monkeypatch.delenv("ABYSS_API_KEY", raising=False)
48
+ monkeypatch.setenv("ABYSS_BASE_URL", server.base)
49
+ exit = main(["publish", str(dir)])
50
+ printed = capsys.readouterr()
51
+
52
+ assert server.problems == []
53
+ assert exit == 1
54
+ assert "publish_file_missing" in printed.err
55
+ assert "invalid_api_key" in printed.err
56
+ finally:
57
+ 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