argoshot 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,16 @@
1
+ # The repository's root .gitignore ignores "argoshot" (the server binary) at any depth; the SDKs' own
2
+ # source directories are named argoshot, so take them back.
3
+ !argoshot
4
+ !argoshot/
5
+ # Build outputs (rebuild them; never commit them)
6
+ */dist/
7
+ rust/target/
8
+ rust/Cargo.lock
9
+ php/vendor/
10
+ php/composer.lock
11
+ php/.phpunit.cache/
12
+ dotnet/**/bin/
13
+ dotnet/**/obj/
14
+ ruby/*.gem
15
+ python/**/__pycache__/
16
+ php/.phpunit.result.cache
argoshot-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RRLabs
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,124 @@
1
+ Metadata-Version: 2.5
2
+ Name: argoshot
3
+ Version: 0.1.0
4
+ Summary: Official client for the Argoshot screenshot API: screenshots, PDFs and signed og:image URLs of any web page or HTML.
5
+ Project-URL: Homepage, https://argoshot.com
6
+ Project-URL: Documentation, https://argoshot.com/docs
7
+ Project-URL: Repository, https://github.com/rrlabs-io/argoshot-python
8
+ Author: Argoshot
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: argoshot,html-to-image,og-image,pdf,screenshot,screenshot-api
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+
22
+ # argoshot
23
+
24
+ The official Python client for [Argoshot](https://argoshot.com), the screenshot API: screenshots, PDFs and signed
25
+ `og:image` URLs of any web page or HTML. **Free to start.** Docs: https://argoshot.com/docs
26
+
27
+ Standard library only (no dependencies), Python 3.8+, typed.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install argoshot
33
+ ```
34
+
35
+ Get your access key (and secret key, for signed URLs) from the dashboard's API keys page.
36
+
37
+ ## Screenshot to a file
38
+
39
+ ```python
40
+ import os
41
+ from argoshot import Argoshot
42
+
43
+ client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"])
44
+
45
+ png = client.take(url="https://example.com", format="png", full_page=True, block_cookie_banners=True)
46
+ with open("example.png", "wb") as f:
47
+ f.write(png)
48
+ ```
49
+
50
+ ## Signed og:image URL
51
+
52
+ `url()` builds a `GET /take` link for `<img src>` or `<meta property="og:image">`. With a secret key it is signed
53
+ (HMAC-SHA256 of the query string), so nobody can change its options. Set the key to **signed requests only** in the
54
+ dashboard before you put its links in public pages.
55
+
56
+ ```python
57
+ client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"], secret_key=os.environ["ARGOSHOT_SECRET_KEY"])
58
+
59
+ og_image = client.url(
60
+ url="https://example.com/blog/my-post",
61
+ viewport_width=1200,
62
+ viewport_height=630,
63
+ format="png",
64
+ cache=True,
65
+ cache_ttl=86400,
66
+ )
67
+ # <meta property="og:image" content="{{ og_image }}">
68
+ ```
69
+
70
+ ## HTML to PNG
71
+
72
+ When `html` (or `markdown`) is given, `take()` sends a JSON `POST` instead of a long query string.
73
+
74
+ ```python
75
+ card = client.take(
76
+ html='<div style="font: 64px system-ui; padding: 80px">Hello from Argoshot</div>',
77
+ format="png",
78
+ viewport_width=1200,
79
+ viewport_height=630,
80
+ )
81
+ with open("card.png", "wb") as f:
82
+ f.write(card)
83
+ ```
84
+
85
+ ## Options
86
+
87
+ Options are the API's own names (https://argoshot.com/docs/options), as keyword arguments or a dict; lists are lists:
88
+ `hide_selectors=[".banner", "#chat"]`. Pass names that are Python keywords in the dict:
89
+ `client.take({"url": "https://example.com", "async": True, "webhook_url": "https://you.example/hook"})`.
90
+ `argoshot.TakeOptions` types the common ones.
91
+
92
+ ## Errors
93
+
94
+ A failed request raises `ArgoshotError` with the API's `code` (e.g. `selector_not_found`, `screenshots_limit_reached`),
95
+ `message`, HTTP `status`, `documentation_url`, and `upgrade_url` / `retry_after` when the API gives them.
96
+ All codes: https://argoshot.com/docs/errors
97
+
98
+ ```python
99
+ from argoshot import ArgoshotError
100
+
101
+ try:
102
+ client.take(url="https://example.com", selector="#missing", error_on_selector_not_found=True)
103
+ except ArgoshotError as e:
104
+ print(e.code, e.message)
105
+ ```
106
+
107
+ ## Usage
108
+
109
+ ```python
110
+ print(client.usage()) # {"total": ..., "available": ..., "used": ..., ...}
111
+ ```
112
+
113
+ ## Configuration
114
+
115
+ ```python
116
+ Argoshot(access_key, secret_key=None, base_url="https://api.argoshot.com", timeout=120.0)
117
+ ```
118
+
119
+ Note: a key set to *signed requests only* cannot send JSON `POST` requests (the API refuses them), so
120
+ `take(html=...)` needs a key that permits unsigned requests.
121
+
122
+ ## Licence
123
+
124
+ MIT
@@ -0,0 +1,103 @@
1
+ # argoshot
2
+
3
+ The official Python client for [Argoshot](https://argoshot.com), the screenshot API: screenshots, PDFs and signed
4
+ `og:image` URLs of any web page or HTML. **Free to start.** Docs: https://argoshot.com/docs
5
+
6
+ Standard library only (no dependencies), Python 3.8+, typed.
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ pip install argoshot
12
+ ```
13
+
14
+ Get your access key (and secret key, for signed URLs) from the dashboard's API keys page.
15
+
16
+ ## Screenshot to a file
17
+
18
+ ```python
19
+ import os
20
+ from argoshot import Argoshot
21
+
22
+ client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"])
23
+
24
+ png = client.take(url="https://example.com", format="png", full_page=True, block_cookie_banners=True)
25
+ with open("example.png", "wb") as f:
26
+ f.write(png)
27
+ ```
28
+
29
+ ## Signed og:image URL
30
+
31
+ `url()` builds a `GET /take` link for `<img src>` or `<meta property="og:image">`. With a secret key it is signed
32
+ (HMAC-SHA256 of the query string), so nobody can change its options. Set the key to **signed requests only** in the
33
+ dashboard before you put its links in public pages.
34
+
35
+ ```python
36
+ client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"], secret_key=os.environ["ARGOSHOT_SECRET_KEY"])
37
+
38
+ og_image = client.url(
39
+ url="https://example.com/blog/my-post",
40
+ viewport_width=1200,
41
+ viewport_height=630,
42
+ format="png",
43
+ cache=True,
44
+ cache_ttl=86400,
45
+ )
46
+ # <meta property="og:image" content="{{ og_image }}">
47
+ ```
48
+
49
+ ## HTML to PNG
50
+
51
+ When `html` (or `markdown`) is given, `take()` sends a JSON `POST` instead of a long query string.
52
+
53
+ ```python
54
+ card = client.take(
55
+ html='<div style="font: 64px system-ui; padding: 80px">Hello from Argoshot</div>',
56
+ format="png",
57
+ viewport_width=1200,
58
+ viewport_height=630,
59
+ )
60
+ with open("card.png", "wb") as f:
61
+ f.write(card)
62
+ ```
63
+
64
+ ## Options
65
+
66
+ Options are the API's own names (https://argoshot.com/docs/options), as keyword arguments or a dict; lists are lists:
67
+ `hide_selectors=[".banner", "#chat"]`. Pass names that are Python keywords in the dict:
68
+ `client.take({"url": "https://example.com", "async": True, "webhook_url": "https://you.example/hook"})`.
69
+ `argoshot.TakeOptions` types the common ones.
70
+
71
+ ## Errors
72
+
73
+ A failed request raises `ArgoshotError` with the API's `code` (e.g. `selector_not_found`, `screenshots_limit_reached`),
74
+ `message`, HTTP `status`, `documentation_url`, and `upgrade_url` / `retry_after` when the API gives them.
75
+ All codes: https://argoshot.com/docs/errors
76
+
77
+ ```python
78
+ from argoshot import ArgoshotError
79
+
80
+ try:
81
+ client.take(url="https://example.com", selector="#missing", error_on_selector_not_found=True)
82
+ except ArgoshotError as e:
83
+ print(e.code, e.message)
84
+ ```
85
+
86
+ ## Usage
87
+
88
+ ```python
89
+ print(client.usage()) # {"total": ..., "available": ..., "used": ..., ...}
90
+ ```
91
+
92
+ ## Configuration
93
+
94
+ ```python
95
+ Argoshot(access_key, secret_key=None, base_url="https://api.argoshot.com", timeout=120.0)
96
+ ```
97
+
98
+ Note: a key set to *signed requests only* cannot send JSON `POST` requests (the API refuses them), so
99
+ `take(html=...)` needs a key that permits unsigned requests.
100
+
101
+ ## Licence
102
+
103
+ MIT
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "argoshot"
7
+ version = "0.1.0"
8
+ description = "Official client for the Argoshot screenshot API: screenshots, PDFs and signed og:image URLs of any web page or HTML."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Argoshot" }]
13
+ requires-python = ">=3.8"
14
+ dependencies = []
15
+ keywords = ["argoshot", "screenshot", "screenshot-api", "html-to-image", "pdf", "og-image"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Internet :: WWW/HTTP",
22
+ "Topic :: Multimedia :: Graphics :: Capture :: Screen Capture",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://argoshot.com"
28
+ Documentation = "https://argoshot.com/docs"
29
+ Repository = "https://github.com/rrlabs-io/argoshot-python"
30
+
31
+ [tool.hatch.build]
32
+ # (the repository's root .gitignore ignores any path named "argoshot": do not let it drop the package)
33
+ ignore-vcs = true
34
+ exclude = ["dist", "**/__pycache__"]
35
+
36
+ [tool.hatch.build.targets.sdist]
37
+ include = ["src/argoshot", "tests", "README.md", "LICENSE", "pyproject.toml"]
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/argoshot"]
@@ -0,0 +1,24 @@
1
+ """Argoshot: a small client for the Argoshot screenshot API (https://argoshot.com/docs). Standard library only."""
2
+
3
+ from ._client import (
4
+ DEFAULT_BASE_URL,
5
+ Argoshot,
6
+ ArgoshotError,
7
+ TakeOptions,
8
+ build_query,
9
+ parse_error,
10
+ sign,
11
+ )
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "DEFAULT_BASE_URL",
17
+ "Argoshot",
18
+ "ArgoshotError",
19
+ "TakeOptions",
20
+ "build_query",
21
+ "parse_error",
22
+ "sign",
23
+ "__version__",
24
+ ]
@@ -0,0 +1,204 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict, Union
10
+
11
+ DEFAULT_BASE_URL = "https://api.argoshot.com"
12
+ _VERSION = "0.1.0"
13
+ _CLIENT_OWN = ("access_key", "signature")
14
+
15
+ OptionValue = Union[str, int, float, bool, None, Sequence[Union[str, int, float, bool]]]
16
+
17
+
18
+ class TakeOptions(TypedDict, total=False):
19
+ """The common options, typed. Any other option of https://argoshot.com/docs/options is accepted by name."""
20
+
21
+ url: str
22
+ html: str
23
+ markdown: str
24
+ format: str
25
+ viewport_width: int
26
+ viewport_height: int
27
+ viewport_device: str
28
+ device_scale_factor: float
29
+ full_page: bool
30
+ block_cookie_banners: bool
31
+ block_ads: bool
32
+ dark_mode: bool
33
+ selector: str
34
+ cache: bool
35
+ cache_ttl: int
36
+ image_quality: int
37
+ delay: int
38
+ timeout: int
39
+ wait_until: List[str]
40
+ hide_selectors: List[str]
41
+ response_type: str
42
+ webhook_url: str
43
+
44
+
45
+ class ArgoshotError(Exception):
46
+ """An error the API answered (its error_code and error_message), or a response that was not the API's."""
47
+
48
+ def __init__(
49
+ self,
50
+ code: str,
51
+ message: str,
52
+ status: int = 0,
53
+ documentation_url: Optional[str] = None,
54
+ upgrade_url: Optional[str] = None,
55
+ returned_status_code: Optional[int] = None,
56
+ matched_string: Optional[str] = None,
57
+ retry_after: Optional[int] = None,
58
+ body: Optional[str] = None,
59
+ ) -> None:
60
+ super().__init__(message)
61
+ self.code = code
62
+ self.message = message
63
+ self.status = status
64
+ self.documentation_url = documentation_url
65
+ self.upgrade_url = upgrade_url
66
+ self.returned_status_code = returned_status_code
67
+ self.matched_string = matched_string
68
+ self.retry_after = retry_after
69
+ self.body = body
70
+
71
+ def __str__(self) -> str:
72
+ return f"{self.code}: {self.message}"
73
+
74
+
75
+ class Argoshot:
76
+ """A client for the Argoshot API.
77
+
78
+ >>> client = Argoshot("ACCESS_KEY", secret_key="SECRET_KEY")
79
+ >>> png = client.take(url="https://example.com", format="png")
80
+ >>> og_image = client.url(url="https://example.com", viewport_width=1200, viewport_height=630)
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ access_key: str,
86
+ secret_key: Optional[str] = None,
87
+ base_url: str = DEFAULT_BASE_URL,
88
+ timeout: float = 120.0,
89
+ ) -> None:
90
+ if not access_key:
91
+ raise ValueError("Argoshot: an access key is required")
92
+ self.access_key = access_key
93
+ self.secret_key = secret_key or None
94
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
95
+ self.timeout = timeout
96
+
97
+ def url(self, options: Optional[Mapping[str, OptionValue]] = None, /, **kwargs: OptionValue) -> str:
98
+ """A GET /take URL for these options (for <img src> or og:image), signed when a secret key is set.
99
+
100
+ The access key is in the URL: for public pages, use a key set to "signed requests only".
101
+ """
102
+ query = build_query(_merge(options, kwargs))
103
+ unsigned = (query + "&" if query else "") + "access_key=" + _encode(self.access_key)
104
+ if self.secret_key:
105
+ unsigned += "&signature=" + sign(self.secret_key, unsigned)
106
+ return self.base_url + "/take?" + unsigned
107
+
108
+ def take(self, options: Optional[Mapping[str, OptionValue]] = None, /, **kwargs: OptionValue) -> bytes:
109
+ """Render and return the file's bytes. Raises ArgoshotError on failure.
110
+
111
+ GET for url captures (signed when a secret key is set); a JSON POST when html or markdown is given.
112
+ Options are the API's names; pass ones that are Python keywords (async) in the dict.
113
+ """
114
+ opts = _clean(_merge(options, kwargs))
115
+ headers = {"X-Access-Key": self.access_key, "User-Agent": "argoshot-python/" + _VERSION}
116
+ if "html" in opts or "markdown" in opts:
117
+ headers["Content-Type"] = "application/json"
118
+ body = json.dumps(opts).encode("utf-8")
119
+ request = urllib.request.Request(self.base_url + "/take", data=body, headers=headers, method="POST")
120
+ else:
121
+ query = build_query(opts)
122
+ if self.secret_key:
123
+ query += "&signature=" + sign(self.secret_key, query)
124
+ request = urllib.request.Request(self.base_url + "/take?" + query, headers=headers, method="GET")
125
+ return self._send(request)
126
+
127
+ def usage(self) -> Dict[str, Any]:
128
+ """GET /usage: renders total, available and used, and the plan's limits. Costs nothing."""
129
+ headers = {"X-Access-Key": self.access_key, "User-Agent": "argoshot-python/" + _VERSION}
130
+ request = urllib.request.Request(self.base_url + "/usage", headers=headers, method="GET")
131
+ return json.loads(self._send(request).decode("utf-8"))
132
+
133
+ def _send(self, request: urllib.request.Request) -> bytes:
134
+ try:
135
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
136
+ return response.read()
137
+ except urllib.error.HTTPError as e:
138
+ body = e.read().decode("utf-8", errors="replace")
139
+ raise parse_error(e.code, body, e.headers.get("Retry-After") if e.headers else None) from None
140
+
141
+
142
+ def parse_error(status: int, body: str, retry_after: Optional[str] = None) -> ArgoshotError:
143
+ """An ArgoshotError from an error response's status and body."""
144
+ retry: Optional[int] = None
145
+ if retry_after and str(retry_after).strip().isdigit():
146
+ retry = int(retry_after)
147
+ try:
148
+ data = json.loads(body)
149
+ except (ValueError, TypeError):
150
+ data = None
151
+ if isinstance(data, dict) and isinstance(data.get("error_code"), str):
152
+ return ArgoshotError(
153
+ code=data["error_code"],
154
+ message=data.get("error_message") or data["error_code"],
155
+ status=status,
156
+ documentation_url=data.get("documentation_url"),
157
+ upgrade_url=data.get("upgrade_url"),
158
+ returned_status_code=data.get("returned_status_code"),
159
+ matched_string=data.get("matched_string"),
160
+ retry_after=retry,
161
+ body=body,
162
+ )
163
+ snippet = (body or "")[:200]
164
+ return ArgoshotError("http_error", f"HTTP {status}" + (f": {snippet}" if snippet else ""), status, retry_after=retry, body=body)
165
+
166
+
167
+ def build_query(options: Optional[Mapping[str, OptionValue]]) -> str:
168
+ """The query string of these options: names sorted, lists repeated, None left out (no access key)."""
169
+ opts = _clean(options)
170
+ parts = []
171
+ for name in sorted(opts):
172
+ value = opts[name]
173
+ values = value if isinstance(value, (list, tuple)) else [value]
174
+ for v in values:
175
+ if v is None:
176
+ continue
177
+ parts.append(_encode(name) + "=" + _encode(_text(v)))
178
+ return "&".join(parts)
179
+
180
+
181
+ def sign(secret_key: str, query: str) -> str:
182
+ """The signature the API checks: lowercase hex HMAC-SHA256 of the query string, under the secret key."""
183
+ return hmac.new(secret_key.encode("utf-8"), query.encode("utf-8"), hashlib.sha256).hexdigest()
184
+
185
+
186
+ def _merge(options: Optional[Mapping[str, OptionValue]], kwargs: Mapping[str, OptionValue]) -> Dict[str, OptionValue]:
187
+ merged: Dict[str, OptionValue] = dict(options or {})
188
+ merged.update(kwargs)
189
+ return merged
190
+
191
+
192
+ def _clean(options: Optional[Mapping[str, OptionValue]]) -> Dict[str, OptionValue]:
193
+ return {k: v for k, v in (options or {}).items() if v is not None and k not in _CLIENT_OWN}
194
+
195
+
196
+ def _text(v: Any) -> str:
197
+ if isinstance(v, bool):
198
+ return "true" if v else "false"
199
+ return str(v)
200
+
201
+
202
+ def _encode(s: str) -> str:
203
+ # RFC 3986: everything but A-Z a-z 0-9 - . _ ~ is percent-encoded (a space is %20, a + is %2B).
204
+ return urllib.parse.quote(s, safe="-._~")
File without changes
@@ -0,0 +1,139 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import unittest
5
+ import urllib.error
6
+ import urllib.request
7
+ from email.message import Message
8
+ from unittest import mock
9
+
10
+ from argoshot import Argoshot, ArgoshotError, build_query, parse_error, sign
11
+
12
+
13
+ class SignatureTest(unittest.TestCase):
14
+ def test_server_vector(self):
15
+ # The server's own test (jai-web-framework framework/Screenshots/tests/privacy/app.jai:194):
16
+ # hmac_sha256("secret-of-the-customer-1234", "html=x&access_key=key-<tenant>"), lowercase hex.
17
+ client = Argoshot("key-2", secret_key="secret-of-the-customer-1234")
18
+ self.assertEqual(
19
+ client.url(html="x"),
20
+ "https://api.argoshot.com/take?html=x&access_key=key-2&signature=9488e5f178e81282b921f410775de15b0767f894504cd18bd66f35616d60ffd1",
21
+ )
22
+
23
+ def test_sorted_encoded_lists_numbers_booleans(self):
24
+ client = Argoshot("AK_test", secret_key="SK_test")
25
+ url = client.url(
26
+ {
27
+ "url": "https://example.com/a b?x=1&y=2",
28
+ "format": "png",
29
+ "full_page": True,
30
+ "viewport_width": 1280,
31
+ "device_scale_factor": 1.5,
32
+ "hide_selectors": [".a", "#b .c"],
33
+ }
34
+ )
35
+ self.assertEqual(
36
+ url,
37
+ "https://api.argoshot.com/take?device_scale_factor=1.5&format=png&full_page=true&hide_selectors=.a&hide_selectors=%23b%20.c&url=https%3A%2F%2Fexample.com%2Fa%20b%3Fx%3D1%26y%3D2&viewport_width=1280&access_key=AK_test&signature=1a6f9d69eae82c57575f031ba76325705f5c0ddc6b48380a6fa7964c8a497b1c",
38
+ )
39
+
40
+ def test_non_ascii_html(self):
41
+ client = Argoshot("AK_test", secret_key="SK_test")
42
+ self.assertEqual(
43
+ client.url(html="<h1>Hi — café + &</h1>", format="png"),
44
+ "https://api.argoshot.com/take?format=png&html=%3Ch1%3EHi%20%E2%80%94%20caf%C3%A9%20%2B%20%26%3C%2Fh1%3E&access_key=AK_test&signature=a1fb4eea53e2c394dce7ab32e31a26a2c8c85b8ebc53ac330ddb0cc441ee9eb7",
45
+ )
46
+
47
+ def test_unsigned_custom_base_none_skipped(self):
48
+ client = Argoshot("AK_test", base_url="http://localhost:8080/")
49
+ self.assertEqual(
50
+ client.url(url="https://example.com", format="png", selector=None, access_key="other", signature="x"),
51
+ "http://localhost:8080/take?format=png&url=https%3A%2F%2Fexample.com&access_key=AK_test",
52
+ )
53
+
54
+ def test_reserved_characters(self):
55
+ self.assertEqual(build_query({"styles": "a{content:'!()*'}"}), "styles=a%7Bcontent%3A%27%21%28%29%2A%27%7D")
56
+
57
+ def test_sign(self):
58
+ self.assertEqual(sign("secret-of-the-customer-1234", "html=x&access_key=key-2"), "9488e5f178e81282b921f410775de15b0767f894504cd18bd66f35616d60ffd1")
59
+
60
+
61
+ class ErrorTest(unittest.TestCase):
62
+ def test_api_error(self):
63
+ body = json.dumps(
64
+ {
65
+ "is_successful": False,
66
+ "error_code": "selector_not_found",
67
+ "error_message": "Nothing matches the selector: #hero",
68
+ "documentation_url": "https://argoshot.com/docs/errors/selector-not-found/",
69
+ }
70
+ )
71
+ e = parse_error(400, body)
72
+ self.assertEqual(e.code, "selector_not_found")
73
+ self.assertEqual(e.message, "Nothing matches the selector: #hero")
74
+ self.assertEqual(e.status, 400)
75
+ self.assertEqual(e.documentation_url, "https://argoshot.com/docs/errors/selector-not-found/")
76
+
77
+ def test_upgrade_retry_and_not_json(self):
78
+ e = parse_error(402, '{"is_successful":false,"error_code":"free_tier_exhausted","error_message":"Used.","upgrade_url":"https://argoshot.com/pricing"}', "5")
79
+ self.assertEqual(e.code, "free_tier_exhausted")
80
+ self.assertEqual(e.upgrade_url, "https://argoshot.com/pricing")
81
+ self.assertEqual(e.retry_after, 5)
82
+ bad = parse_error(502, "<html>Bad gateway</html>")
83
+ self.assertEqual(bad.code, "http_error")
84
+ self.assertEqual(bad.status, 502)
85
+ self.assertIn("HTTP 502", bad.message)
86
+
87
+
88
+ class FakeResponse(io.BytesIO):
89
+ def __enter__(self):
90
+ return self
91
+
92
+ def __exit__(self, *a):
93
+ return False
94
+
95
+
96
+ class TakeTest(unittest.TestCase):
97
+ def test_get_signed_with_header(self):
98
+ client = Argoshot("AK_test", secret_key="SK_test")
99
+ with mock.patch("urllib.request.urlopen", return_value=FakeResponse(b"\x89PNG")) as urlopen:
100
+ self.assertEqual(client.take(url="https://example.com", format="png"), b"\x89PNG")
101
+ request = urlopen.call_args[0][0]
102
+ query = "format=png&url=https%3A%2F%2Fexample.com"
103
+ self.assertEqual(request.full_url, f"https://api.argoshot.com/take?{query}&signature={sign('SK_test', query)}")
104
+ self.assertEqual(request.get_method(), "GET")
105
+ self.assertEqual(request.get_header("X-access-key"), "AK_test")
106
+
107
+ def test_post_json_for_html(self):
108
+ client = Argoshot("AK_test")
109
+ with mock.patch("urllib.request.urlopen", return_value=FakeResponse(b"ok")) as urlopen:
110
+ client.take({"html": "<h1>Hi</h1>", "format": "png", "async": False, "hide_selectors": [".x"]})
111
+ request = urlopen.call_args[0][0]
112
+ self.assertEqual(request.full_url, "https://api.argoshot.com/take")
113
+ self.assertEqual(request.get_method(), "POST")
114
+ self.assertEqual(request.get_header("Content-type"), "application/json")
115
+ self.assertEqual(json.loads(request.data), {"html": "<h1>Hi</h1>", "format": "png", "async": False, "hide_selectors": [".x"]})
116
+
117
+ def test_error_raises(self):
118
+ client = Argoshot("bad")
119
+ headers = Message()
120
+ err = urllib.error.HTTPError(
121
+ "https://api.argoshot.com/take", 400, "Bad Request", headers,
122
+ io.BytesIO(b'{"is_successful":false,"error_code":"access_key_invalid","error_message":"No such access key."}'),
123
+ )
124
+ with mock.patch("urllib.request.urlopen", side_effect=err):
125
+ with self.assertRaises(ArgoshotError) as caught:
126
+ client.take(url="https://example.com")
127
+ self.assertEqual(caught.exception.code, "access_key_invalid")
128
+ self.assertEqual(caught.exception.status, 400)
129
+
130
+
131
+ @unittest.skipUnless(os.environ.get("ARGOSHOT_KEY"), "set ARGOSHOT_KEY to run the live test")
132
+ class LiveTest(unittest.TestCase):
133
+ def test_png(self):
134
+ client = Argoshot(os.environ["ARGOSHOT_KEY"], secret_key=os.environ.get("ARGOSHOT_SECRET"))
135
+ self.assertEqual(client.take(url="https://example.com", format="png")[:4], b"\x89PNG")
136
+
137
+
138
+ if __name__ == "__main__":
139
+ unittest.main()