lumaflow-sdk 0.1.0a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ /dist/
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evan Song
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.5
2
+ Name: lumaflow-sdk
3
+ Version: 0.1.0a1
4
+ Summary: Python client for the Luma Flow business workflow API
5
+ Project-URL: Homepage, https://songhonglei.github.io/LumaFlow/
6
+ Project-URL: Documentation, https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-python.md
7
+ Project-URL: Repository, https://github.com/Songhonglei/LumaFlow
8
+ Project-URL: Issues, https://github.com/Songhonglei/LumaFlow/issues
9
+ Author: Evan Song
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Luma Flow Python SDK
19
+
20
+ Connect Python services to a self-hosted Luma Flow instance. The first alpha
21
+ supports Python 3.11 and later and uses only the Python standard library at runtime.
22
+ It requires a Luma Flow server with the `/api/work/v1` business API and Webhook
23
+ support. The SDK uses published workflow versions.
24
+
25
+ [Self-hosting](https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-self-host.md) ·
26
+ [中文指南](https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-python.md)
27
+
28
+ ## Install from source
29
+
30
+ From the Luma Flow repository root:
31
+
32
+ ```sh
33
+ python3 -m pip install ./sdk/python
34
+ ```
35
+
36
+ ## Submit and read a task
37
+
38
+ Use a personal access token from the server. Set `LUMAFLOW_URL` to its base URL
39
+ and supply `LUMAFLOW_TOKEN` from your credential store. Use HTTPS for remote
40
+ services. Use stable IDs and event keys in integrations that run unattended.
41
+
42
+ ```python
43
+ import os
44
+ from lumaflow import LumaFlowClient
45
+
46
+ client = LumaFlowClient(os.environ["LUMAFLOW_URL"], os.environ["LUMAFLOW_TOKEN"])
47
+ spaces = client.list_spaces()
48
+ apps = client.list_apps(spaces[0]["id"])
49
+ workflows = client.list_workflows(apps[0]["id"])
50
+
51
+ # Example for the supplier review workflow. Use your workflow's fields.
52
+ run = client.start_run(
53
+ apps[0]["id"],
54
+ workflows[0]["id"],
55
+ {"supplier": "Example A", "summary": "New supplier", "kind": "已补齐"},
56
+ idempotency_key="supplier-request-001",
57
+ )
58
+ result = client.get_run(run["id"])
59
+ print(result["status"])
60
+ for artifact in result["evidence"]:
61
+ data = client.get_evidence(run["id"], artifact["id"], attempt=artifact["attempt"])
62
+ print(artifact["name"], data)
63
+ ```
64
+
65
+ The task may still be queued, running, or awaiting approval when queried.
66
+ The example assumes that the first workspace, workbench and workflow are the
67
+ supplier review example. Inspect `fields` to obtain the exact keys and options
68
+ for your workflow. A text attachment uses `{"name": "proof.txt", "text": "..."}`.
69
+
70
+ ## Trigger a Webhook
71
+
72
+ Use the full endpoint and dedicated key from the trigger's configuration.
73
+ The Webhook returns a run ID. Query it with a personal token for an account
74
+ with access to the run.
75
+
76
+ ```python
77
+ import os
78
+ from lumaflow import trigger_webhook
79
+
80
+ run_id = trigger_webhook(
81
+ os.environ["LUMAFLOW_WEBHOOK_URL"],
82
+ os.environ["LUMAFLOW_WEBHOOK_TOKEN"],
83
+ {"supplier": "Example A", "summary": "New supplier", "kind": "已补齐"},
84
+ idempotency_key="supplier-event-001",
85
+ )
86
+ ```
87
+
88
+ Use the same ASCII idempotency key and input if you retry the same submission.
89
+ A conflicting reuse of a key can return HTTP 409. The SDK does not retry or
90
+ follow redirects. `APIError.status_code` carries the server's HTTP status.
91
+ `TransportError` means the exchange failed and submission may already have been
92
+ accepted. `ProtocolError` signals an unexpected success response. The default
93
+ timeout is 30 seconds and can be set with `timeout=`.
@@ -0,0 +1,76 @@
1
+ # Luma Flow Python SDK
2
+
3
+ Connect Python services to a self-hosted Luma Flow instance. The first alpha
4
+ supports Python 3.11 and later and uses only the Python standard library at runtime.
5
+ It requires a Luma Flow server with the `/api/work/v1` business API and Webhook
6
+ support. The SDK uses published workflow versions.
7
+
8
+ [Self-hosting](https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-self-host.md) ·
9
+ [中文指南](https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-python.md)
10
+
11
+ ## Install from source
12
+
13
+ From the Luma Flow repository root:
14
+
15
+ ```sh
16
+ python3 -m pip install ./sdk/python
17
+ ```
18
+
19
+ ## Submit and read a task
20
+
21
+ Use a personal access token from the server. Set `LUMAFLOW_URL` to its base URL
22
+ and supply `LUMAFLOW_TOKEN` from your credential store. Use HTTPS for remote
23
+ services. Use stable IDs and event keys in integrations that run unattended.
24
+
25
+ ```python
26
+ import os
27
+ from lumaflow import LumaFlowClient
28
+
29
+ client = LumaFlowClient(os.environ["LUMAFLOW_URL"], os.environ["LUMAFLOW_TOKEN"])
30
+ spaces = client.list_spaces()
31
+ apps = client.list_apps(spaces[0]["id"])
32
+ workflows = client.list_workflows(apps[0]["id"])
33
+
34
+ # Example for the supplier review workflow. Use your workflow's fields.
35
+ run = client.start_run(
36
+ apps[0]["id"],
37
+ workflows[0]["id"],
38
+ {"supplier": "Example A", "summary": "New supplier", "kind": "已补齐"},
39
+ idempotency_key="supplier-request-001",
40
+ )
41
+ result = client.get_run(run["id"])
42
+ print(result["status"])
43
+ for artifact in result["evidence"]:
44
+ data = client.get_evidence(run["id"], artifact["id"], attempt=artifact["attempt"])
45
+ print(artifact["name"], data)
46
+ ```
47
+
48
+ The task may still be queued, running, or awaiting approval when queried.
49
+ The example assumes that the first workspace, workbench and workflow are the
50
+ supplier review example. Inspect `fields` to obtain the exact keys and options
51
+ for your workflow. A text attachment uses `{"name": "proof.txt", "text": "..."}`.
52
+
53
+ ## Trigger a Webhook
54
+
55
+ Use the full endpoint and dedicated key from the trigger's configuration.
56
+ The Webhook returns a run ID. Query it with a personal token for an account
57
+ with access to the run.
58
+
59
+ ```python
60
+ import os
61
+ from lumaflow import trigger_webhook
62
+
63
+ run_id = trigger_webhook(
64
+ os.environ["LUMAFLOW_WEBHOOK_URL"],
65
+ os.environ["LUMAFLOW_WEBHOOK_TOKEN"],
66
+ {"supplier": "Example A", "summary": "New supplier", "kind": "已补齐"},
67
+ idempotency_key="supplier-event-001",
68
+ )
69
+ ```
70
+
71
+ Use the same ASCII idempotency key and input if you retry the same submission.
72
+ A conflicting reuse of a key can return HTTP 409. The SDK does not retry or
73
+ follow redirects. `APIError.status_code` carries the server's HTTP status.
74
+ `TransportError` means the exchange failed and submission may already have been
75
+ accepted. `ProtocolError` signals an unexpected success response. The default
76
+ timeout is 30 seconds and can be set with `timeout=`.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.33.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lumaflow-sdk"
7
+ version = "0.1.0a1"
8
+ description = "Python client for the Luma Flow business workflow API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Evan Song"}]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://songhonglei.github.io/LumaFlow/"
22
+ Documentation = "https://github.com/Songhonglei/LumaFlow/blob/main/docs/lumaflow-python.md"
23
+ Repository = "https://github.com/Songhonglei/LumaFlow"
24
+ Issues = "https://github.com/Songhonglei/LumaFlow/issues"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/lumaflow"]
28
+
29
+ [tool.hatch.build.targets.sdist]
30
+ include = ["/src", "/tests", "/LICENSE", "/README.md"]
@@ -0,0 +1,13 @@
1
+ """Python client for the Luma Flow business workflow API."""
2
+
3
+ from ._client import LumaFlowClient, trigger_webhook
4
+ from ._http import APIError, LumaFlowError, ProtocolError, TransportError
5
+
6
+ __all__ = [
7
+ "APIError",
8
+ "LumaFlowClient",
9
+ "LumaFlowError",
10
+ "ProtocolError",
11
+ "TransportError",
12
+ "trigger_webhook",
13
+ ]
@@ -0,0 +1,92 @@
1
+ """Business workflow and Webhook clients."""
2
+
3
+ from typing import Any, Mapping
4
+ from urllib.parse import quote, urlencode
5
+
6
+ from ._http import ProtocolError, bearer, http_url, request_json, timeout_seconds
7
+
8
+ JSONObject = dict[str, Any]
9
+
10
+
11
+ def _segment(value: str) -> str:
12
+ if value in {"", ".", ".."} or "/" in value or "\\" in value:
13
+ raise ValueError("Expected a non-empty resource ID")
14
+ return quote(value, safe="")
15
+
16
+
17
+ def _object(payload: Any) -> JSONObject:
18
+ if not isinstance(payload, dict):
19
+ raise ProtocolError("Expected a JSON object")
20
+ return payload
21
+
22
+
23
+ def _objects(payload: Any) -> list[JSONObject]:
24
+ if not isinstance(payload, list):
25
+ raise ProtocolError("Expected a JSON array")
26
+ return [_object(item) for item in payload]
27
+
28
+
29
+ def _run_id(payload: JSONObject) -> str:
30
+ run_id = payload.get("id")
31
+ if not isinstance(run_id, str) or not run_id:
32
+ raise ProtocolError("Task acceptance response is missing a run ID")
33
+ return run_id
34
+
35
+
36
+ class LumaFlowClient:
37
+ """Call the business API using a personal API Token."""
38
+
39
+ def __init__(self, base_url: str, token: str, *, timeout: float = 30.0):
40
+ self._base = http_url(base_url).rstrip("/") + "/api/work/v1"
41
+ self._authorization = bearer(token)
42
+ self._timeout = timeout_seconds(timeout)
43
+
44
+ def _get(self, path: str) -> Any:
45
+ return request_json(self._base + path, self._authorization, self._timeout, 200)
46
+
47
+ def list_spaces(self) -> list[JSONObject]:
48
+ """List workspaces accessible to the token owner."""
49
+ return _objects(self._get("/spaces"))
50
+
51
+ def list_apps(self, space_id: str) -> list[JSONObject]:
52
+ """List workbenches in a workspace."""
53
+ return _objects(self._get("/apps?" + urlencode({"projectId": space_id})))
54
+
55
+ def list_workflows(self, app_id: str) -> list[JSONObject]:
56
+ """List published workflows and their input fields for a workbench."""
57
+ payload = _object(self._get(f"/apps/{_segment(app_id)}/workflows"))
58
+ return _objects(payload.get("workflows"))
59
+
60
+ def start_run(
61
+ self, app_id: str, release_id: str, inputs: Mapping[str, Any], *, idempotency_key: str
62
+ ) -> JSONObject:
63
+ """Submit a task and return its run summary. Persist the key for retries."""
64
+ payload = request_json(
65
+ self._base + "/runs", self._authorization, self._timeout, 202,
66
+ body={"appId": app_id, "releaseId": release_id, "input": dict(inputs)},
67
+ idempotency_key=idempotency_key,
68
+ )
69
+ run = _object(payload)
70
+ _run_id(run)
71
+ return run
72
+
73
+ def get_run(self, run_id: str) -> JSONObject:
74
+ """Return task status, nodes, approval history and evidence references."""
75
+ return _object(self._get(f"/runs/{_segment(run_id)}"))
76
+
77
+ def get_evidence(self, run_id: str, artifact_id: str, *, attempt: int) -> JSONObject:
78
+ """Read one JSON result using its evidence ID and recorded attempt."""
79
+ if type(attempt) is not int or attempt < 1:
80
+ raise ValueError("attempt must be a positive integer")
81
+ return _object(self._get(f"/runs/{_segment(run_id)}/evidence/{_segment(artifact_id)}?attempt={attempt}"))
82
+
83
+
84
+ def trigger_webhook(
85
+ url: str, token: str, inputs: Mapping[str, Any], *, idempotency_key: str, timeout: float = 30.0
86
+ ) -> str:
87
+ """Deliver an event using a scoped Webhook key and return the accepted run ID."""
88
+ payload = request_json(
89
+ http_url(url), bearer(token), timeout_seconds(timeout), 202,
90
+ body={"input": dict(inputs)}, idempotency_key=idempotency_key,
91
+ )
92
+ return _run_id(_object(payload))
@@ -0,0 +1,88 @@
1
+ """HTTP transport shared by the two authentication modes."""
2
+
3
+ import json
4
+ import math
5
+ from http.client import HTTPException
6
+ from urllib.error import HTTPError
7
+ from urllib.parse import urlsplit
8
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
9
+
10
+
11
+ class LumaFlowError(Exception):
12
+ """Base class for errors encountered while calling Luma Flow."""
13
+
14
+
15
+ class APIError(LumaFlowError):
16
+ """A non-success HTTP response with its status and optional API message."""
17
+
18
+ def __init__(self, status_code: int, message: str | None = None):
19
+ self.status_code = status_code
20
+ self.message = message
21
+ super().__init__(f"HTTP {status_code}" + (f": {message}" if message else ""))
22
+
23
+
24
+ class TransportError(LumaFlowError):
25
+ """The HTTP exchange failed. The server may already have accepted a write."""
26
+
27
+
28
+ class ProtocolError(LumaFlowError):
29
+ """A success response did not match the expected API contract."""
30
+
31
+
32
+ class _NoRedirects(HTTPRedirectHandler):
33
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
34
+ return None
35
+
36
+
37
+ def http_url(value: str) -> str:
38
+ if any(char.isspace() for char in value) or any(char in value for char in "?#\\"):
39
+ raise ValueError("Use an HTTP(S) URL without whitespace, query, or fragment")
40
+ parts = urlsplit(value)
41
+ if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username is not None:
42
+ raise ValueError("Use an HTTP(S) URL without embedded credentials")
43
+ _ = parts.port # Reject malformed ports before making a request.
44
+ return value
45
+
46
+
47
+ def bearer(token: str) -> str:
48
+ if not token or any(not 33 <= ord(char) <= 126 for char in token):
49
+ raise ValueError("Supply a non-empty bearer credential without whitespace")
50
+ return "Bearer " + token
51
+
52
+
53
+ def timeout_seconds(timeout: float) -> float:
54
+ if not math.isfinite(timeout) or timeout <= 0:
55
+ raise ValueError("timeout must be a positive, finite number of seconds")
56
+ return timeout
57
+
58
+
59
+ def request_json(url, authorization, timeout, expected_status, *, body=None, idempotency_key=None):
60
+ headers = {"Accept": "application/json", "Authorization": authorization}
61
+ data = None
62
+ if body is not None:
63
+ if (not idempotency_key or len(idempotency_key) > 100
64
+ or any(not 32 <= ord(char) <= 126 for char in idempotency_key)
65
+ or idempotency_key != idempotency_key.strip()):
66
+ raise ValueError("idempotency_key must be 1–100 printable ASCII bytes without surrounding spaces")
67
+ headers.update({"Content-Type": "application/json", "Idempotency-Key": idempotency_key})
68
+ data = json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8")
69
+ request = Request(url, data=data, headers=headers)
70
+ try:
71
+ with build_opener(_NoRedirects()).open(request, timeout=timeout) as response:
72
+ if response.status != expected_status:
73
+ raise ProtocolError(f"Expected HTTP {expected_status}, got HTTP {response.status}")
74
+ return json.load(response)
75
+ except HTTPError as error:
76
+ message = None
77
+ try:
78
+ with error:
79
+ payload = json.loads(error.read(8192))
80
+ if isinstance(payload, dict) and isinstance(payload.get("error"), str):
81
+ message = payload["error"].replace(authorization[7:], "[redacted]")
82
+ except (HTTPException, OSError, ValueError):
83
+ pass
84
+ raise APIError(error.code, message) from None
85
+ except (HTTPException, OSError):
86
+ raise TransportError("Luma Flow request failed or timed out") from None
87
+ except ValueError:
88
+ raise ProtocolError("Luma Flow returned invalid JSON") from None
@@ -0,0 +1,141 @@
1
+ import json
2
+ import threading
3
+ import unittest
4
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
+
6
+ from lumaflow import APIError, LumaFlowClient, ProtocolError, TransportError, trigger_webhook
7
+
8
+
9
+ class TestClient(unittest.TestCase):
10
+ def setUp(self):
11
+ self.calls = []
12
+ self.status = 200
13
+ self.payload = []
14
+ self.redirect = None
15
+ self.abort_response = False
16
+ test = self
17
+
18
+ class Handler(BaseHTTPRequestHandler):
19
+ def log_message(self, *args):
20
+ pass
21
+
22
+ def handle_request(self):
23
+ raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
24
+ test.calls.append((self.command, self.path, dict(self.headers), json.loads(raw) if raw else None))
25
+ if test.abort_response:
26
+ self.close_connection = True
27
+ return
28
+ self.send_response(test.status)
29
+ if test.redirect:
30
+ self.send_header("Location", test.redirect)
31
+ self.send_header("Content-Type", "application/json")
32
+ self.end_headers()
33
+ payload = test.payload if isinstance(test.payload, bytes) else json.dumps(test.payload).encode()
34
+ self.wfile.write(payload)
35
+
36
+ do_GET = do_POST = handle_request
37
+
38
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
39
+ worker = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01})
40
+ worker.start()
41
+ self.addCleanup(server.server_close)
42
+ self.addCleanup(worker.join)
43
+ self.addCleanup(server.shutdown)
44
+ self.base = f"http://127.0.0.1:{server.server_port}/platform"
45
+ self.client = LumaFlowClient(self.base + "/", "personal-test-token")
46
+
47
+ def test_list_spaces_apps_and_published_workflows(self):
48
+ self.payload = [{"id": "财务 & A"}]
49
+ self.assertEqual(self.client.list_spaces(), self.payload)
50
+ self.payload = [{"id": "reviews #1"}]
51
+ self.assertEqual(self.client.list_apps("财务 & A"), self.payload)
52
+ self.payload = {"app": self.payload[0], "workflows": [{"id": "release", "fields": []}]}
53
+ self.assertEqual(self.client.list_workflows("reviews #1"), self.payload["workflows"])
54
+ self.assertEqual([call[1] for call in self.calls], [
55
+ "/platform/api/work/v1/spaces",
56
+ "/platform/api/work/v1/apps?projectId=%E8%B4%A2%E5%8A%A1+%26+A",
57
+ "/platform/api/work/v1/apps/reviews%20%231/workflows",
58
+ ])
59
+ self.assertEqual(self.calls[0][2]["Authorization"], "Bearer personal-test-token")
60
+ self.assertNotIn("Origin", self.calls[0][2])
61
+
62
+ def test_start_and_read_run_and_evidence(self):
63
+ self.status, self.payload = 202, {"id": "run", "status": "queued"}
64
+ inputs = {"summary": "复核", "proof": {"name": "proof.txt", "text": "合成材料"}}
65
+ self.assertEqual(self.client.start_run("app", "release", inputs, idempotency_key="case-1"), self.payload)
66
+ method, path, headers, body = self.calls[0]
67
+ self.assertEqual((method, path), ("POST", "/platform/api/work/v1/runs"))
68
+ self.assertEqual(headers["Idempotency-Key"], "case-1")
69
+ self.assertNotIn("Origin", headers)
70
+ self.assertEqual(body, {"appId": "app", "releaseId": "release", "input": inputs})
71
+
72
+ self.status, self.payload = 200, {"status": "succeeded", "evidence": [{"id": "artifact", "attempt": 2}]}
73
+ self.assertEqual(self.client.get_run("run"), self.payload)
74
+ self.payload = {"count": 2}
75
+ self.assertEqual(self.client.get_evidence("run", "artifact", attempt=2), self.payload)
76
+ self.assertEqual(self.calls[1][1], "/platform/api/work/v1/runs/run")
77
+ self.assertEqual(self.calls[2][1], "/platform/api/work/v1/runs/run/evidence/artifact?attempt=2")
78
+
79
+ def test_webhook_uses_its_own_key_and_only_sends_input(self):
80
+ self.status, self.payload = 202, {"id": "from-webhook"}
81
+ delivery_url = self.base + "/api/work/v1/webhooks/example"
82
+ self.assertEqual(trigger_webhook(delivery_url, "webhook-test-key", {}, idempotency_key="event-1"), "from-webhook")
83
+ method, path, headers, body = self.calls[0]
84
+ self.assertEqual((method, path), ("POST", "/platform/api/work/v1/webhooks/example"))
85
+ self.assertEqual(headers["Authorization"], "Bearer webhook-test-key")
86
+ self.assertEqual(headers["Idempotency-Key"], "event-1")
87
+ self.assertEqual(body, {"input": {}})
88
+
89
+ def test_api_error_keeps_status_and_sanitizes_message(self):
90
+ for status in (400, 401, 403, 404, 409, 410, 413, 502):
91
+ with self.subTest(status=status):
92
+ self.status, self.payload = status, {"error": "rejected personal-test-token"}
93
+ with self.assertRaises(APIError) as caught:
94
+ self.client.list_spaces()
95
+ self.assertEqual(caught.exception.status_code, status)
96
+ self.assertEqual(caught.exception.message, "rejected [redacted]")
97
+ self.status, self.payload = 502, b"<html>upstream error</html>"
98
+ with self.assertRaisesRegex(APIError, "^HTTP 502$"):
99
+ self.client.list_spaces()
100
+
101
+ def test_redirects_are_not_followed(self):
102
+ self.redirect = self.base + "/other"
103
+ self.status = 302
104
+ with self.assertRaisesRegex(APIError, "HTTP 302"):
105
+ self.client.list_spaces()
106
+ with self.assertRaisesRegex(APIError, "HTTP 302"):
107
+ self.client.start_run("app", "release", {}, idempotency_key="event-1")
108
+ self.assertEqual(len(self.calls), 2)
109
+
110
+ def test_protocol_errors(self):
111
+ for payload in (b"bad JSON", {"unexpected": "shape"}, [True]):
112
+ with self.subTest(payload=payload), self.assertRaises(ProtocolError):
113
+ self.payload = payload
114
+ self.client.list_spaces()
115
+ self.status, self.payload = 202, {}
116
+ with self.assertRaises(ProtocolError):
117
+ self.client.start_run("app", "release", {}, idempotency_key="event-1")
118
+
119
+ def test_transport_error_does_not_repeat_write(self):
120
+ self.abort_response = True
121
+ with self.assertRaises(TransportError):
122
+ self.client.start_run("app", "release", {}, idempotency_key="event-1")
123
+ self.assertEqual(len(self.calls), 1)
124
+
125
+ def test_invalid_arguments_never_send_a_request(self):
126
+ for key in ("", "a" * 101, "事件", " trial", "line\nbreak"):
127
+ with self.subTest(key=key), self.assertRaises(ValueError):
128
+ self.client.start_run("app", "release", {}, idempotency_key=key)
129
+ for url in ("ftp://example.com", "https://user@example.com", "http://example.com?secret=no", "http://example.com:bad"):
130
+ with self.subTest(url=url), self.assertRaises(ValueError):
131
+ LumaFlowClient(url, "test-token")
132
+ for run_id in ("", "..", "a/b"):
133
+ with self.subTest(run_id=run_id), self.assertRaises(ValueError):
134
+ self.client.get_run(run_id)
135
+ with self.assertRaises(ValueError):
136
+ self.client.get_evidence("run", "artifact", attempt=0)
137
+ with self.assertRaises(ValueError):
138
+ LumaFlowClient(self.base, "invalid\r\ntoken")
139
+ with self.assertRaises(ValueError):
140
+ LumaFlowClient(self.base, "test-token", timeout=float("nan"))
141
+ self.assertEqual(self.calls, [])