findcheap 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 llmbender
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: findcheap
3
+ Version: 0.1.0
4
+ Summary: Find where the product on a page is sold for less: the Findcheap API's search, extract and resolve calls.
5
+ Author-email: Findcheap <support@findcheap.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://findcheap.ai/developers
8
+ Project-URL: Documentation, https://findcheap.ai/developers/docs
9
+ Keywords: findcheap,price comparison,shopping,agents,product search
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Internet :: WWW/HTTP
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # findcheap
19
+
20
+ The Findcheap API in Python: where the product on a page is sold for less. Standard library only, Python 3.9+.
21
+
22
+ ```bash
23
+ pip install findcheap
24
+ export FINDCHEAP_API_KEY=fc_live_... # from https://findcheap.ai/signin?next=/dashboard/keys
25
+ ```
26
+
27
+ ```python
28
+ from findcheap import Findcheap, FindcheapApiError
29
+
30
+ fc = Findcheap() # reads FINDCHEAP_API_KEY; or Findcheap(api_key="fc_live_...")
31
+
32
+ answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones", max_results=3)
33
+ print(answer["product"]["title"], "read in", answer["search"]["market"])
34
+ for card in answer["same_product"]:
35
+ print(card["price"], card["currency"], card["retailer"], card["url"] or card["resolve_id"])
36
+
37
+ page = fc.extract("https://www.jlab.com/products/jbuds-lux-anc-headphones")
38
+ if page["is_product_page"]:
39
+ print(page["title"], page["price"], page["currency"])
40
+
41
+ link = fc.resolve(answer["similar_products"][0]["resolve_id"]) # for a card whose url is None
42
+ ```
43
+
44
+ Every answer opens with `request_id` and closes with `credits_used`. A failed call raises `FindcheapApiError` with `.status`, `.type`, `.message`, `.credits_used`, `.request_id` and `.retry_after` (seconds, on a 429); a call that never reached the API raises `FindcheapConnectionError`. Both subclass `FindcheapError`.
45
+
46
+ Timeouts sit above the API's own ceilings (a search answers within 90 seconds, a read within 30): 100, 40 and 20 seconds for search, extract and resolve, or one `timeout=` for all three.
47
+
48
+ The reference, with every field: https://findcheap.ai/developers/docs.md.
@@ -0,0 +1,31 @@
1
+ # findcheap
2
+
3
+ The Findcheap API in Python: where the product on a page is sold for less. Standard library only, Python 3.9+.
4
+
5
+ ```bash
6
+ pip install findcheap
7
+ export FINDCHEAP_API_KEY=fc_live_... # from https://findcheap.ai/signin?next=/dashboard/keys
8
+ ```
9
+
10
+ ```python
11
+ from findcheap import Findcheap, FindcheapApiError
12
+
13
+ fc = Findcheap() # reads FINDCHEAP_API_KEY; or Findcheap(api_key="fc_live_...")
14
+
15
+ answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones", max_results=3)
16
+ print(answer["product"]["title"], "read in", answer["search"]["market"])
17
+ for card in answer["same_product"]:
18
+ print(card["price"], card["currency"], card["retailer"], card["url"] or card["resolve_id"])
19
+
20
+ page = fc.extract("https://www.jlab.com/products/jbuds-lux-anc-headphones")
21
+ if page["is_product_page"]:
22
+ print(page["title"], page["price"], page["currency"])
23
+
24
+ link = fc.resolve(answer["similar_products"][0]["resolve_id"]) # for a card whose url is None
25
+ ```
26
+
27
+ Every answer opens with `request_id` and closes with `credits_used`. A failed call raises `FindcheapApiError` with `.status`, `.type`, `.message`, `.credits_used`, `.request_id` and `.retry_after` (seconds, on a 429); a call that never reached the API raises `FindcheapConnectionError`. Both subclass `FindcheapError`.
28
+
29
+ Timeouts sit above the API's own ceilings (a search answers within 90 seconds, a read within 30): 100, 40 and 20 seconds for search, extract and resolve, or one `timeout=` for all three.
30
+
31
+ The reference, with every field: https://findcheap.ai/developers/docs.md.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "findcheap"
7
+ version = "0.1.0"
8
+ description = "Find where the product on a page is sold for less: the Findcheap API's search, extract and resolve calls."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "Findcheap", email = "support@findcheap.ai" }]
13
+ keywords = ["findcheap", "price comparison", "shopping", "agents", "product search"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Internet :: WWW/HTTP",
18
+ ]
19
+ dependencies = []
20
+
21
+ [project.urls]
22
+ Homepage = "https://findcheap.ai/developers"
23
+ Documentation = "https://findcheap.ai/developers/docs"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ """The Findcheap API in Python: where the product on a page is sold for less.
2
+
3
+ from findcheap import Findcheap
4
+ fc = Findcheap() # FINDCHEAP_API_KEY in the environment
5
+ answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones")
6
+
7
+ Reference: https://findcheap.ai/developers/docs.md
8
+ """
9
+ from .client import (
10
+ Findcheap,
11
+ FindcheapApiError,
12
+ FindcheapConnectionError,
13
+ FindcheapError,
14
+ Card,
15
+ ReadAnswer,
16
+ ResolveAnswer,
17
+ SearchAnswer,
18
+ SearchEcho,
19
+ __version__,
20
+ )
21
+
22
+ __all__ = [
23
+ "Findcheap", "FindcheapError", "FindcheapApiError", "FindcheapConnectionError",
24
+ "Card", "ReadAnswer", "ResolveAnswer", "SearchAnswer", "SearchEcho", "__version__",
25
+ ]
@@ -0,0 +1,204 @@
1
+ """The client: three POSTs over urllib, the answer as the API sends it.
2
+
3
+ Nothing is reshaped. A search answer opens with `request_id` and `search`
4
+ (what was searched), then `product`, `product_name`, `same_product`,
5
+ `similar_products`, `page_is_cheapest`, `credits_used`; the TypedDicts
6
+ below name the fields for an editor, and `extra="allow"` on the API's
7
+ side means a field added later arrives here untouched.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import socket
14
+ import urllib.error
15
+ import urllib.request
16
+ from typing import Any, Dict, List, Literal, Optional, TypedDict
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ DEFAULT_BASE_URL = "https://api.findcheap.ai"
21
+ # Above the API's own walls (a search answers within 90 s, a read within 30),
22
+ # so the API's timeout envelope, not a client cut-off, is what a caller sees.
23
+ SEARCH_TIMEOUT_S = 100.0
24
+ EXTRACT_TIMEOUT_S = 40.0
25
+ RESOLVE_TIMEOUT_S = 20.0
26
+
27
+ Condition = Literal["new", "used"]
28
+
29
+
30
+ class SearchEcho(TypedDict):
31
+ """What was searched: the address as sent, the market the search ran in, the condition, the cap."""
32
+ url: str
33
+ market: str
34
+ condition: str
35
+ max_results: int
36
+
37
+
38
+ class Product(TypedDict):
39
+ """The page as read."""
40
+ title: Optional[str]
41
+ image: Optional[str]
42
+ price: Optional[float]
43
+ currency: Optional[str]
44
+ brand: Optional[str]
45
+ url: str
46
+ market: str
47
+ in_stock: Optional[bool]
48
+
49
+
50
+ class Card(TypedDict, total=False):
51
+ """One listing elsewhere. `url` None means a `resolve_id` to pass to resolve()."""
52
+ title: str
53
+ price: float
54
+ currency: str
55
+ url: Optional[str]
56
+ resolve_id: Optional[str]
57
+ image: str
58
+ retailer: str
59
+ rating: Optional[float]
60
+ ratings_count: Optional[int]
61
+ over_page_price: Optional[bool] # same_product cards only
62
+ unit_size: Optional[str]
63
+ pack_count: Optional[int]
64
+ normalized_price: Optional[float]
65
+ coupon: Optional[str]
66
+ promo_code: Optional[str]
67
+ price_before_discount: Optional[float]
68
+ discount_type: Optional[str]
69
+ discount_value: Optional[float]
70
+
71
+
72
+ class SearchAnswer(TypedDict):
73
+ request_id: str
74
+ search: SearchEcho
75
+ product: Product
76
+ product_name: Optional[str]
77
+ same_product: List[Card]
78
+ similar_products: List[Card]
79
+ page_is_cheapest: bool
80
+ credits_used: int
81
+
82
+
83
+ class ReadAnswer(TypedDict):
84
+ request_id: str
85
+ is_product_page: bool
86
+ url: str
87
+ market: str
88
+ title: Optional[str]
89
+ image: Optional[str]
90
+ price: Optional[float]
91
+ currency: Optional[str]
92
+ brand: Optional[str]
93
+ in_stock: Optional[bool]
94
+ reason: Optional[str]
95
+ credits_used: int
96
+
97
+
98
+ class ResolveAnswer(TypedDict):
99
+ request_id: str
100
+ resolved: bool
101
+ url: Optional[str]
102
+ retailer: Optional[str]
103
+ credits_used: int
104
+
105
+
106
+ class FindcheapError(Exception):
107
+ """Anything that stopped a call: the API's answer (FindcheapApiError) or the network (FindcheapConnectionError)."""
108
+
109
+
110
+ class FindcheapApiError(FindcheapError):
111
+ """The API answered an error: its envelope's type, message, credits_used and request_id, plus the HTTP status.
112
+
113
+ `type` is one of the reference's: invalid_request, invalid_url, unknown_market, unauthorized,
114
+ credits_exhausted, account_suspended, not_searchable, refused, rate_limited, unreachable,
115
+ timeout, search_failed, account_service_unavailable — or "http_error" when the body was not
116
+ the API's envelope (a proxy's page). `retry_after` is the 429's header, in seconds, else None.
117
+ """
118
+
119
+ def __init__(self, status: int, type_: str, message: str, credits_used: int = 0,
120
+ request_id: Optional[str] = None, retry_after: Optional[int] = None):
121
+ super().__init__(f"{status} {type_}: {message}")
122
+ self.status, self.type, self.message = status, type_, message
123
+ self.credits_used, self.request_id, self.retry_after = credits_used, request_id, retry_after
124
+
125
+
126
+ class FindcheapConnectionError(FindcheapError):
127
+ """The call never got an answer: no connection, a DNS failure, or the client's own timeout."""
128
+
129
+
130
+ class Findcheap:
131
+ """The client. `api_key` defaults to the FINDCHEAP_API_KEY environment variable; `timeout`, when
132
+ given, replaces the per-call defaults (100 s search, 40 s extract, 20 s resolve)."""
133
+
134
+ def __init__(self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL,
135
+ timeout: Optional[float] = None, user_agent: Optional[str] = None):
136
+ key = api_key or os.environ.get("FINDCHEAP_API_KEY")
137
+ if not key:
138
+ raise ValueError("Findcheap needs an API key: pass api_key=... or set FINDCHEAP_API_KEY "
139
+ "(create one at https://findcheap.ai/signin?next=/dashboard/keys).")
140
+ self._key = key
141
+ self._base = base_url.rstrip("/")
142
+ self._timeout = timeout
143
+ self._user_agent = user_agent or f"findcheap-python/{__version__}"
144
+
145
+ # ── The three calls ──────────────────────────────────────────────
146
+
147
+ def search(self, url: str, *, market: Optional[str] = None, marketplaces: Optional[List[str]] = None,
148
+ condition: Condition = "new", max_results: Optional[int] = None) -> SearchAnswer:
149
+ """Where the product on the page is sold for less (10 credits; up to 90 s). Only the options
150
+ given travel in the body, so the API's defaults apply to the rest."""
151
+ body: Dict[str, Any] = {"url": url}
152
+ if market is not None:
153
+ body["market"] = market
154
+ if marketplaces is not None:
155
+ body["marketplaces"] = list(marketplaces)
156
+ if condition != "new":
157
+ body["condition"] = condition
158
+ if max_results is not None:
159
+ body["max_results"] = max_results
160
+ return self._post("/v1/search", body, SEARCH_TIMEOUT_S) # type: ignore[return-value]
161
+
162
+ def extract(self, url: str, *, market: Optional[str] = None) -> ReadAnswer:
163
+ """What the page sells, without a search (1 credit; up to 30 s)."""
164
+ body: Dict[str, Any] = {"url": url}
165
+ if market is not None:
166
+ body["market"] = market
167
+ return self._post("/v1/extract", body, EXTRACT_TIMEOUT_S) # type: ignore[return-value]
168
+
169
+ def resolve(self, resolve_id: str) -> ResolveAnswer:
170
+ """The merchant's link for a card that came with a resolve_id (1 credit when a link came back)."""
171
+ return self._post("/v1/resolve", {"id": resolve_id}, RESOLVE_TIMEOUT_S) # type: ignore[return-value]
172
+
173
+ # ── The wire ─────────────────────────────────────────────────────
174
+
175
+ def _post(self, path: str, body: Dict[str, Any], default_timeout: float) -> Dict[str, Any]:
176
+ data = json.dumps(body).encode("utf-8")
177
+ request = urllib.request.Request(
178
+ self._base + path, data=data, method="POST",
179
+ headers={"Authorization": f"Bearer {self._key}", "Content-Type": "application/json",
180
+ "Accept": "application/json", "User-Agent": self._user_agent})
181
+ timeout = self._timeout if self._timeout is not None else default_timeout
182
+ try:
183
+ with urllib.request.urlopen(request, timeout=timeout) as response:
184
+ return json.loads(response.read().decode("utf-8"))
185
+ except urllib.error.HTTPError as exc:
186
+ raise _api_error(exc) from None
187
+ except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError) as exc:
188
+ raise FindcheapConnectionError(f"Findcheap could not be reached: {exc}") from exc
189
+
190
+
191
+ def _api_error(exc: urllib.error.HTTPError) -> FindcheapApiError:
192
+ """The API's envelope as an exception; a body that is not the envelope (a proxy's page) is
193
+ "http_error" with the status's reason."""
194
+ raw = exc.read()
195
+ try:
196
+ error = json.loads(raw.decode("utf-8")).get("error") or {}
197
+ except (ValueError, UnicodeDecodeError):
198
+ error = {}
199
+ retry_after = exc.headers.get("Retry-After") if exc.headers else None
200
+ return FindcheapApiError(
201
+ exc.code, str(error.get("type") or "http_error"),
202
+ str(error.get("message") or exc.reason or f"HTTP {exc.code}"),
203
+ credits_used=int(error.get("credits_used") or 0), request_id=error.get("request_id"),
204
+ retry_after=int(retry_after) if retry_after and str(retry_after).isdigit() else None)
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: findcheap
3
+ Version: 0.1.0
4
+ Summary: Find where the product on a page is sold for less: the Findcheap API's search, extract and resolve calls.
5
+ Author-email: Findcheap <support@findcheap.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://findcheap.ai/developers
8
+ Project-URL: Documentation, https://findcheap.ai/developers/docs
9
+ Keywords: findcheap,price comparison,shopping,agents,product search
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Internet :: WWW/HTTP
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # findcheap
19
+
20
+ The Findcheap API in Python: where the product on a page is sold for less. Standard library only, Python 3.9+.
21
+
22
+ ```bash
23
+ pip install findcheap
24
+ export FINDCHEAP_API_KEY=fc_live_... # from https://findcheap.ai/signin?next=/dashboard/keys
25
+ ```
26
+
27
+ ```python
28
+ from findcheap import Findcheap, FindcheapApiError
29
+
30
+ fc = Findcheap() # reads FINDCHEAP_API_KEY; or Findcheap(api_key="fc_live_...")
31
+
32
+ answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones", max_results=3)
33
+ print(answer["product"]["title"], "read in", answer["search"]["market"])
34
+ for card in answer["same_product"]:
35
+ print(card["price"], card["currency"], card["retailer"], card["url"] or card["resolve_id"])
36
+
37
+ page = fc.extract("https://www.jlab.com/products/jbuds-lux-anc-headphones")
38
+ if page["is_product_page"]:
39
+ print(page["title"], page["price"], page["currency"])
40
+
41
+ link = fc.resolve(answer["similar_products"][0]["resolve_id"]) # for a card whose url is None
42
+ ```
43
+
44
+ Every answer opens with `request_id` and closes with `credits_used`. A failed call raises `FindcheapApiError` with `.status`, `.type`, `.message`, `.credits_used`, `.request_id` and `.retry_after` (seconds, on a 429); a call that never reached the API raises `FindcheapConnectionError`. Both subclass `FindcheapError`.
45
+
46
+ Timeouts sit above the API's own ceilings (a search answers within 90 seconds, a read within 30): 100, 40 and 20 seconds for search, extract and resolve, or one `timeout=` for all three.
47
+
48
+ The reference, with every field: https://findcheap.ai/developers/docs.md.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/findcheap/__init__.py
5
+ src/findcheap/client.py
6
+ src/findcheap.egg-info/PKG-INFO
7
+ src/findcheap.egg-info/SOURCES.txt
8
+ src/findcheap.egg-info/dependency_links.txt
9
+ src/findcheap.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ findcheap
@@ -0,0 +1,121 @@
1
+ """Offline tests of the Python client over a local stub of the API: no network, no key, no spend.
2
+
3
+ cd findcheap-sdks/python && python3 -m unittest -v
4
+ """
5
+ import json
6
+ import os
7
+ import sys
8
+ import threading
9
+ import unittest
10
+ from http.server import BaseHTTPRequestHandler, HTTPServer
11
+
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
13
+ from findcheap import Findcheap, FindcheapApiError, FindcheapConnectionError # noqa: E402
14
+
15
+ SEARCH = {"request_id": "r-1", "search": {"url": "https://shop.example.com/p/1", "market": "US", "condition": "new", "max_results": 3},
16
+ "product": {"title": "Kettle", "image": None, "price": 29.99, "currency": "USD", "brand": "Acme", "url": "https://shop.example.com/p/1", "market": "US", "in_stock": True},
17
+ "product_name": "Acme Kettle", "same_product": [{"title": "Kettle", "price": 19.0, "currency": "USD", "url": "https://w/x", "image": "i", "retailer": "eBay", "over_page_price": False}],
18
+ "similar_products": [], "page_is_cheapest": False, "credits_used": 10}
19
+ READ = {"request_id": "r-2", "is_product_page": True, "url": "https://shop.example.com/p/1", "market": "US", "title": "Kettle", "image": None,
20
+ "price": 29.99, "currency": "USD", "brand": "Acme", "in_stock": True, "reason": None, "credits_used": 1}
21
+ RESOLVE = {"request_id": "r-3", "resolved": True, "url": "https://merchant/x", "retailer": "Walmart", "credits_used": 1}
22
+ seen = []
23
+
24
+
25
+ class Stub(BaseHTTPRequestHandler):
26
+ def do_POST(self):
27
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
28
+ seen.append((self.path, dict(self.headers), body))
29
+ if self.headers.get("Authorization") != "Bearer fc_live_test":
30
+ return self._send(401, {"error": {"type": "unauthorized", "message": "No key.", "credits_used": 0, "request_id": "e-0"}})
31
+ if body.get("url") == "https://en.wikipedia.org/wiki/Shoe":
32
+ return self._send(422, {"error": {"type": "not_searchable", "message": "Not a product page. Billed as a page read: 1 credit.", "credits_used": 1, "request_id": "e-1"}})
33
+ if body.get("url") == "https://slow.example/p":
34
+ return self._send(429, {"error": {"type": "rate_limited", "message": "Wait.", "credits_used": 0, "request_id": "e-2"}}, {"Retry-After": "7"})
35
+ if body.get("url") == "https://proxy.example/p":
36
+ self.send_response(502); self.send_header("Content-Type", "text/html"); self.end_headers(); self.wfile.write(b"<html>Bad Gateway</html>"); return
37
+ answer = {"/v1/search": SEARCH, "/v1/extract": READ, "/v1/resolve": RESOLVE}[self.path]
38
+ self._send(200, answer)
39
+
40
+ def _send(self, status, payload, headers=None):
41
+ self.send_response(status)
42
+ self.send_header("Content-Type", "application/json")
43
+ for k, v in (headers or {}).items():
44
+ self.send_header(k, v)
45
+ self.end_headers()
46
+ self.wfile.write(json.dumps(payload).encode())
47
+
48
+ def log_message(self, *a): # quiet
49
+ pass
50
+
51
+
52
+ class ClientTest(unittest.TestCase):
53
+ @classmethod
54
+ def setUpClass(cls):
55
+ cls.server = HTTPServer(("127.0.0.1", 0), Stub)
56
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
57
+ cls.base = f"http://127.0.0.1:{cls.server.server_port}"
58
+ cls.fc = Findcheap(api_key="fc_live_test", base_url=cls.base)
59
+
60
+ @classmethod
61
+ def tearDownClass(cls):
62
+ cls.server.shutdown()
63
+
64
+ def test_search_sends_only_what_was_given_and_returns_the_answer_as_is(self):
65
+ seen.clear()
66
+ out = self.fc.search("https://shop.example.com/p/1", max_results=3)
67
+ path, headers, body = seen[-1]
68
+ self.assertEqual(path, "/v1/search")
69
+ self.assertEqual(body, {"url": "https://shop.example.com/p/1", "max_results": 3})
70
+ self.assertEqual(headers["Authorization"], "Bearer fc_live_test")
71
+ self.assertTrue(headers["User-Agent"].startswith("findcheap-python/"))
72
+ self.assertEqual(list(out), ["request_id", "search", "product", "product_name", "same_product", "similar_products", "page_is_cheapest", "credits_used"])
73
+ self.assertEqual(out["credits_used"], 10)
74
+
75
+ def test_search_options_travel_as_the_api_takes_them(self):
76
+ seen.clear()
77
+ self.fc.search("https://shop.example.com/p/1", market="in", marketplaces=["amazon", "flipkart"], condition="used")
78
+ self.assertEqual(seen[-1][2], {"url": "https://shop.example.com/p/1", "market": "in", "marketplaces": ["amazon", "flipkart"], "condition": "used"})
79
+
80
+ def test_extract_and_resolve(self):
81
+ self.assertEqual(self.fc.extract("https://shop.example.com/p/1", market="US")["title"], "Kettle")
82
+ self.assertEqual(seen[-1][2], {"url": "https://shop.example.com/p/1", "market": "US"})
83
+ self.assertEqual(self.fc.resolve("abc")["retailer"], "Walmart")
84
+ self.assertEqual(seen[-1][0], "/v1/resolve")
85
+ self.assertEqual(seen[-1][2], {"id": "abc"})
86
+
87
+ def test_the_envelope_becomes_an_api_error_with_its_fields(self):
88
+ with self.assertRaises(FindcheapApiError) as cm:
89
+ self.fc.search("https://en.wikipedia.org/wiki/Shoe")
90
+ e = cm.exception
91
+ self.assertEqual((e.status, e.type, e.credits_used, e.request_id, e.retry_after), (422, "not_searchable", 1, "e-1", None))
92
+ self.assertIn("Billed as a page read", e.message)
93
+ self.assertEqual(str(e), "422 not_searchable: Not a product page. Billed as a page read: 1 credit.")
94
+
95
+ def test_a_429_carries_retry_after(self):
96
+ with self.assertRaises(FindcheapApiError) as cm:
97
+ self.fc.extract("https://slow.example/p")
98
+ self.assertEqual((cm.exception.type, cm.exception.retry_after), ("rate_limited", 7))
99
+
100
+ def test_a_body_that_is_not_the_envelope_is_http_error(self):
101
+ with self.assertRaises(FindcheapApiError) as cm:
102
+ self.fc.extract("https://proxy.example/p")
103
+ self.assertEqual((cm.exception.status, cm.exception.type, cm.exception.credits_used), (502, "http_error", 0))
104
+
105
+ def test_a_wrong_key_is_unauthorized(self):
106
+ with self.assertRaises(FindcheapApiError) as cm:
107
+ Findcheap(api_key="fc_live_wrong", base_url=self.base).resolve("x")
108
+ self.assertEqual(cm.exception.type, "unauthorized")
109
+
110
+ def test_no_server_is_a_connection_error(self):
111
+ with self.assertRaises(FindcheapConnectionError):
112
+ Findcheap(api_key="fc_live_test", base_url="http://127.0.0.1:9", timeout=2).resolve("x")
113
+
114
+ def test_no_key_anywhere_is_a_value_error(self):
115
+ os.environ.pop("FINDCHEAP_API_KEY", None)
116
+ with self.assertRaises(ValueError):
117
+ Findcheap()
118
+
119
+
120
+ if __name__ == "__main__":
121
+ unittest.main()