recapi 0.4.11__tar.gz → 0.4.13__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.
- {recapi-0.4.11/recapi.egg-info → recapi-0.4.13}/PKG-INFO +5 -4
- {recapi-0.4.11 → recapi-0.4.13}/README.md +4 -3
- {recapi-0.4.11 → recapi-0.4.13}/pyproject.toml +1 -1
- {recapi-0.4.11 → recapi-0.4.13}/recapi/async_client.py +3 -3
- {recapi-0.4.11 → recapi-0.4.13}/recapi/client.py +47 -5
- {recapi-0.4.11 → recapi-0.4.13/recapi.egg-info}/PKG-INFO +5 -4
- {recapi-0.4.11 → recapi-0.4.13}/tests/test_async_client.py +13 -0
- {recapi-0.4.11 → recapi-0.4.13}/tests/test_client.py +16 -0
- {recapi-0.4.11 → recapi-0.4.13}/tests/test_client_vectors.py +42 -0
- {recapi-0.4.11 → recapi-0.4.13}/LICENSE +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi/__init__.py +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi/history.py +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi/py.typed +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/setup.cfg +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/tests/test_history.py +0 -0
- {recapi-0.4.11 → recapi-0.4.13}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.13
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://recapi.io
|
|
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
49
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
50
50
|
|
|
51
51
|
```sh
|
|
52
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
237
237
|
|
|
238
238
|
| Method | What it does |
|
|
239
239
|
|---|---|
|
|
240
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
240
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
241
241
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
243
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -272,7 +272,8 @@ batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
|
272
272
|
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
273
|
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
274
|
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
-
the items the API refused.
|
|
275
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
276
|
+
of its section on the errors page; its message ends with it.
|
|
276
277
|
|
|
277
278
|
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
278
279
|
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
@@ -26,7 +26,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
26
26
|
(the dashboard's quick start shows the line with your API's address):
|
|
27
27
|
|
|
28
28
|
```sh
|
|
29
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
29
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -214,7 +214,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
214
214
|
|
|
215
215
|
| Method | What it does |
|
|
216
216
|
|---|---|
|
|
217
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
217
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
218
218
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
219
219
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
220
220
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -249,7 +249,8 @@ batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
|
249
249
|
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
250
250
|
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
251
251
|
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
252
|
-
the items the API refused.
|
|
252
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
253
|
+
of its section on the errors page; its message ends with it.
|
|
253
254
|
|
|
254
255
|
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
255
256
|
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.13"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -70,9 +70,9 @@ class AsyncClient:
|
|
|
70
70
|
# serve the fallback. Past its deadline, the call asks only for popular items.
|
|
71
71
|
return await asyncio.to_thread(fn, deadline, *args, **params)
|
|
72
72
|
|
|
73
|
-
async def track(self, item_id: str, level: int | str, **
|
|
74
|
-
"""Record an interaction: :meth:`Client.track`."""
|
|
75
|
-
await self._run(self._client.track, item_id, level, **
|
|
73
|
+
async def track(self, item_id: str, level: int | str, **fields: Any) -> None:
|
|
74
|
+
"""Record an interaction (ids, value, currency): :meth:`Client.track`."""
|
|
75
|
+
await self._run(self._client.track, item_id, level, **fields)
|
|
76
76
|
|
|
77
77
|
async def identify(self, anon_id: str, user_id: str) -> None:
|
|
78
78
|
"""At login, the visitor's history becomes the user's: :meth:`Client.identify`."""
|
|
@@ -14,6 +14,7 @@ import hashlib
|
|
|
14
14
|
import http.client
|
|
15
15
|
import json
|
|
16
16
|
import logging
|
|
17
|
+
import math
|
|
17
18
|
import os
|
|
18
19
|
import random
|
|
19
20
|
import threading
|
|
@@ -29,7 +30,7 @@ from typing import Any, Protocol
|
|
|
29
30
|
|
|
30
31
|
from .history import History, is_id
|
|
31
32
|
|
|
32
|
-
__version__ = "0.4.
|
|
33
|
+
__version__ = "0.4.13"
|
|
33
34
|
|
|
34
35
|
log = logging.getLogger("recapi")
|
|
35
36
|
Tags = Sequence[str] | None
|
|
@@ -114,16 +115,27 @@ class RecapiError(Exception):
|
|
|
114
115
|
|
|
115
116
|
``code`` is the API's error code (``invalid_request``, ``rate_limited``,
|
|
116
117
|
``quota_exceeded``...) or a client one: ``network``, ``timeout``,
|
|
117
|
-
``invalid_response``.
|
|
118
|
+
``invalid_response``. ``docs_url`` is the errors page's section for an
|
|
119
|
+
API error, from its body (None when the API sent none, and for a client
|
|
120
|
+
code); the error's text then ends with ``, see <docs_url>``.
|
|
118
121
|
"""
|
|
119
122
|
|
|
120
123
|
def __init__(
|
|
121
|
-
self,
|
|
124
|
+
self,
|
|
125
|
+
code: str,
|
|
126
|
+
message: str,
|
|
127
|
+
*,
|
|
128
|
+
status: int = 0,
|
|
129
|
+
retry_after: float | None = None,
|
|
130
|
+
docs_url: str | None = None,
|
|
122
131
|
) -> None:
|
|
123
|
-
|
|
132
|
+
# The address ends the text, so the log line or traceback that
|
|
133
|
+
# prints the error names its fix.
|
|
134
|
+
super().__init__(f"{message}, see {docs_url}" if docs_url else message)
|
|
124
135
|
self.code = code
|
|
125
136
|
self.status = status
|
|
126
137
|
self.retry_after = retry_after
|
|
138
|
+
self.docs_url = docs_url or None
|
|
127
139
|
|
|
128
140
|
@property
|
|
129
141
|
def retryable(self) -> bool:
|
|
@@ -467,19 +479,24 @@ class Client:
|
|
|
467
479
|
user_id: str | None = None,
|
|
468
480
|
anon_id: str | None = None,
|
|
469
481
|
recommendation_id: str | None = None,
|
|
482
|
+
value: float | None = None,
|
|
483
|
+
currency: str | None = None,
|
|
470
484
|
) -> None:
|
|
471
485
|
"""Record an interaction: the user's history changes at once, the event is queued.
|
|
472
486
|
|
|
473
487
|
``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
|
|
474
488
|
``purchase`` (10), ``reject`` (-10: never recommend the item to this
|
|
475
489
|
user again until a positive event on it). ``recommendation_id``
|
|
476
|
-
overrides the automatic attribution.
|
|
490
|
+
overrides the automatic attribution. ``value`` is what the buyer paid for
|
|
491
|
+
a purchase's line (0 for a free one), ``currency`` its ISO 4217 code; a
|
|
492
|
+
currency needs a value. Raises ``ValueError`` on a bad level, amount
|
|
477
493
|
or a bad user, visitor or recommendation id. An ``item_id`` the API would
|
|
478
494
|
refuse isn't one: a page often takes it from a visitor's URL, so the
|
|
479
495
|
event is dropped and logged instead.
|
|
480
496
|
"""
|
|
481
497
|
level = _level(level)
|
|
482
498
|
_check_ids(user_id=user_id, anon_id=anon_id, recommendation_id=recommendation_id)
|
|
499
|
+
_check_amount(value, currency)
|
|
483
500
|
# A crafted link must not fail the page. Nothing is kept: in the history
|
|
484
501
|
# it would make the API refuse every later list. The line never quotes
|
|
485
502
|
# the visitor's id.
|
|
@@ -510,6 +527,8 @@ class Client:
|
|
|
510
527
|
"user_id": user_id,
|
|
511
528
|
"anon_id": anon_id,
|
|
512
529
|
"recommendation_id": attributed,
|
|
530
|
+
"value": value,
|
|
531
|
+
"currency": currency,
|
|
513
532
|
"timestamp": _iso(t),
|
|
514
533
|
"event_id": str(uuid.uuid4()),
|
|
515
534
|
}
|
|
@@ -1211,11 +1230,15 @@ def _http_error(status: int, headers: Any, text: bytes) -> RecapiError:
|
|
|
1211
1230
|
or _CODE_BY_STATUS.get(status)
|
|
1212
1231
|
or ("internal" if status >= 500 else "http_error")
|
|
1213
1232
|
)
|
|
1233
|
+
# Only a string: an older server sends none, and a proxy's odd body must
|
|
1234
|
+
# not put an object in the text.
|
|
1235
|
+
docs_url = body.get("docs_url")
|
|
1214
1236
|
return RecapiError(
|
|
1215
1237
|
str(code),
|
|
1216
1238
|
str(body.get("message") or f"HTTP {status}"),
|
|
1217
1239
|
status=status,
|
|
1218
1240
|
retry_after=_retry_after(headers.get("Retry-After")),
|
|
1241
|
+
docs_url=docs_url if isinstance(docs_url, str) else None,
|
|
1219
1242
|
)
|
|
1220
1243
|
|
|
1221
1244
|
|
|
@@ -1313,6 +1336,25 @@ def _check_ids(**ids: str | None) -> None:
|
|
|
1313
1336
|
raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
|
|
1314
1337
|
|
|
1315
1338
|
|
|
1339
|
+
def _check_amount(value: object, currency: object) -> None:
|
|
1340
|
+
"""Refuse what the API would refuse in the event (spec/client_vectors.json "amounts")."""
|
|
1341
|
+
if value is not None and (
|
|
1342
|
+
isinstance(value, bool) or not isinstance(value, int | float) or not (0 <= value < math.inf)
|
|
1343
|
+
):
|
|
1344
|
+
raise ValueError("value must be a number of at least 0")
|
|
1345
|
+
if currency is None:
|
|
1346
|
+
return
|
|
1347
|
+
if value is None:
|
|
1348
|
+
raise ValueError("currency needs a value")
|
|
1349
|
+
if not (
|
|
1350
|
+
isinstance(currency, str)
|
|
1351
|
+
and len(currency) == 3
|
|
1352
|
+
and currency.isascii()
|
|
1353
|
+
and currency.isalpha()
|
|
1354
|
+
):
|
|
1355
|
+
raise ValueError("currency must be three letters (ISO 4217)")
|
|
1356
|
+
|
|
1357
|
+
|
|
1316
1358
|
def _usable_context(value: object) -> bool:
|
|
1317
1359
|
# An id, or nothing: an empty string reads as no context item.
|
|
1318
1360
|
return value is None or is_id(value) or (isinstance(value, str) and not value)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.13
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://recapi.io
|
|
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
49
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
50
50
|
|
|
51
51
|
```sh
|
|
52
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
237
237
|
|
|
238
238
|
| Method | What it does |
|
|
239
239
|
|---|---|
|
|
240
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
240
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
241
241
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
243
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -272,7 +272,8 @@ batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
|
272
272
|
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
273
|
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
274
|
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
-
the items the API refused.
|
|
275
|
+
the items the API refused. An API error also carries `docs_url`, the address
|
|
276
|
+
of its section on the errors page; its message ends with it.
|
|
276
277
|
|
|
277
278
|
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
278
279
|
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
@@ -115,6 +115,19 @@ class AsyncClient(APITest):
|
|
|
115
115
|
self.assertIn("invalid_request", logs.output[0])
|
|
116
116
|
self.assertNotIn("evil", logs.output[0])
|
|
117
117
|
|
|
118
|
+
def test_async_track_sends_an_amount(self) -> None:
|
|
119
|
+
client = self.async_client()
|
|
120
|
+
|
|
121
|
+
async def run() -> None:
|
|
122
|
+
await client.track("p1", "purchase", user_id="u", value=49.9, currency="EUR")
|
|
123
|
+
with self.assertRaises(ValueError):
|
|
124
|
+
await client.track("p1", "purchase", user_id="u", currency="EUR")
|
|
125
|
+
await client.flush()
|
|
126
|
+
|
|
127
|
+
asyncio.run(run())
|
|
128
|
+
sent = [e for batch in self.api.events() for e in batch]
|
|
129
|
+
self.assertEqual([(e["value"], e["currency"]) for e in sent], [(49.9, "EUR")])
|
|
130
|
+
|
|
118
131
|
def test_async_track_drops_an_unusable_item_id(self) -> None:
|
|
119
132
|
client = self.async_client()
|
|
120
133
|
|
|
@@ -392,6 +392,22 @@ class Recommend(APITest):
|
|
|
392
392
|
self.assertIn("recs down", logs.output[0])
|
|
393
393
|
self.assertIn("pop down", logs.output[0])
|
|
394
394
|
|
|
395
|
+
def test_the_log_line_for_a_refused_key_ends_with_the_address_of_its_fix(self) -> None:
|
|
396
|
+
docs_url = "https://app.recapi.io/docs/errors#401-unauthorized"
|
|
397
|
+
error = {"code": "unauthorized", "message": "missing or invalid API key"}
|
|
398
|
+
self.api.handler = lambda call: Reply(401, {"error": {**error, "docs_url": docs_url}})
|
|
399
|
+
client = self.client()
|
|
400
|
+
client.track("a", 1, user_id="u")
|
|
401
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
402
|
+
client.flush()
|
|
403
|
+
client.recommend(user_id="u", count=3)
|
|
404
|
+
self.assertTrue(logs.output)
|
|
405
|
+
for line in logs.output:
|
|
406
|
+
self.assertTrue(line.endswith(f"missing or invalid API key, see {docs_url}"), line)
|
|
407
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
408
|
+
client._popular(1, None, None, None)
|
|
409
|
+
self.assertEqual(caught.exception.docs_url, docs_url)
|
|
410
|
+
|
|
395
411
|
def test_an_unusable_context_item_id_is_reported_without_the_id(self) -> None:
|
|
396
412
|
# A page takes the id from a visitor's URL: the visitor must not reach
|
|
397
413
|
# the log, the rejected item still leaves the list, and the history
|
|
@@ -25,6 +25,8 @@ def error_reply(case: dict) -> Reply:
|
|
|
25
25
|
body = None
|
|
26
26
|
if case.get("body_code"):
|
|
27
27
|
body = {"error": {"code": case["body_code"], "message": "from the vector"}}
|
|
28
|
+
if "docs_url" in case:
|
|
29
|
+
body["error"]["docs_url"] = case["docs_url"]
|
|
28
30
|
headers = {"Retry-After": case["retry_after"]} if "retry_after" in case else {}
|
|
29
31
|
if "retry_after_ms" in case and case["retry_after_ms"] is not None and not headers:
|
|
30
32
|
headers = {"Retry-After": str(case["retry_after_ms"] / 1000)}
|
|
@@ -84,6 +86,12 @@ class ClientVectors(APITest):
|
|
|
84
86
|
if "retry_after_ms" in case:
|
|
85
87
|
want = case["retry_after_ms"]
|
|
86
88
|
self.assertEqual(error.retry_after, None if want is None else want / 1000)
|
|
89
|
+
self.assertEqual(error.docs_url, case.get("docs_url"))
|
|
90
|
+
# An older server sends no docs_url: no address, and the message as sent.
|
|
91
|
+
if "docs_url" in case:
|
|
92
|
+
self.assertTrue(str(error).endswith(", see " + case["docs_url"]), str(error))
|
|
93
|
+
elif case.get("body_code"):
|
|
94
|
+
self.assertEqual(str(error), "from the vector")
|
|
87
95
|
|
|
88
96
|
def test_vector_list_calls_keep_the_page_up(self) -> None:
|
|
89
97
|
for case in VECTORS["errors"]:
|
|
@@ -472,3 +480,37 @@ class ClientVectors(APITest):
|
|
|
472
480
|
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
473
481
|
self.assertEqual(got, case["upserted"])
|
|
474
482
|
self.assertEqual(rejected, case["rejected"] or None)
|
|
483
|
+
|
|
484
|
+
def test_vector_amounts(self) -> None:
|
|
485
|
+
vectors = VECTORS["amounts"]
|
|
486
|
+
event = vectors["event"]
|
|
487
|
+
client = self.client()
|
|
488
|
+
bad = [*vectors["invalid"], {"value": float("nan")}, {"value": float("inf")}]
|
|
489
|
+
bad += [
|
|
490
|
+
{"value": float("-inf"), "currency": "EUR"},
|
|
491
|
+
{"value": True},
|
|
492
|
+
{"value": 1, "currency": ""},
|
|
493
|
+
{"value": 1, "currency": "ÉUR"}, # a letter, but not ASCII
|
|
494
|
+
{"value": 1, "currency": 978}, # the numeric code
|
|
495
|
+
]
|
|
496
|
+
for case in bad:
|
|
497
|
+
with self.subTest(case=case), self.assertRaises(ValueError):
|
|
498
|
+
client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
|
|
499
|
+
for case in vectors["valid"]:
|
|
500
|
+
client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
|
|
501
|
+
client.flush()
|
|
502
|
+
sent = [e for batch in self.api.events() for e in batch] # nothing of the invalid ones
|
|
503
|
+
self.assertEqual(len(sent), len(vectors["valid"]))
|
|
504
|
+
for want, got in zip(vectors["valid"], sent, strict=True):
|
|
505
|
+
for key in ("value", "currency"): # as given, absent when unset
|
|
506
|
+
self.assertEqual(got.get(key, "absent"), want.get(key, "absent"), want)
|
|
507
|
+
self.assertIs(type(got.get("value")), type(want.get("value")))
|
|
508
|
+
|
|
509
|
+
def test_every_vector_section_runs(self) -> None:
|
|
510
|
+
run = {"description", "max_events_per_request", "max_exclude", "recommend_timeout_ms",
|
|
511
|
+
"levels", "ids", "errors", "retry", "batches", "exclude", "context_ids", "fallback",
|
|
512
|
+
"restore", "identify", "stored_state", "metadata", "why", "lists", "upsert_items",
|
|
513
|
+
"amounts"} # fmt: skip
|
|
514
|
+
self.assertEqual(
|
|
515
|
+
set(VECTORS) - run, set(), "sections of spec/client_vectors.json not tested"
|
|
516
|
+
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|