blockquote-agents 0.1.2__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 Arne Kellmann
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,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: blockquote-agents
3
+ Version: 0.1.2
4
+ Summary: Official Blockquote SDK and CLI for blockquote.io: Python API client for AI citability scans and report comparisons.
5
+ License: MIT
6
+ Project-URL: Homepage, https://blockquote.io
7
+ Project-URL: Repository, https://github.com/ArneFfm/blockquote-agents
8
+ Project-URL: Documentation, https://blockquote.io/developers
9
+ Project-URL: Bug Tracker, https://github.com/ArneFfm/blockquote-agents/issues
10
+ Keywords: blockquote,blockquote.io,sdk,api-client,cli,ai-citability
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # Blockquote Python SDK and CLI
17
+
18
+ Official client for [Blockquote](https://blockquote.io). Requires Python 3.10 or later. No runtime dependencies.
19
+
20
+ ```sh
21
+ pip install blockquote-agents
22
+ ```
23
+
24
+ ```python
25
+ import os
26
+ import uuid
27
+ from blockquote_agents import Blockquote, BlockquoteError
28
+
29
+ client = Blockquote(api_key=os.getenv("BLOCKQUOTE_API_KEY"))
30
+ started = client.start_scan("https://example.com", idempotency_key=str(uuid.uuid4()))
31
+ print(started.data, started.headers.get("Retry-After"))
32
+ # Wait for Retry-After, then read the returned id.
33
+ report = client.get_scan(started.data["id"])
34
+ comparison = client.compare_scans(from_id="BASELINE_ID", to_id="NEW_ID")
35
+ ```
36
+
37
+ Each call returns a `Response` with `data`, `status`, and HTTP `headers`.
38
+ `BlockquoteError` retains `data`, `status`, `headers`, and `retry_after`. Network errors pass through.
39
+ Requests time out after 30 seconds. Set `timeout` in the constructor to change this.
40
+ The client does not retry or poll automatically. Scans can return a cached result or pending status.
41
+ Reuse an idempotency key only when you repeat the same scan request.
42
+
43
+ Public report reads need no key. Account access uses an optional bearer key from [your account](https://blockquote.io/account).
44
+ Keys require Pro or Agency. Unattended scan creation can require a paid key with the `scan` scope.
45
+ Human verification still applies where required. Pass `turnstile_token` when available; the SDK does not obtain or bypass verification.
46
+ Pass `refresh=True` to request a fresh scan with account authentication. Scan quotas still apply.
47
+ Read access and comparison output follow your account plan.
48
+
49
+ See the [API reference](https://blockquote.io/api/docs) and [OpenAPI document](https://blockquote.io/api/v1/openapi.json).
50
+
51
+ Run tests from this package directory:
52
+
53
+ ```sh
54
+ python3 -m unittest discover -s tests
55
+ ```
56
+
57
+ ## Command line
58
+
59
+ The package installs the `blockquote` command. `python -m blockquote_agents` runs the same CLI.
60
+
61
+ ```sh
62
+ python -m pip install --upgrade blockquote-agents
63
+ blockquote --help
64
+ blockquote read SCAN_ID
65
+ blockquote scan https://example.com --idempotency-key UNIQUE_REQUEST_ID
66
+ blockquote compare BASELINE_ID NEW_ID
67
+ ```
68
+
69
+ Set `BLOCKQUOTE_API_KEY` for account access. Set `BLOCKQUOTE_TURNSTILE_TOKEN` only when you have a human verification token.
70
+ Use `--refresh` with `scan` to request a fresh scan. Authentication and quota rules remain the same.
71
+ The CLI prints JSON with `data`, `status`, and `headers`. It does not poll or retry.
72
+ HTTP failures print server data, headers, status, and `retryAfter` to stderr with exit code 1.
73
+ Other request failures print only their error type to avoid exposing credentials. Invalid arguments exit with code 2.
@@ -0,0 +1,58 @@
1
+ # Blockquote Python SDK and CLI
2
+
3
+ Official client for [Blockquote](https://blockquote.io). Requires Python 3.10 or later. No runtime dependencies.
4
+
5
+ ```sh
6
+ pip install blockquote-agents
7
+ ```
8
+
9
+ ```python
10
+ import os
11
+ import uuid
12
+ from blockquote_agents import Blockquote, BlockquoteError
13
+
14
+ client = Blockquote(api_key=os.getenv("BLOCKQUOTE_API_KEY"))
15
+ started = client.start_scan("https://example.com", idempotency_key=str(uuid.uuid4()))
16
+ print(started.data, started.headers.get("Retry-After"))
17
+ # Wait for Retry-After, then read the returned id.
18
+ report = client.get_scan(started.data["id"])
19
+ comparison = client.compare_scans(from_id="BASELINE_ID", to_id="NEW_ID")
20
+ ```
21
+
22
+ Each call returns a `Response` with `data`, `status`, and HTTP `headers`.
23
+ `BlockquoteError` retains `data`, `status`, `headers`, and `retry_after`. Network errors pass through.
24
+ Requests time out after 30 seconds. Set `timeout` in the constructor to change this.
25
+ The client does not retry or poll automatically. Scans can return a cached result or pending status.
26
+ Reuse an idempotency key only when you repeat the same scan request.
27
+
28
+ Public report reads need no key. Account access uses an optional bearer key from [your account](https://blockquote.io/account).
29
+ Keys require Pro or Agency. Unattended scan creation can require a paid key with the `scan` scope.
30
+ Human verification still applies where required. Pass `turnstile_token` when available; the SDK does not obtain or bypass verification.
31
+ Pass `refresh=True` to request a fresh scan with account authentication. Scan quotas still apply.
32
+ Read access and comparison output follow your account plan.
33
+
34
+ See the [API reference](https://blockquote.io/api/docs) and [OpenAPI document](https://blockquote.io/api/v1/openapi.json).
35
+
36
+ Run tests from this package directory:
37
+
38
+ ```sh
39
+ python3 -m unittest discover -s tests
40
+ ```
41
+
42
+ ## Command line
43
+
44
+ The package installs the `blockquote` command. `python -m blockquote_agents` runs the same CLI.
45
+
46
+ ```sh
47
+ python -m pip install --upgrade blockquote-agents
48
+ blockquote --help
49
+ blockquote read SCAN_ID
50
+ blockquote scan https://example.com --idempotency-key UNIQUE_REQUEST_ID
51
+ blockquote compare BASELINE_ID NEW_ID
52
+ ```
53
+
54
+ Set `BLOCKQUOTE_API_KEY` for account access. Set `BLOCKQUOTE_TURNSTILE_TOKEN` only when you have a human verification token.
55
+ Use `--refresh` with `scan` to request a fresh scan. Authentication and quota rules remain the same.
56
+ The CLI prints JSON with `data`, `status`, and `headers`. It does not poll or retry.
57
+ HTTP failures print server data, headers, status, and `retryAfter` to stderr with exit code 1.
58
+ Other request failures print only their error type to avoid exposing credentials. Invalid arguments exit with code 2.
@@ -0,0 +1,82 @@
1
+ """Official Blockquote client. Uses Python's standard library."""
2
+ import json
3
+ from dataclasses import dataclass
4
+ from urllib.error import HTTPError
5
+ from urllib.parse import quote, urlencode, urlsplit
6
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
7
+
8
+
9
+ @dataclass
10
+ class Response:
11
+ data: object
12
+ status: int
13
+ headers: object
14
+
15
+
16
+ class BlockquoteError(Exception):
17
+ def __init__(self, response):
18
+ super().__init__(f"Blockquote HTTP {response.status}")
19
+ self.data = response.data
20
+ self.status = response.status
21
+ self.headers = response.headers
22
+ self.retry_after = response.headers.get("Retry-After")
23
+
24
+
25
+ class _NoRedirect(HTTPRedirectHandler):
26
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
27
+ return None
28
+
29
+
30
+ class Blockquote:
31
+ def __init__(self, api_key=None, base_url="https://blockquote.io/api/v1", timeout=30):
32
+ base = urlsplit(base_url)
33
+ if base.scheme != "https" or not base.netloc or base.username or base.password or base.query or base.fragment:
34
+ raise ValueError("base_url must be an HTTPS URL without credentials, query, or fragment")
35
+ self.base_url = base_url.rstrip("/")
36
+ self.api_key = api_key
37
+ self.timeout = timeout
38
+ self._opener = build_opener(_NoRedirect())
39
+
40
+ def _request(self, path, body=None, idempotency_key=None):
41
+ headers = {"Accept": "application/json"}
42
+ if self.api_key:
43
+ headers["Authorization"] = f"Bearer {self.api_key}"
44
+ if body is not None:
45
+ headers["Content-Type"] = "application/json"
46
+ if idempotency_key:
47
+ headers["Idempotency-Key"] = idempotency_key
48
+ request = Request(self.base_url + path, headers=headers,
49
+ data=None if body is None else json.dumps(body).encode())
50
+ try:
51
+ raw = self._opener.open(request, timeout=self.timeout)
52
+ except HTTPError as error:
53
+ raw = error
54
+ with raw:
55
+ text = raw.read().decode("utf-8", errors="replace")
56
+ try:
57
+ data = json.loads(text)
58
+ except ValueError:
59
+ data = text
60
+ response = Response(data, raw.status, raw.headers)
61
+ if not 200 <= response.status < 300:
62
+ raise BlockquoteError(response)
63
+ return response
64
+
65
+ def start_scan(self, url, *, refresh=None, turnstile_token=None, idempotency_key=None):
66
+ body = {"url": url}
67
+ if refresh is not None:
68
+ body["refresh"] = refresh
69
+ if turnstile_token is not None:
70
+ body["turnstileToken"] = turnstile_token
71
+ return self._request("/scan", body, idempotency_key)
72
+
73
+ def get_scan(self, scan_id):
74
+ if not isinstance(scan_id, str) or not scan_id.strip() or scan_id in (".", ".."):
75
+ raise ValueError("A scan id is required")
76
+ return self._request("/scan/" + quote(scan_id, safe=""))
77
+
78
+ def compare_scans(self, *, from_id=None, to_id=None, url=None):
79
+ if (url and (from_id is not None or to_id is not None)) or (not url and (not from_id or not to_id)):
80
+ raise ValueError("Use url or both from_id and to_id")
81
+ query = {"url": url} if url else {"from": from_id, "to": to_id}
82
+ return self._request("/compare?" + urlencode(query))
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,57 @@
1
+ """Command-line access to the Blockquote client."""
2
+ import argparse
3
+ import json
4
+ import os
5
+ import sys
6
+
7
+ from . import Blockquote, BlockquoteError
8
+
9
+
10
+ def main(argv=None):
11
+ parser = argparse.ArgumentParser(
12
+ prog="blockquote",
13
+ description="Read and start Blockquote AI visibility scans.",
14
+ epilog=("Set BLOCKQUOTE_API_KEY for account access. Public reads need no key. "
15
+ "Scan creation can require a paid key or human verification. "
16
+ "Set BLOCKQUOTE_TURNSTILE_TOKEN for a human verification token. "
17
+ "Scans are asynchronous. Wait for Retry-After before reading the returned id. "
18
+ "No automatic retries are made."),
19
+ )
20
+ commands = parser.add_subparsers(dest="command")
21
+ scan = commands.add_parser("scan", help="Start a scan")
22
+ scan.add_argument("url")
23
+ scan.add_argument("--refresh", action="store_true", default=None)
24
+ scan.add_argument("--idempotency-key")
25
+ read = commands.add_parser("read", help="Read a report or pending status")
26
+ read.add_argument("scan_id")
27
+ compare = commands.add_parser("compare", help="Compare two scans")
28
+ compare.add_argument("from_id")
29
+ compare.add_argument("to_id")
30
+ args = parser.parse_args(argv)
31
+ if args.command is None:
32
+ parser.print_help()
33
+ return 0
34
+ try:
35
+ client = Blockquote(api_key=os.getenv("BLOCKQUOTE_API_KEY"))
36
+ if args.command == "scan":
37
+ result = client.start_scan(
38
+ args.url, refresh=args.refresh,
39
+ idempotency_key=args.idempotency_key,
40
+ turnstile_token=os.getenv("BLOCKQUOTE_TURNSTILE_TOKEN"),
41
+ )
42
+ elif args.command == "read":
43
+ result = client.get_scan(args.scan_id)
44
+ else:
45
+ result = client.compare_scans(from_id=args.from_id, to_id=args.to_id)
46
+ print(json.dumps({"data": result.data, "status": result.status,
47
+ "headers": dict(result.headers.items())}, indent=2))
48
+ return 0
49
+ except BlockquoteError as error:
50
+ print(json.dumps({"error": str(error), "status": error.status, "data": error.data,
51
+ "headers": dict(error.headers.items()),
52
+ "retryAfter": error.retry_after}), file=sys.stderr)
53
+ return 1
54
+ except Exception as error:
55
+ # Header validation errors can contain credentials; print the error type only.
56
+ print(json.dumps({"error": f"Request failed ({type(error).__name__})."}), file=sys.stderr)
57
+ return 1
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: blockquote-agents
3
+ Version: 0.1.2
4
+ Summary: Official Blockquote SDK and CLI for blockquote.io: Python API client for AI citability scans and report comparisons.
5
+ License: MIT
6
+ Project-URL: Homepage, https://blockquote.io
7
+ Project-URL: Repository, https://github.com/ArneFfm/blockquote-agents
8
+ Project-URL: Documentation, https://blockquote.io/developers
9
+ Project-URL: Bug Tracker, https://github.com/ArneFfm/blockquote-agents/issues
10
+ Keywords: blockquote,blockquote.io,sdk,api-client,cli,ai-citability
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # Blockquote Python SDK and CLI
17
+
18
+ Official client for [Blockquote](https://blockquote.io). Requires Python 3.10 or later. No runtime dependencies.
19
+
20
+ ```sh
21
+ pip install blockquote-agents
22
+ ```
23
+
24
+ ```python
25
+ import os
26
+ import uuid
27
+ from blockquote_agents import Blockquote, BlockquoteError
28
+
29
+ client = Blockquote(api_key=os.getenv("BLOCKQUOTE_API_KEY"))
30
+ started = client.start_scan("https://example.com", idempotency_key=str(uuid.uuid4()))
31
+ print(started.data, started.headers.get("Retry-After"))
32
+ # Wait for Retry-After, then read the returned id.
33
+ report = client.get_scan(started.data["id"])
34
+ comparison = client.compare_scans(from_id="BASELINE_ID", to_id="NEW_ID")
35
+ ```
36
+
37
+ Each call returns a `Response` with `data`, `status`, and HTTP `headers`.
38
+ `BlockquoteError` retains `data`, `status`, `headers`, and `retry_after`. Network errors pass through.
39
+ Requests time out after 30 seconds. Set `timeout` in the constructor to change this.
40
+ The client does not retry or poll automatically. Scans can return a cached result or pending status.
41
+ Reuse an idempotency key only when you repeat the same scan request.
42
+
43
+ Public report reads need no key. Account access uses an optional bearer key from [your account](https://blockquote.io/account).
44
+ Keys require Pro or Agency. Unattended scan creation can require a paid key with the `scan` scope.
45
+ Human verification still applies where required. Pass `turnstile_token` when available; the SDK does not obtain or bypass verification.
46
+ Pass `refresh=True` to request a fresh scan with account authentication. Scan quotas still apply.
47
+ Read access and comparison output follow your account plan.
48
+
49
+ See the [API reference](https://blockquote.io/api/docs) and [OpenAPI document](https://blockquote.io/api/v1/openapi.json).
50
+
51
+ Run tests from this package directory:
52
+
53
+ ```sh
54
+ python3 -m unittest discover -s tests
55
+ ```
56
+
57
+ ## Command line
58
+
59
+ The package installs the `blockquote` command. `python -m blockquote_agents` runs the same CLI.
60
+
61
+ ```sh
62
+ python -m pip install --upgrade blockquote-agents
63
+ blockquote --help
64
+ blockquote read SCAN_ID
65
+ blockquote scan https://example.com --idempotency-key UNIQUE_REQUEST_ID
66
+ blockquote compare BASELINE_ID NEW_ID
67
+ ```
68
+
69
+ Set `BLOCKQUOTE_API_KEY` for account access. Set `BLOCKQUOTE_TURNSTILE_TOKEN` only when you have a human verification token.
70
+ Use `--refresh` with `scan` to request a fresh scan. Authentication and quota rules remain the same.
71
+ The CLI prints JSON with `data`, `status`, and `headers`. It does not poll or retry.
72
+ HTTP failures print server data, headers, status, and `retryAfter` to stderr with exit code 1.
73
+ Other request failures print only their error type to avoid exposing credentials. Invalid arguments exit with code 2.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ blockquote_agents/__init__.py
5
+ blockquote_agents/__main__.py
6
+ blockquote_agents/cli.py
7
+ blockquote_agents.egg-info/PKG-INFO
8
+ blockquote_agents.egg-info/SOURCES.txt
9
+ blockquote_agents.egg-info/dependency_links.txt
10
+ blockquote_agents.egg-info/entry_points.txt
11
+ blockquote_agents.egg-info/top_level.txt
12
+ tests/test_cli.py
13
+ tests/test_client.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ blockquote = blockquote_agents.cli:main
@@ -0,0 +1 @@
1
+ blockquote_agents
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "blockquote-agents"
7
+ version = "0.1.2"
8
+ description = "Official Blockquote SDK and CLI for blockquote.io: Python API client for AI citability scans and report comparisons."
9
+ keywords = ["blockquote", "blockquote.io", "sdk", "api-client", "cli", "ai-citability"]
10
+ readme = "README.md"
11
+ requires-python = ">=3.10"
12
+ license = {text = "MIT"}
13
+
14
+ [project.scripts]
15
+ blockquote = "blockquote_agents.cli:main"
16
+
17
+ [project.urls]
18
+ Homepage = "https://blockquote.io"
19
+ Repository = "https://github.com/ArneFfm/blockquote-agents"
20
+ Documentation = "https://blockquote.io/developers"
21
+ "Bug Tracker" = "https://github.com/ArneFfm/blockquote-agents/issues"
22
+
23
+ [tool.setuptools.packages.find]
24
+ include = ["blockquote_agents*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,68 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ import unittest
9
+ from unittest.mock import patch
10
+
11
+ from blockquote_agents import BlockquoteError, Response
12
+ from blockquote_agents.cli import main
13
+
14
+
15
+ class CliTest(unittest.TestCase):
16
+ def test_module_help_and_invalid_arguments_are_offline(self):
17
+ for args in ([], ["--help"]):
18
+ result = subprocess.run([sys.executable, "-m", "blockquote_agents", *args],
19
+ cwd=Path(__file__).resolve().parents[1],
20
+ capture_output=True, text=True)
21
+ self.assertEqual(result.returncode, 0)
22
+ self.assertIn("BLOCKQUOTE_API_KEY", result.stdout)
23
+ result = subprocess.run([sys.executable, "-m", "blockquote_agents", "read", "id", "--refresh"],
24
+ cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True)
25
+ self.assertEqual(result.returncode, 2)
26
+
27
+ def test_commands_forward_options_and_preserve_response(self):
28
+ response = Response({"id": "scan-id"}, 202, {"Retry-After": "5"})
29
+ with patch("blockquote_agents.cli.Blockquote") as factory, patch.dict(os.environ, {
30
+ "BLOCKQUOTE_API_KEY": "test-key", "BLOCKQUOTE_TURNSTILE_TOKEN": "test-token"
31
+ }):
32
+ client = factory.return_value
33
+ for args, method in [(["scan", "https://example.com", "--refresh", "--idempotency-key", "key-1"], client.start_scan),
34
+ (["read", "scan-id"], client.get_scan),
35
+ (["compare", "old", "new"], client.compare_scans)]:
36
+ method.return_value = response
37
+ output = io.StringIO()
38
+ with contextlib.redirect_stdout(output):
39
+ self.assertEqual(main(args), 0)
40
+ self.assertEqual(json.loads(output.getvalue()), {
41
+ "data": {"id": "scan-id"}, "status": 202, "headers": {"Retry-After": "5"}
42
+ })
43
+ factory.assert_called_with(api_key="test-key")
44
+ client.start_scan.assert_called_once_with("https://example.com", refresh=True,
45
+ idempotency_key="key-1", turnstile_token="test-token")
46
+ client.get_scan.assert_called_once_with("scan-id")
47
+ client.compare_scans.assert_called_once_with(from_id="old", to_id="new")
48
+
49
+ def test_http_errors_retain_retry_guidance_and_other_errors_hide_secrets(self):
50
+ for error in [BlockquoteError(Response({"error": "quota"}, 429, {"Retry-After": "60"})),
51
+ ValueError("invalid header with secret-test-token")]:
52
+ with patch("blockquote_agents.cli.Blockquote") as factory:
53
+ factory.return_value.get_scan.side_effect = error
54
+ output = io.StringIO()
55
+ with contextlib.redirect_stderr(output):
56
+ self.assertEqual(main(["read", "scan-id"]), 1)
57
+ payload = json.loads(output.getvalue())
58
+ if isinstance(error, BlockquoteError):
59
+ self.assertEqual(payload["status"], 429)
60
+ self.assertEqual(payload["retryAfter"], "60")
61
+ self.assertEqual(payload["data"], {"error": "quota"})
62
+ else:
63
+ self.assertNotIn("secret-test-token", output.getvalue())
64
+ factory.return_value.get_scan.assert_called_once()
65
+
66
+
67
+ if __name__ == "__main__":
68
+ unittest.main()
@@ -0,0 +1,58 @@
1
+ import io
2
+ import json
3
+ import unittest
4
+ from email.message import Message
5
+ from unittest.mock import Mock
6
+ from urllib.error import HTTPError
7
+ from blockquote_agents import Blockquote, BlockquoteError
8
+
9
+
10
+ class Raw(io.BytesIO):
11
+ status = 202
12
+ headers = Message()
13
+ headers["Retry-After"] = "3"
14
+
15
+
16
+ class ClientTest(unittest.TestCase):
17
+ def test_wire_contract(self):
18
+ client = Blockquote(api_key="test-key")
19
+ client._opener = Mock()
20
+ client._opener.open.side_effect = lambda *args, **kwargs: Raw(b'{"id":"scan-id"}')
21
+ result = client.start_scan("https://example.com", refresh=True, idempotency_key="request-1")
22
+ request = client._opener.open.call_args.args[0]
23
+ self.assertEqual(request.full_url, "https://blockquote.io/api/v1/scan")
24
+ self.assertEqual(json.loads(request.data), {"url": "https://example.com", "refresh": True})
25
+ self.assertEqual(request.get_header("Authorization"), "Bearer test-key")
26
+ self.assertEqual(request.get_header("Idempotency-key"), "request-1")
27
+ self.assertEqual(result.headers.get("Retry-After"), "3")
28
+ client.get_scan("a/b")
29
+ self.assertTrue(client._opener.open.call_args.args[0].full_url.endswith("/scan/a%2Fb"))
30
+ client.compare_scans(from_id="a", to_id="b")
31
+ self.assertTrue(client._opener.open.call_args.args[0].full_url.endswith("/compare?from=a&to=b"))
32
+
33
+ def test_http_error_preserves_payload_and_retry(self):
34
+ for body in (b'{"error":"quota"}', b'upstream unavailable'):
35
+ client = Blockquote()
36
+ client._opener = Mock()
37
+ headers = Message()
38
+ headers["Retry-After"] = "60"
39
+ client._opener.open.side_effect = HTTPError("https://blockquote.io", 429, "Limited", headers, io.BytesIO(body))
40
+ with self.assertRaises(BlockquoteError) as caught:
41
+ client.get_scan("id")
42
+ self.assertEqual(caught.exception.status, 429)
43
+ self.assertEqual(caught.exception.retry_after, "60")
44
+ self.assertIn(caught.exception.data, ({"error": "quota"}, "upstream unavailable"))
45
+ self.assertEqual(client._opener.open.call_count, 1)
46
+ self.assertIsNone(client._opener.open.call_args.args[0].get_header("Authorization"))
47
+
48
+ def test_invalid_inputs(self):
49
+ with self.assertRaises(ValueError):
50
+ Blockquote(base_url="http://example.com")
51
+ with self.assertRaises(ValueError):
52
+ Blockquote().get_scan("..")
53
+ with self.assertRaises(ValueError):
54
+ Blockquote().compare_scans(url="example.com", from_id="a")
55
+
56
+
57
+ if __name__ == "__main__":
58
+ unittest.main()