formfeed 0.3.26__tar.gz → 0.3.28__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: formfeed
3
- Version: 0.3.26
3
+ Version: 0.3.28
4
4
  Summary: Formfeed API client: template-based PDF and image generation (sync and async, httpx).
5
5
  Project-URL: Homepage, https://formfeed.dev
6
6
  Project-URL: Documentation, https://docs.formfeed.dev/api/sdks/python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "formfeed"
7
- version = "0.3.26"
7
+ version = "0.3.28"
8
8
  description = "Formfeed API client: template-based PDF and image generation (sync and async, httpx)."
9
9
  readme = "README.md"
10
10
  # PEP 639: the SPDX expression replaces the licence classifier, the two must not be combined
@@ -102,4 +102,4 @@ __all__ = [
102
102
  "verify_webhook_signature",
103
103
  ]
104
104
 
105
- __version__ = "0.3.26"
105
+ __version__ = "0.3.28"
@@ -0,0 +1,31 @@
1
+ """The SDK's half of the operations table (plan 34, decision 9).
2
+
3
+ ``operations.json`` names a method for every operation of the API, or why there is none.
4
+ ``packages/api-types/src/lib/sdk-fixtures.spec.ts`` holds the names to the API; this holds them to
5
+ both clients, so a renamed method fails here.
6
+ """
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+ import pytest
13
+
14
+ from formfeed import AsyncFormfeed, Formfeed
15
+
16
+ MAP = json.loads((Path(__file__).resolve().parents[1] / "operations.json").read_text(encoding="utf-8"))
17
+ NAMED = [(operation, path) for operation, path in MAP["operations"].items() if isinstance(path, str)]
18
+
19
+
20
+ def test_names_a_method_for_most_operations():
21
+ assert len(NAMED) > 50
22
+
23
+
24
+ @pytest.mark.parametrize("client_class", [Formfeed, AsyncFormfeed])
25
+ @pytest.mark.parametrize(("operation", "path"), NAMED)
26
+ def test_the_named_method_exists(client_class, operation, path):
27
+ client = client_class("ff_test_k", transport=httpx.MockTransport(lambda request: httpx.Response(200)))
28
+ target = client
29
+ for part in path.split("."):
30
+ target = getattr(target, part)
31
+ assert callable(target), f"{operation}: {path}"
@@ -0,0 +1,122 @@
1
+ """The test vectors every SDK reads (plan 34, decision 9).
2
+
3
+ Written by ``packages/api-types/src/lib/sdk-fixtures.spec.ts``: webhook signatures, retries and
4
+ problems, played through both clients as a caller meets them.
5
+ """
6
+
7
+ import asyncio
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+ import pytest
13
+
14
+ import formfeed.client as client_module
15
+ from formfeed import AsyncFormfeed, Formfeed, FormfeedError, verify_webhook_signature
16
+
17
+ VECTORS = Path(__file__).resolve().parents[2] / "api-types" / "fixtures" / "sdk"
18
+
19
+
20
+ def _load(name: str):
21
+ return json.loads((VECTORS / f"{name}.json").read_text(encoding="utf-8"))
22
+
23
+
24
+ WEBHOOKS = _load("webhook-signatures")
25
+ RETRIES = _load("retries")
26
+ PROBLEMS = _load("problems")
27
+
28
+
29
+ @pytest.mark.parametrize("case", WEBHOOKS["cases"], ids=lambda case: case["name"])
30
+ def test_webhook_signature(case):
31
+ body = case["body"] if case["body"] is not None else WEBHOOKS["body"]
32
+ valid = verify_webhook_signature(
33
+ WEBHOOKS["secret"],
34
+ case["header"],
35
+ body,
36
+ tolerance_seconds=WEBHOOKS["tolerance_seconds"],
37
+ now=WEBHOOKS["now"],
38
+ )
39
+ assert valid is case["valid"]
40
+
41
+
42
+ def _answering(answers):
43
+ """A transport handler that gives the answers in order and counts the requests."""
44
+ state = {"requests": 0}
45
+
46
+ def handler(request: httpx.Request) -> httpx.Response:
47
+ answer = answers[state["requests"]]
48
+ state["requests"] += 1
49
+ if answer.get("network_error"):
50
+ raise httpx.ConnectError("connection refused", request=request)
51
+ headers = {"retry-after": answer["retry_after"]} if answer.get("retry_after") else {}
52
+ return httpx.Response(answer["status"], json=answer.get("body", {}), headers=headers)
53
+
54
+ return handler, state
55
+
56
+
57
+ def _outcome(call):
58
+ try:
59
+ call()
60
+ return {"ok": True}
61
+ except FormfeedError as error:
62
+ return {"error": {"code": error.code, "status": error.status}}
63
+
64
+
65
+ def _check(case, waits, requests):
66
+ assert requests == len(case["answers"])
67
+ assert len(waits) == len(case["waits_ms"])
68
+ for wait, (lowest, highest) in zip(waits, case["waits_ms"]):
69
+ assert lowest - 1e-6 <= wait <= highest + 1e-6
70
+
71
+
72
+ # the lowest jitter and the highest, so both ends of every wait's bounds are met
73
+ @pytest.mark.parametrize("jitter", [0.0, 0.999999])
74
+ @pytest.mark.parametrize("case", RETRIES["cases"], ids=lambda case: case["name"])
75
+ def test_retries(case, jitter, monkeypatch):
76
+ waits: list[float] = []
77
+ monkeypatch.setattr(client_module.random, "random", lambda: jitter)
78
+ monkeypatch.setattr(client_module.time, "sleep", lambda seconds: waits.append(seconds * 1000))
79
+ handler, state = _answering(case["answers"])
80
+ client = Formfeed("ff_test_k", transport=httpx.MockTransport(handler), max_retries=RETRIES["max_retries"])
81
+ assert _outcome(lambda: client.request("GET", "/account")) == case["outcome"]
82
+ _check(case, waits, state["requests"])
83
+
84
+
85
+ @pytest.mark.parametrize("jitter", [0.0, 0.999999])
86
+ @pytest.mark.parametrize("case", RETRIES["cases"], ids=lambda case: case["name"])
87
+ def test_retries_async(case, jitter, monkeypatch):
88
+ waits: list[float] = []
89
+
90
+ async def sleep(seconds: float) -> None:
91
+ waits.append(seconds * 1000)
92
+
93
+ monkeypatch.setattr(client_module.random, "random", lambda: jitter)
94
+ monkeypatch.setattr(client_module.asyncio, "sleep", sleep)
95
+ handler, state = _answering(case["answers"])
96
+
97
+ async def call():
98
+ async with AsyncFormfeed(
99
+ "ff_test_k", transport=httpx.MockTransport(handler), max_retries=RETRIES["max_retries"]
100
+ ) as client:
101
+ await client.request("GET", "/account")
102
+
103
+ assert _outcome(lambda: asyncio.run(call())) == case["outcome"]
104
+ _check(case, waits, state["requests"])
105
+
106
+
107
+ @pytest.mark.parametrize("case", PROBLEMS["cases"], ids=lambda case: case["name"])
108
+ def test_problem(case):
109
+ def handler(request: httpx.Request) -> httpx.Response:
110
+ body = case["body"]
111
+ if body is None:
112
+ return httpx.Response(case["status"], headers=case["headers"])
113
+ if isinstance(body, str):
114
+ return httpx.Response(case["status"], text=body, headers={**case["headers"], "content-type": "text/plain"})
115
+ return httpx.Response(case["status"], json=body, headers=case["headers"])
116
+
117
+ client = Formfeed("ff_test_k", transport=httpx.MockTransport(handler), max_retries=0)
118
+ with pytest.raises(FormfeedError) as raised:
119
+ client.request("GET", "/account")
120
+ error = raised.value
121
+ got = {"code": error.code, "message": error.message, "status": error.status, "request_id": error.request_id}
122
+ assert got == case["expect"]
File without changes
File without changes
File without changes