tinyfish 0.4.0__tar.gz → 0.6.0__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.
- {tinyfish-0.4.0 → tinyfish-0.6.0}/CHANGELOG.md +14 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/PKG-INFO +7 -2
- {tinyfish-0.4.0 → tinyfish-0.6.0}/README.md +6 -1
- {tinyfish-0.4.0 → tinyfish-0.6.0}/pyproject.toml +1 -1
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/__init__.py +17 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/client/_base.py +38 -5
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/client/async_.py +3 -3
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/client/sync.py +3 -3
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/client.py +9 -4
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/fetch/__init__.py +2 -2
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/search/__init__.py +2 -2
- tinyfish-0.6.0/src/tinyfish/wallet/__init__.py +41 -0
- tinyfish-0.6.0/src/tinyfish/wallet/types.py +87 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_client.py +85 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_fetch.py +12 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_search.py +14 -0
- tinyfish-0.6.0/tests/test_wallet.py +239 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/uv.lock +1 -1
- {tinyfish-0.4.0 → tinyfish-0.6.0}/.gitignore +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/.pre-commit-config.yaml +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/AGENTS.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/CLAUDE.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/RELEASE.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/exceptions-and-errors-guide.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/internal/api-integration-header.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/internal/exceptions-and-errors-guide.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/internal/publishing-private-guide.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/pagination-guide.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/proxy-and-browser-profiles.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/docs/streaming-guide.md +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/client/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/exceptions.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/resource.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/_utils/sse_parser.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/agent/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/agent/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/browser/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/browser/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/fetch/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/py.typed +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/runs/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/runs/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/search/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/vault/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/src/tinyfish/vault/types.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/__init__.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/conftest.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_agent.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_browser.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_errors.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_runs.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/test_vault.py +0 -0
- {tinyfish-0.4.0 → tinyfish-0.6.0}/tests/testing_guide.md +0 -0
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.6.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.5.0...sdk-py/v0.6.0) (2026-08-11)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **sdk:** wallet resource — client.wallet.get() in TypeScript and Python SDKs (PF-3454) ([#4213](https://github.com/tinyfish-io/ux-labs/issues/4213)) ([1127f1d](https://github.com/tinyfish-io/ux-labs/commit/1127f1de8acf2eef27c22eec5cd08b9cabdfaf86))
|
|
9
|
+
|
|
10
|
+
## [0.5.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.4.0...sdk-py/v0.5.0) (2026-08-04)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Features
|
|
14
|
+
|
|
15
|
+
* **sdk:** send Search and Fetch to their own hosts ([#4008](https://github.com/tinyfish-io/ux-labs/issues/4008)) ([813b4df](https://github.com/tinyfish-io/ux-labs/commit/813b4dfec7a72f1f0771237798c63a1708cb5cee))
|
|
16
|
+
|
|
3
17
|
## [0.4.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.3.0...sdk-py/v0.4.0) (2026-07-23)
|
|
4
18
|
|
|
5
19
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tinyfish
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: Official Python SDK for the TinyFish API
|
|
5
5
|
Requires-Python: >=3.11
|
|
6
6
|
Requires-Dist: httpx>=0.27.0
|
|
@@ -57,6 +57,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
|
|
|
57
57
|
| [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
|
|
58
58
|
| [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
|
|
59
59
|
| [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
|
|
60
|
+
| `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
|
|
60
61
|
|
|
61
62
|
---
|
|
62
63
|
|
|
@@ -384,7 +385,11 @@ All seven methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_
|
|
|
384
385
|
```python
|
|
385
386
|
client = TinyFish(
|
|
386
387
|
api_key="your-api-key", # optional — or set TINYFISH_API_KEY env var
|
|
387
|
-
base_url=
|
|
388
|
+
base_url=None, # optional — omit it: Search and Fetch then use
|
|
389
|
+
# https://api.search.tinyfish.ai and
|
|
390
|
+
# https://api.fetch.tinyfish.ai; any explicit value
|
|
391
|
+
# keeps every product on it. Do not pass a product host
|
|
392
|
+
# here — it serves at the root, so /v1/search would 404
|
|
388
393
|
timeout=600.0, # optional — seconds (default: 600)
|
|
389
394
|
max_retries=2, # optional — retry attempts (default: 2)
|
|
390
395
|
)
|
|
@@ -47,6 +47,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
|
|
|
47
47
|
| [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
|
|
48
48
|
| [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
|
|
49
49
|
| [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
|
|
50
|
+
| `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
|
|
50
51
|
|
|
51
52
|
---
|
|
52
53
|
|
|
@@ -374,7 +375,11 @@ All seven methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_
|
|
|
374
375
|
```python
|
|
375
376
|
client = TinyFish(
|
|
376
377
|
api_key="your-api-key", # optional — or set TINYFISH_API_KEY env var
|
|
377
|
-
base_url=
|
|
378
|
+
base_url=None, # optional — omit it: Search and Fetch then use
|
|
379
|
+
# https://api.search.tinyfish.ai and
|
|
380
|
+
# https://api.fetch.tinyfish.ai; any explicit value
|
|
381
|
+
# keeps every product on it. Do not pass a product host
|
|
382
|
+
# here — it serves at the root, so /v1/search would 404
|
|
378
383
|
timeout=600.0, # optional — seconds (default: 600)
|
|
379
384
|
max_retries=2, # optional — retry attempts (default: 2)
|
|
380
385
|
)
|
|
@@ -80,6 +80,16 @@ from .vault.types import (
|
|
|
80
80
|
VaultSyncItemsResponse,
|
|
81
81
|
)
|
|
82
82
|
|
|
83
|
+
# Wallet types
|
|
84
|
+
from .wallet.types import (
|
|
85
|
+
WalletAutoReload,
|
|
86
|
+
WalletAutoReloadState,
|
|
87
|
+
WalletMeter,
|
|
88
|
+
WalletPendingTopUp,
|
|
89
|
+
WalletRates,
|
|
90
|
+
WalletResponse,
|
|
91
|
+
)
|
|
92
|
+
|
|
83
93
|
__version__ = version("tinyfish")
|
|
84
94
|
|
|
85
95
|
__all__ = [
|
|
@@ -149,4 +159,11 @@ __all__ = [
|
|
|
149
159
|
"VaultDisconnectResponse",
|
|
150
160
|
"VaultListItemsResponse",
|
|
151
161
|
"VaultSyncItemsResponse",
|
|
162
|
+
# Wallet types
|
|
163
|
+
"WalletAutoReloadState",
|
|
164
|
+
"WalletAutoReload",
|
|
165
|
+
"WalletMeter",
|
|
166
|
+
"WalletRates",
|
|
167
|
+
"WalletPendingTopUp",
|
|
168
|
+
"WalletResponse",
|
|
152
169
|
]
|
|
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import os
|
|
6
6
|
from importlib.metadata import version as _pkg_version
|
|
7
|
-
from typing import Any, TypeVar
|
|
7
|
+
from typing import Any, Literal, TypeVar
|
|
8
8
|
|
|
9
9
|
import httpx
|
|
10
10
|
from pydantic import BaseModel
|
|
@@ -32,6 +32,21 @@ _RETRY_MULTIPLIER: float = 0.5
|
|
|
32
32
|
_RETRY_MAX_WAIT: float = 8.0
|
|
33
33
|
|
|
34
34
|
|
|
35
|
+
def _sanitize_client_header(value: str) -> str:
|
|
36
|
+
"""Non-printable chars raise in httpx; 128 is the server cap (client_name varchar(128))."""
|
|
37
|
+
return "".join(ch for ch in value if 32 <= ord(ch) <= 126).strip()[:128]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
DEFAULT_BASE_URL = "https://agent.tinyfish.ai"
|
|
41
|
+
|
|
42
|
+
# Search and Fetch have their own hostnames, which serve the API at the root path. They are
|
|
43
|
+
# the entry points that run through the API gateway; DEFAULT_BASE_URL is not.
|
|
44
|
+
PRODUCT_BASE_URLS = {
|
|
45
|
+
"search": "https://api.search.tinyfish.ai",
|
|
46
|
+
"fetch": "https://api.fetch.tinyfish.ai",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
35
50
|
class _BaseClient:
|
|
36
51
|
"""Shared logic for sync and async clients. Not for direct use."""
|
|
37
52
|
|
|
@@ -39,16 +54,19 @@ class _BaseClient:
|
|
|
39
54
|
self,
|
|
40
55
|
*,
|
|
41
56
|
api_key: str | None,
|
|
42
|
-
base_url: str,
|
|
57
|
+
base_url: str | None,
|
|
43
58
|
max_retries: int = _DEFAULT_MAX_RETRIES,
|
|
44
59
|
) -> None:
|
|
45
60
|
"""
|
|
46
61
|
Args:
|
|
47
62
|
api_key: API key for authentication. If None, falls back to the
|
|
48
63
|
TINYFISH_API_KEY environment variable.
|
|
49
|
-
base_url: Base URL for all API requests
|
|
64
|
+
base_url: Base URL for all API requests. When set, every product is
|
|
65
|
+
reached on it; when None, Search and Fetch use their own hosts.
|
|
50
66
|
max_retries: Default max retry attempts (default: 2)
|
|
51
67
|
"""
|
|
68
|
+
base_url = (base_url or "").strip() or None
|
|
69
|
+
|
|
52
70
|
# If no key was passed explicitly, try the environment variable.
|
|
53
71
|
# This lets users do `export TINYFISH_API_KEY=xxx` and omit api_key
|
|
54
72
|
# entirely when constructing the client.
|
|
@@ -62,9 +80,17 @@ class _BaseClient:
|
|
|
62
80
|
# and do not appear in autocomplete or when someone inspects the object
|
|
63
81
|
# casually (e.g. vars(client) in a debug session).
|
|
64
82
|
self._api_key = resolved_key
|
|
65
|
-
self._base_url = base_url
|
|
83
|
+
self._base_url = base_url or DEFAULT_BASE_URL
|
|
84
|
+
self._use_product_hosts = base_url is None
|
|
66
85
|
self._max_retries = max_retries
|
|
67
86
|
|
|
87
|
+
def product_url(self, product: Literal["search", "fetch"]) -> str:
|
|
88
|
+
"""Where to send a Search or Fetch request: the product host, or a path on an
|
|
89
|
+
explicitly configured base URL."""
|
|
90
|
+
if self._use_product_hosts:
|
|
91
|
+
return f"{PRODUCT_BASE_URLS[product]}/"
|
|
92
|
+
return f"/v1/{product}"
|
|
93
|
+
|
|
68
94
|
def __repr__(self) -> str:
|
|
69
95
|
# Mask the key so that logging `repr(client)` never writes a live secret
|
|
70
96
|
# to stdout, log files, or error tracking services. We keep the first 8
|
|
@@ -74,13 +100,20 @@ class _BaseClient:
|
|
|
74
100
|
return f"{self.__class__.__name__}(base_url={self._base_url!r}, api_key={masked!r})"
|
|
75
101
|
|
|
76
102
|
def _build_default_headers(self) -> dict[str, str]:
|
|
77
|
-
|
|
103
|
+
headers = {
|
|
78
104
|
"Content-Type": "application/json",
|
|
79
105
|
"Accept": "application/json",
|
|
80
106
|
"X-API-Key": self._api_key,
|
|
81
107
|
"User-Agent": f"tinyfish-python/{_pkg_version('tinyfish')}",
|
|
82
108
|
"X-TF-Request-Origin": "tinyfish-python",
|
|
83
109
|
}
|
|
110
|
+
client_name = _sanitize_client_header(os.environ.get("TF_CLIENT_NAME", ""))
|
|
111
|
+
client_version = _sanitize_client_header(os.environ.get("TF_CLIENT_VERSION", ""))
|
|
112
|
+
if client_name:
|
|
113
|
+
headers["X-TF-Client-Name"] = client_name
|
|
114
|
+
if client_version:
|
|
115
|
+
headers["X-TF-Client-Version"] = client_version
|
|
116
|
+
return headers
|
|
84
117
|
|
|
85
118
|
@staticmethod
|
|
86
119
|
def _inject_integration(json: dict[str, Any] | None) -> dict[str, Any] | None:
|
|
@@ -28,21 +28,21 @@ class BaseAsyncAPIClient(_BaseClient):
|
|
|
28
28
|
self,
|
|
29
29
|
*,
|
|
30
30
|
api_key: str,
|
|
31
|
-
base_url: str,
|
|
31
|
+
base_url: str | None,
|
|
32
32
|
timeout: float = _DEFAULT_TIMEOUT,
|
|
33
33
|
max_retries: int = _DEFAULT_MAX_RETRIES,
|
|
34
34
|
) -> None:
|
|
35
35
|
"""
|
|
36
36
|
Args:
|
|
37
37
|
api_key: API key for authentication
|
|
38
|
-
base_url: Base URL for all API requests
|
|
38
|
+
base_url: Base URL for all API requests. None uses per-product hosts.
|
|
39
39
|
timeout: Default timeout in seconds (default: 600.0)
|
|
40
40
|
max_retries: Default max retry attempts (default: 2)
|
|
41
41
|
"""
|
|
42
42
|
super().__init__(api_key=api_key, base_url=base_url, max_retries=max_retries)
|
|
43
43
|
|
|
44
44
|
self._client = httpx.AsyncClient(
|
|
45
|
-
base_url=
|
|
45
|
+
base_url=self._base_url,
|
|
46
46
|
timeout=timeout,
|
|
47
47
|
headers=self._build_default_headers(),
|
|
48
48
|
)
|
|
@@ -28,21 +28,21 @@ class BaseSyncAPIClient(_BaseClient):
|
|
|
28
28
|
self,
|
|
29
29
|
*,
|
|
30
30
|
api_key: str,
|
|
31
|
-
base_url: str,
|
|
31
|
+
base_url: str | None,
|
|
32
32
|
timeout: float = _DEFAULT_TIMEOUT,
|
|
33
33
|
max_retries: int = _DEFAULT_MAX_RETRIES,
|
|
34
34
|
) -> None:
|
|
35
35
|
"""
|
|
36
36
|
Args:
|
|
37
37
|
api_key: API key for authentication
|
|
38
|
-
base_url: Base URL for all API requests
|
|
38
|
+
base_url: Base URL for all API requests. None uses per-product hosts.
|
|
39
39
|
timeout: Default timeout in seconds (default: 600.0)
|
|
40
40
|
max_retries: Default max retry attempts (default: 2)
|
|
41
41
|
"""
|
|
42
42
|
super().__init__(api_key=api_key, base_url=base_url, max_retries=max_retries)
|
|
43
43
|
|
|
44
44
|
self._client = httpx.Client(
|
|
45
|
-
base_url=
|
|
45
|
+
base_url=self._base_url,
|
|
46
46
|
timeout=timeout,
|
|
47
47
|
headers=self._build_default_headers(),
|
|
48
48
|
)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""TinyFish SDK client."""
|
|
2
2
|
|
|
3
3
|
from tinyfish._utils.client import BaseAsyncAPIClient, BaseSyncAPIClient
|
|
4
|
-
from tinyfish._utils.client._base import _DEFAULT_TIMEOUT
|
|
4
|
+
from tinyfish._utils.client._base import _DEFAULT_TIMEOUT, DEFAULT_BASE_URL
|
|
5
5
|
|
|
6
6
|
from .agent import AgentResource, AsyncAgentResource
|
|
7
7
|
from .browser import AsyncBrowserResource, BrowserResource
|
|
@@ -9,10 +9,11 @@ from .fetch import AsyncFetchResource, FetchResource
|
|
|
9
9
|
from .runs import AsyncRunsResource, RunsResource
|
|
10
10
|
from .search import AsyncSearchResource, SearchResource
|
|
11
11
|
from .vault import AsyncVaultResource, VaultResource
|
|
12
|
+
from .wallet import AsyncWalletResource, WalletResource
|
|
12
13
|
|
|
13
14
|
__all__ = ["TinyFish", "AsyncTinyFish"]
|
|
14
15
|
|
|
15
|
-
API_BASE_URL =
|
|
16
|
+
API_BASE_URL = DEFAULT_BASE_URL
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
class TinyFish(BaseSyncAPIClient):
|
|
@@ -30,6 +31,7 @@ class TinyFish(BaseSyncAPIClient):
|
|
|
30
31
|
runs: RunsResource
|
|
31
32
|
search: SearchResource
|
|
32
33
|
vault: VaultResource
|
|
34
|
+
wallet: WalletResource
|
|
33
35
|
|
|
34
36
|
def __init__(
|
|
35
37
|
self,
|
|
@@ -38,7 +40,7 @@ class TinyFish(BaseSyncAPIClient):
|
|
|
38
40
|
# the TINYFISH_API_KEY environment variable and raise a clear ValueError
|
|
39
41
|
# if neither is set.
|
|
40
42
|
api_key: str | None = None,
|
|
41
|
-
base_url: str =
|
|
43
|
+
base_url: str | None = None,
|
|
42
44
|
timeout: float = _DEFAULT_TIMEOUT,
|
|
43
45
|
max_retries: int = 2,
|
|
44
46
|
):
|
|
@@ -55,6 +57,7 @@ class TinyFish(BaseSyncAPIClient):
|
|
|
55
57
|
self.runs = RunsResource(self)
|
|
56
58
|
self.search = SearchResource(self)
|
|
57
59
|
self.vault = VaultResource(self)
|
|
60
|
+
self.wallet = WalletResource(self)
|
|
58
61
|
|
|
59
62
|
|
|
60
63
|
class AsyncTinyFish(BaseAsyncAPIClient):
|
|
@@ -69,6 +72,7 @@ class AsyncTinyFish(BaseAsyncAPIClient):
|
|
|
69
72
|
runs: AsyncRunsResource
|
|
70
73
|
search: AsyncSearchResource
|
|
71
74
|
vault: AsyncVaultResource
|
|
75
|
+
wallet: AsyncWalletResource
|
|
72
76
|
|
|
73
77
|
def __init__(
|
|
74
78
|
self,
|
|
@@ -77,7 +81,7 @@ class AsyncTinyFish(BaseAsyncAPIClient):
|
|
|
77
81
|
# the TINYFISH_API_KEY environment variable and raise a clear ValueError
|
|
78
82
|
# if neither is set.
|
|
79
83
|
api_key: str | None = None,
|
|
80
|
-
base_url: str =
|
|
84
|
+
base_url: str | None = None,
|
|
81
85
|
timeout: float = _DEFAULT_TIMEOUT,
|
|
82
86
|
max_retries: int = 2,
|
|
83
87
|
):
|
|
@@ -94,3 +98,4 @@ class AsyncTinyFish(BaseAsyncAPIClient):
|
|
|
94
98
|
self.runs = AsyncRunsResource(self)
|
|
95
99
|
self.search = AsyncSearchResource(self)
|
|
96
100
|
self.vault = AsyncVaultResource(self)
|
|
101
|
+
self.wallet = AsyncWalletResource(self)
|
|
@@ -97,7 +97,7 @@ class FetchResource(BaseSyncAPIResource):
|
|
|
97
97
|
if_modified_since=if_modified_since,
|
|
98
98
|
include_etag_and_last_modified=include_etag_and_last_modified,
|
|
99
99
|
)
|
|
100
|
-
return self._post("
|
|
100
|
+
return self._post(self._client.product_url("fetch"), json=body, cast_to=FetchResponse)
|
|
101
101
|
|
|
102
102
|
|
|
103
103
|
class AsyncFetchResource(BaseAsyncAPIResource):
|
|
@@ -177,7 +177,7 @@ class AsyncFetchResource(BaseAsyncAPIResource):
|
|
|
177
177
|
if_modified_since=if_modified_since,
|
|
178
178
|
include_etag_and_last_modified=include_etag_and_last_modified,
|
|
179
179
|
)
|
|
180
|
-
return await self._post("
|
|
180
|
+
return await self._post(self._client.product_url("fetch"), json=body, cast_to=FetchResponse)
|
|
181
181
|
|
|
182
182
|
|
|
183
183
|
def _validate_purpose(purpose: str | None) -> None:
|
|
@@ -183,7 +183,7 @@ class SearchResource(BaseSyncAPIResource):
|
|
|
183
183
|
pub_year_max=pub_year_max,
|
|
184
184
|
page=page,
|
|
185
185
|
)
|
|
186
|
-
return self._get("
|
|
186
|
+
return self._get(self._client.product_url("search"), params=params, cast_to=SearchQueryResponse)
|
|
187
187
|
|
|
188
188
|
|
|
189
189
|
class AsyncSearchResource(BaseAsyncAPIResource):
|
|
@@ -257,4 +257,4 @@ class AsyncSearchResource(BaseAsyncAPIResource):
|
|
|
257
257
|
pub_year_max=pub_year_max,
|
|
258
258
|
page=page,
|
|
259
259
|
)
|
|
260
|
-
return await self._get("
|
|
260
|
+
return await self._get(self._client.product_url("search"), params=params, cast_to=SearchQueryResponse)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Wallet resource for retrieving wallet balance, auto-reload, and rates."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tinyfish._utils.resource import BaseAsyncAPIResource, BaseSyncAPIResource
|
|
6
|
+
|
|
7
|
+
from .types import WalletResponse
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class WalletResource(BaseSyncAPIResource):
|
|
11
|
+
"""Retrieve the caller's wallet (sync)."""
|
|
12
|
+
|
|
13
|
+
def get(self) -> WalletResponse:
|
|
14
|
+
"""Get the caller's wallet: balance, auto-reload state, per-contract rates,
|
|
15
|
+
and any in-flight top-up.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
WalletResponse with the full wallet shape.
|
|
19
|
+
|
|
20
|
+
Raises:
|
|
21
|
+
AuthenticationError: Invalid API key.
|
|
22
|
+
"""
|
|
23
|
+
return self._get("/v1/wallet", cast_to=WalletResponse)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AsyncWalletResource(BaseAsyncAPIResource):
|
|
27
|
+
"""Retrieve the caller's wallet (async)."""
|
|
28
|
+
|
|
29
|
+
async def get(self) -> WalletResponse:
|
|
30
|
+
"""Get the caller's wallet: balance, auto-reload state, per-contract rates,
|
|
31
|
+
and any in-flight top-up.
|
|
32
|
+
|
|
33
|
+
Async version of `WalletResource.get()`.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
WalletResponse with the full wallet shape.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
AuthenticationError: Invalid API key.
|
|
40
|
+
"""
|
|
41
|
+
return await self._get("/v1/wallet", cast_to=WalletResponse)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Wallet request/response types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from typing import Annotated, Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class WalletAutoReloadState(StrEnum):
|
|
12
|
+
"""Auto-reload configuration state."""
|
|
13
|
+
|
|
14
|
+
UNCONFIGURED = "unconfigured"
|
|
15
|
+
ON = "on"
|
|
16
|
+
OFF = "off"
|
|
17
|
+
PAUSED_PAYMENT_FAILED = "paused_payment_failed"
|
|
18
|
+
NEEDS_PAYMENT_METHOD = "needs_payment_method"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WalletAutoReloadUnconfigured(BaseModel):
|
|
22
|
+
"""Auto-reload has never been configured for this wallet."""
|
|
23
|
+
|
|
24
|
+
state: Literal[WalletAutoReloadState.UNCONFIGURED] = Field(..., description="Current auto-reload state")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class WalletAutoReloadConfigured(BaseModel):
|
|
28
|
+
"""Auto-reload is configured — threshold and recharge_to are always present."""
|
|
29
|
+
|
|
30
|
+
state: Literal[
|
|
31
|
+
WalletAutoReloadState.ON,
|
|
32
|
+
WalletAutoReloadState.OFF,
|
|
33
|
+
WalletAutoReloadState.PAUSED_PAYMENT_FAILED,
|
|
34
|
+
WalletAutoReloadState.NEEDS_PAYMENT_METHOD,
|
|
35
|
+
] = Field(..., description="Current auto-reload state")
|
|
36
|
+
threshold: str = Field(..., description="Balance floor that triggers a reload.")
|
|
37
|
+
recharge_to: str = Field(..., description="Balance the wallet is topped up to when a reload triggers.")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
WalletAutoReload = Annotated[
|
|
41
|
+
WalletAutoReloadUnconfigured | WalletAutoReloadConfigured,
|
|
42
|
+
Field(discriminator="state"),
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class WalletMeter(BaseModel):
|
|
47
|
+
"""One priced product on the caller's Metronome contract."""
|
|
48
|
+
|
|
49
|
+
product_id: str = Field(..., description="Metronome product ID")
|
|
50
|
+
label: str = Field(..., description="Human-readable meter label")
|
|
51
|
+
unit_amount: str = Field(..., description="Per-unit rate, decimal string")
|
|
52
|
+
currency: str = Field(..., description="Currency code")
|
|
53
|
+
per: str | None = Field(None, description="Billable unit this meter charges per. Absent when unlabeled.")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class WalletRates(BaseModel):
|
|
57
|
+
"""Every priced product on the caller's Metronome contract, read live."""
|
|
58
|
+
|
|
59
|
+
meters: list[WalletMeter] = Field(..., description="Priced products on the contract")
|
|
60
|
+
as_of: str = Field(..., description="ISO timestamp the rates were read")
|
|
61
|
+
source: Literal["metronome-contract"] = Field(..., description="Rate provenance")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class WalletPendingTopUp(BaseModel):
|
|
65
|
+
"""An in-flight top-up. Completed, failed, and no-attempt states read null."""
|
|
66
|
+
|
|
67
|
+
amount: str = Field(..., description="Top-up amount, decimal string")
|
|
68
|
+
started_at: str = Field(..., description="ISO timestamp the top-up started")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class WalletResponse(BaseModel):
|
|
72
|
+
"""Wallet balance, auto-reload, per-product rates, and any in-flight top-up."""
|
|
73
|
+
|
|
74
|
+
available_balance: str = Field(
|
|
75
|
+
..., description="Current spendable balance. A negative value means the wallet is overdrawn."
|
|
76
|
+
)
|
|
77
|
+
currency: str = Field(..., description="Currency code")
|
|
78
|
+
as_of: str = Field(..., description="ISO timestamp the balance was read")
|
|
79
|
+
auto_reload: WalletAutoReload | None = Field(
|
|
80
|
+
None, description="None means the auto-reload read failed, not that it is unconfigured"
|
|
81
|
+
)
|
|
82
|
+
pending_top_up: WalletPendingTopUp | None = Field(
|
|
83
|
+
None, description="None means no in-flight top-up, or the ledger read failed"
|
|
84
|
+
)
|
|
85
|
+
rates: WalletRates | None = Field(
|
|
86
|
+
None, description="None means the rates read failed, or the wallet has no Metronome contract yet"
|
|
87
|
+
)
|
|
@@ -227,3 +227,88 @@ async def test_async_integration_in_body_via_env(respx_mock: MockRouter):
|
|
|
227
227
|
|
|
228
228
|
body = json.loads(route.calls[0].request.content)
|
|
229
229
|
assert body["api_integration"] == "dify"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ─── TF_CLIENT_NAME / TF_CLIENT_VERSION env vars ──────────────────────────
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# TF_CLIENT_NAME / TF_CLIENT_VERSION env vars are sent as client headers
|
|
236
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
237
|
+
def test_client_headers_via_env(respx_mock: MockRouter):
|
|
238
|
+
with mock.patch.dict(os.environ, {"TF_CLIENT_NAME": "claude-code", "TF_CLIENT_VERSION": "1.2.3"}):
|
|
239
|
+
c = TinyFish(api_key=API_KEY, base_url=BASE_URL, max_retries=0)
|
|
240
|
+
route = respx_mock.post(_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
|
|
241
|
+
c.agent.run(**_BODY)
|
|
242
|
+
headers = route.calls[0].request.headers
|
|
243
|
+
assert headers["x-tf-client-name"] == "claude-code"
|
|
244
|
+
assert headers["x-tf-client-version"] == "1.2.3"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# Without TF_CLIENT_NAME / TF_CLIENT_VERSION, client headers are absent
|
|
248
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
249
|
+
def test_no_client_headers_by_default(respx_mock: MockRouter):
|
|
250
|
+
with mock.patch.dict(os.environ, {}, clear=False):
|
|
251
|
+
os.environ.pop("TF_CLIENT_NAME", None)
|
|
252
|
+
os.environ.pop("TF_CLIENT_VERSION", None)
|
|
253
|
+
c = TinyFish(api_key=API_KEY, base_url=BASE_URL, max_retries=0)
|
|
254
|
+
route = respx_mock.post(_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
|
|
255
|
+
c.agent.run(**_BODY)
|
|
256
|
+
headers = route.calls[0].request.headers
|
|
257
|
+
assert "x-tf-client-name" not in headers
|
|
258
|
+
assert "x-tf-client-version" not in headers
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# Async client sends client headers when env vars are set
|
|
262
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
263
|
+
async def test_async_client_headers_via_env(respx_mock: MockRouter):
|
|
264
|
+
with mock.patch.dict(os.environ, {"TF_CLIENT_NAME": "claude-desktop", "TF_CLIENT_VERSION": "0.9"}):
|
|
265
|
+
route = respx_mock.post(_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
|
|
266
|
+
async with AsyncTinyFish(api_key=API_KEY, base_url=BASE_URL, max_retries=0) as c:
|
|
267
|
+
await c.agent.run(**_BODY)
|
|
268
|
+
headers = route.calls[0].request.headers
|
|
269
|
+
assert headers["x-tf-client-name"] == "claude-desktop"
|
|
270
|
+
assert headers["x-tf-client-version"] == "0.9"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# Whitespace-only env vars are treated as unset; unsafe chars are stripped
|
|
274
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
275
|
+
def test_client_headers_sanitized(respx_mock: MockRouter):
|
|
276
|
+
with mock.patch.dict(os.environ, {"TF_CLIENT_NAME": " ", "TF_CLIENT_VERSION": "1.2.3\n"}):
|
|
277
|
+
c = TinyFish(api_key=API_KEY, base_url=BASE_URL, max_retries=0)
|
|
278
|
+
route = respx_mock.post(_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
|
|
279
|
+
c.agent.run(**_BODY)
|
|
280
|
+
headers = route.calls[0].request.headers
|
|
281
|
+
assert "x-tf-client-name" not in headers
|
|
282
|
+
assert headers["x-tf-client-version"] == "1.2.3"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# Values over the 128-char server cap are truncated client-side
|
|
286
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
287
|
+
def test_client_headers_truncated_to_128(respx_mock: MockRouter):
|
|
288
|
+
with mock.patch.dict(os.environ, {"TF_CLIENT_NAME": "n" * 200, "TF_CLIENT_VERSION": "v" * 200}):
|
|
289
|
+
c = TinyFish(api_key=API_KEY, base_url=BASE_URL, max_retries=0)
|
|
290
|
+
route = respx_mock.post(_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
|
|
291
|
+
c.agent.run(**_BODY)
|
|
292
|
+
headers = route.calls[0].request.headers
|
|
293
|
+
assert headers["x-tf-client-name"] == "n" * 128
|
|
294
|
+
assert headers["x-tf-client-version"] == "v" * 128
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def test_search_and_fetch_default_to_their_own_hosts():
|
|
298
|
+
client = TinyFish(api_key="sk-test")
|
|
299
|
+
|
|
300
|
+
assert client.product_url("search") == "https://api.search.tinyfish.ai/"
|
|
301
|
+
assert client.product_url("fetch") == "https://api.fetch.tinyfish.ai/"
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def test_explicit_base_url_keeps_every_product_on_it():
|
|
305
|
+
client = TinyFish(api_key="sk-test", base_url="http://127.0.0.1:4010")
|
|
306
|
+
|
|
307
|
+
assert client.product_url("search") == "/v1/search"
|
|
308
|
+
assert client.product_url("fetch") == "/v1/fetch"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def test_blank_base_url_behaves_like_omitted():
|
|
312
|
+
client = TinyFish(api_key="sk-test", base_url=" ")
|
|
313
|
+
|
|
314
|
+
assert client.product_url("search") == "https://api.search.tinyfish.ai/"
|
|
@@ -481,3 +481,15 @@ async def test_async_get_contents_401(async_client: AsyncTinyFish, respx_mock: M
|
|
|
481
481
|
async with async_client as c:
|
|
482
482
|
with pytest.raises(AuthenticationError):
|
|
483
483
|
await c.fetch.get_contents(["https://example.com"])
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
@pytest.mark.respx
|
|
487
|
+
def test_default_client_calls_the_fetch_host(respx_mock: MockRouter) -> None:
|
|
488
|
+
"""Pins the wire, not the URL builder — see the search-host test."""
|
|
489
|
+
route = respx_mock.post("https://api.fetch.tinyfish.ai/").mock(
|
|
490
|
+
return_value=httpx.Response(200, json={"results": [], "errors": []})
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
TinyFish(api_key="sk-test", max_retries=0).fetch.get_contents(urls=["https://example.com"])
|
|
494
|
+
|
|
495
|
+
assert route.called
|
|
@@ -528,3 +528,17 @@ async def test_async_query_401(async_client: AsyncTinyFish, respx_mock: MockRout
|
|
|
528
528
|
respx_mock.get(_SEARCH_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
|
|
529
529
|
with pytest.raises(AuthenticationError):
|
|
530
530
|
await _do_query(async_client, "test")
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
@pytest.mark.respx
|
|
534
|
+
def test_default_client_calls_the_search_host(respx_mock: MockRouter) -> None:
|
|
535
|
+
"""The URL builder is unit-tested elsewhere; this pins the wire, so a resource that
|
|
536
|
+
forgets product_url cannot silently fall back to the old host."""
|
|
537
|
+
route = respx_mock.get("https://api.search.tinyfish.ai/").mock(
|
|
538
|
+
return_value=httpx.Response(200, json=_search_response())
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
TinyFish(api_key="sk-test", max_retries=0).search.query("agentql pricing")
|
|
542
|
+
|
|
543
|
+
assert route.called
|
|
544
|
+
assert route.calls[0].request.url.params["query"] == "agentql pricing"
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Tests for wallet.get — sync and async."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import pytest
|
|
9
|
+
from pydantic import ValidationError
|
|
10
|
+
from respx import MockRouter
|
|
11
|
+
|
|
12
|
+
from tests.conftest import BASE_URL
|
|
13
|
+
from tinyfish import AsyncTinyFish, AuthenticationError, TinyFish
|
|
14
|
+
from tinyfish.wallet.types import WalletAutoReloadState, WalletResponse
|
|
15
|
+
|
|
16
|
+
# ─── Constants ────────────────────────────────────────────────────────────────
|
|
17
|
+
|
|
18
|
+
_WALLET_PATH = "/v1/wallet"
|
|
19
|
+
_AS_OF = "2026-08-10T18:04:11.220Z"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _meter(**overrides: Any) -> dict[str, Any]:
|
|
23
|
+
base: dict[str, Any] = {
|
|
24
|
+
"product_id": "prod_agent",
|
|
25
|
+
"label": "Agent steps",
|
|
26
|
+
"unit_amount": "0.016000",
|
|
27
|
+
"currency": "USD",
|
|
28
|
+
"per": "step",
|
|
29
|
+
}
|
|
30
|
+
return {**base, **overrides}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _rates(**overrides: Any) -> dict[str, Any]:
|
|
34
|
+
base: dict[str, Any] = {
|
|
35
|
+
"meters": [_meter()],
|
|
36
|
+
"as_of": _AS_OF,
|
|
37
|
+
"source": "metronome-contract",
|
|
38
|
+
}
|
|
39
|
+
return {**base, **overrides}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _wallet_response(**overrides: Any) -> dict[str, Any]:
|
|
43
|
+
base: dict[str, Any] = {
|
|
44
|
+
"available_balance": "21.44",
|
|
45
|
+
"currency": "USD",
|
|
46
|
+
"as_of": _AS_OF,
|
|
47
|
+
"auto_reload": {"state": "unconfigured"},
|
|
48
|
+
"pending_top_up": None,
|
|
49
|
+
"rates": _rates(),
|
|
50
|
+
}
|
|
51
|
+
return {**base, **overrides}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
55
|
+
# wallet.get — sync
|
|
56
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
60
|
+
def test_get_returns_full_shape(client: TinyFish, respx_mock: MockRouter):
|
|
61
|
+
respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
|
|
62
|
+
result = client.wallet.get()
|
|
63
|
+
assert isinstance(result, WalletResponse)
|
|
64
|
+
assert result.available_balance == "21.44"
|
|
65
|
+
assert result.currency == "USD"
|
|
66
|
+
assert result.as_of == _AS_OF
|
|
67
|
+
assert result.auto_reload is not None
|
|
68
|
+
assert result.auto_reload.state == WalletAutoReloadState.UNCONFIGURED
|
|
69
|
+
assert result.pending_top_up is None
|
|
70
|
+
assert result.rates is not None
|
|
71
|
+
assert len(result.rates.meters) == 1
|
|
72
|
+
assert result.rates.source == "metronome-contract"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
76
|
+
def test_get_sends_get_method(client: TinyFish, respx_mock: MockRouter):
|
|
77
|
+
route = respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
|
|
78
|
+
client.wallet.get()
|
|
79
|
+
assert route.calls[0].request.method == "GET"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
83
|
+
def test_get_round_trips_negative_balance(client: TinyFish, respx_mock: MockRouter):
|
|
84
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
85
|
+
return_value=httpx.Response(200, json=_wallet_response(available_balance="-14.02"))
|
|
86
|
+
)
|
|
87
|
+
result = client.wallet.get()
|
|
88
|
+
assert result.available_balance == "-14.02"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
92
|
+
def test_get_fully_degraded_response(client: TinyFish, respx_mock: MockRouter):
|
|
93
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
94
|
+
return_value=httpx.Response(200, json=_wallet_response(auto_reload=None, pending_top_up=None, rates=None))
|
|
95
|
+
)
|
|
96
|
+
result = client.wallet.get()
|
|
97
|
+
assert result.auto_reload is None
|
|
98
|
+
assert result.pending_top_up is None
|
|
99
|
+
assert result.rates is None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
103
|
+
def test_get_auto_reload_unconfigured_has_no_threshold(client: TinyFish, respx_mock: MockRouter):
|
|
104
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
105
|
+
return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "unconfigured"}))
|
|
106
|
+
)
|
|
107
|
+
result = client.wallet.get()
|
|
108
|
+
assert result.auto_reload is not None
|
|
109
|
+
assert result.auto_reload.state == WalletAutoReloadState.UNCONFIGURED
|
|
110
|
+
assert not hasattr(result.auto_reload, "threshold")
|
|
111
|
+
assert not hasattr(result.auto_reload, "recharge_to")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@pytest.mark.parametrize(
|
|
115
|
+
"state",
|
|
116
|
+
["on", "off", "paused_payment_failed", "needs_payment_method"],
|
|
117
|
+
)
|
|
118
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
119
|
+
def test_get_auto_reload_configured_states(state: str, client: TinyFish, respx_mock: MockRouter):
|
|
120
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
121
|
+
return_value=httpx.Response(
|
|
122
|
+
200,
|
|
123
|
+
json=_wallet_response(auto_reload={"state": state, "threshold": "10.00", "recharge_to": "50.00"}),
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
result = client.wallet.get()
|
|
127
|
+
assert result.auto_reload is not None
|
|
128
|
+
assert result.auto_reload.state == state
|
|
129
|
+
assert result.auto_reload.threshold == "10.00"
|
|
130
|
+
assert result.auto_reload.recharge_to == "50.00"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
134
|
+
def test_get_auto_reload_configured_missing_threshold_raises(client: TinyFish, respx_mock: MockRouter):
|
|
135
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
136
|
+
return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "on", "recharge_to": "50.00"}))
|
|
137
|
+
)
|
|
138
|
+
with pytest.raises(ValidationError):
|
|
139
|
+
client.wallet.get()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
143
|
+
def test_get_pending_top_up(client: TinyFish, respx_mock: MockRouter):
|
|
144
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
145
|
+
return_value=httpx.Response(
|
|
146
|
+
200, json=_wallet_response(pending_top_up={"amount": "50.00", "started_at": _AS_OF})
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
result = client.wallet.get()
|
|
150
|
+
assert result.pending_top_up is not None
|
|
151
|
+
assert result.pending_top_up.amount == "50.00"
|
|
152
|
+
assert result.pending_top_up.started_at == _AS_OF
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
156
|
+
def test_get_meter_without_per(client: TinyFish, respx_mock: MockRouter):
|
|
157
|
+
meter = _meter()
|
|
158
|
+
del meter["per"]
|
|
159
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
160
|
+
return_value=httpx.Response(200, json=_wallet_response(rates=_rates(meters=[meter])))
|
|
161
|
+
)
|
|
162
|
+
result = client.wallet.get()
|
|
163
|
+
assert result.rates is not None
|
|
164
|
+
assert result.rates.meters[0].per is None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
168
|
+
def test_get_strips_unknown_field(client: TinyFish, respx_mock: MockRouter):
|
|
169
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
170
|
+
return_value=httpx.Response(200, json=_wallet_response(unexpected_field="surprise"))
|
|
171
|
+
)
|
|
172
|
+
result = client.wallet.get()
|
|
173
|
+
assert result.available_balance == "21.44"
|
|
174
|
+
assert not hasattr(result, "unexpected_field")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
178
|
+
def test_get_401(client: TinyFish, respx_mock: MockRouter):
|
|
179
|
+
respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
|
|
180
|
+
with pytest.raises(AuthenticationError):
|
|
181
|
+
client.wallet.get()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
185
|
+
# wallet.get — async
|
|
186
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
190
|
+
async def test_async_get_returns_full_shape(async_client: AsyncTinyFish, respx_mock: MockRouter):
|
|
191
|
+
respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
|
|
192
|
+
async with async_client as c:
|
|
193
|
+
result = await c.wallet.get()
|
|
194
|
+
assert isinstance(result, WalletResponse)
|
|
195
|
+
assert result.available_balance == "21.44"
|
|
196
|
+
assert result.rates is not None
|
|
197
|
+
assert len(result.rates.meters) == 1
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
201
|
+
async def test_async_get_round_trips_negative_balance(async_client: AsyncTinyFish, respx_mock: MockRouter):
|
|
202
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
203
|
+
return_value=httpx.Response(200, json=_wallet_response(available_balance="-14.02"))
|
|
204
|
+
)
|
|
205
|
+
async with async_client as c:
|
|
206
|
+
result = await c.wallet.get()
|
|
207
|
+
assert result.available_balance == "-14.02"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
211
|
+
async def test_async_get_fully_degraded_response(async_client: AsyncTinyFish, respx_mock: MockRouter):
|
|
212
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
213
|
+
return_value=httpx.Response(200, json=_wallet_response(auto_reload=None, pending_top_up=None, rates=None))
|
|
214
|
+
)
|
|
215
|
+
async with async_client as c:
|
|
216
|
+
result = await c.wallet.get()
|
|
217
|
+
assert result.auto_reload is None
|
|
218
|
+
assert result.pending_top_up is None
|
|
219
|
+
assert result.rates is None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
223
|
+
async def test_async_get_auto_reload_configured_missing_threshold_raises(
|
|
224
|
+
async_client: AsyncTinyFish, respx_mock: MockRouter
|
|
225
|
+
):
|
|
226
|
+
respx_mock.get(_WALLET_PATH).mock(
|
|
227
|
+
return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "on", "recharge_to": "50.00"}))
|
|
228
|
+
)
|
|
229
|
+
async with async_client as c:
|
|
230
|
+
with pytest.raises(ValidationError):
|
|
231
|
+
await c.wallet.get()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@pytest.mark.respx(base_url=BASE_URL)
|
|
235
|
+
async def test_async_get_401(async_client: AsyncTinyFish, respx_mock: MockRouter):
|
|
236
|
+
respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
|
|
237
|
+
async with async_client as c:
|
|
238
|
+
with pytest.raises(AuthenticationError):
|
|
239
|
+
await c.wallet.get()
|
|
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
|
|
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
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|