Skip to content

Commit 3bc92ce

Browse files
ci: add mypy strict type checking
Add mypy and types-requests to dev dependencies with a strict config, run it in the lint job, and add the mypy badge to README. Fix the eight no-any-return errors in both clients: validate that the API response is a JSON object, coerce taskId/balance to int/float, and check that a ready task carries a solution object. Behaviour is unchanged for well-formed responses; malformed ones now raise NetworkError instead of failing later. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent e446148 commit 3bc92ce

5 files changed

Lines changed: 32 additions & 8 deletions

File tree

‎.github/workflows/tests.yml‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ on:
99
workflow_call:
1010

1111
jobs:
12-
# Static checks: ruff lint + formatting. Runs once on a single Python
13-
# version since the result does not depend on the interpreter.
12+
# Static checks: ruff lint + formatting and mypy type checking. Runs once
13+
# on a single Python version since the result does not depend on the
14+
# interpreter.
1415
lint:
1516
runs-on: ubuntu-latest
1617
steps:
@@ -30,6 +31,9 @@ jobs:
3031
- name: Ruff format check
3132
run: ruff format --check .
3233

34+
- name: mypy
35+
run: mypy captcha_solver_api
36+
3337
# Test suite across all supported Python versions, plus a build check
3438
# to catch packaging errors early. Skipped if lint fails to save CI minutes.
3539
test:

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
[![Typed](https://img.shields.io/badge/typing-typed-blue)](https://github.com/captcha-solver-api/python-sdk/blob/main/captcha_solver_api/py.typed)
1010
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/captcha-solver-api/python-sdk/blob/main/LICENSE.md)
1111
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
12+
[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
1213
[![JavaScript SDK](https://img.shields.io/badge/also_available-JavaScript_SDK-f7df1e?logo=javascript&logoColor=black)](https://github.com/captcha-solver-api/javascript-sdk)
1314

1415
Official Python SDK for the Captcha Solver API. Solve reCAPTCHA v2/v3, Cloudflare Turnstile, GeeTest, Yandex SmartCaptcha, Tencent, and image/click captchas with a single method call -- sync or async.

‎captcha_solver_api/async_client.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ async def _request(
113113
except ValueError as exc:
114114
raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc
115115

116+
if not isinstance(data, dict):
117+
raise NetworkError(f"Unexpected API response shape: {type(data).__name__}")
116118
return data
117119

118120
def _ensure_success(self, data: Dict[str, Any]) -> None:
@@ -154,7 +156,7 @@ async def create_task(self, task: Any, language_pool: Optional[str] = None) -> i
154156

155157
data = await self._request("createTask", payload)
156158
self._ensure_success(data)
157-
return data["taskId"]
159+
return int(data["taskId"])
158160

159161
async def get_task_result(self, task_id: int) -> Dict[str, Any]:
160162
"""Fetch the current status of a previously submitted task.
@@ -203,7 +205,7 @@ async def get_balance(self) -> float:
203205
payload = {"clientKey": self.client_key}
204206
data = await self._request("getBalance", payload)
205207
self._ensure_success(data)
206-
return data["balance"]
208+
return float(data["balance"])
207209

208210
async def solve(
209211
self,
@@ -248,6 +250,9 @@ async def solve(
248250
result = await self.get_task_result(task_id)
249251

250252
if result.get("status") == "ready":
251-
return result["solution"]
253+
solution = result["solution"]
254+
if not isinstance(solution, dict):
255+
raise NetworkError("API returned a ready task without a solution object")
256+
return solution
252257

253258
raise CaptchaTimeoutError("Task solving timed out.")

‎captcha_solver_api/client.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ def _request(
102102
except ValueError as exc:
103103
raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc
104104

105+
if not isinstance(data, dict):
106+
raise NetworkError(f"Unexpected API response shape: {type(data).__name__}")
105107
return data
106108

107109
def _ensure_success(self, data: Dict[str, Any]) -> None:
@@ -141,7 +143,7 @@ def create_task(self, task: Any, language_pool: Optional[str] = None) -> int:
141143

142144
data = self._request("createTask", payload)
143145
self._ensure_success(data)
144-
return data["taskId"]
146+
return int(data["taskId"])
145147

146148
def get_task_result(self, task_id: int) -> Dict[str, Any]:
147149
"""Fetches the current status of a task created with `create_task()`.
@@ -187,7 +189,7 @@ def get_balance(self) -> float:
187189
payload = {"clientKey": self.client_key}
188190
data = self._request("getBalance", payload)
189191
self._ensure_success(data)
190-
return data["balance"]
192+
return float(data["balance"])
191193

192194
def solve(
193195
self,
@@ -230,6 +232,9 @@ def solve(
230232
result = self.get_task_result(task_id)
231233

232234
if result.get("status") == "ready":
233-
return result["solution"]
235+
solution = result["solution"]
236+
if not isinstance(solution, dict):
237+
raise NetworkError("API returned a ready task without a solution object")
238+
return solution
234239

235240
raise CaptchaTimeoutError("Task solving timed out.")

‎pyproject.toml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ dev = [
4646
"pytest-mock>=3",
4747
"python-dotenv>=1.0",
4848
"ruff>=0.6",
49+
"mypy>=1.10",
50+
"types-requests>=2.28",
4951
]
5052

5153
[project.urls]
@@ -65,6 +67,13 @@ captcha_solver_api = ["py.typed"]
6567
[tool.pytest.ini_options]
6668
asyncio_mode = "auto"
6769

70+
[tool.mypy]
71+
# mypy 2.x cannot target 3.9; 3.10 is the lowest it accepts. Runtime
72+
# compatibility with 3.9 is still covered by the CI test matrix.
73+
python_version = "3.10"
74+
strict = true
75+
files = ["captcha_solver_api"]
76+
6877
[tool.ruff]
6978
target-version = "py39"
7079
line-length = 100

0 commit comments

Comments
 (0)