Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/sdk/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ uv add ./packages/sdk/python
from genehub_sdk import GeneHubClient

client = GeneHubClient(base_url="https://registry.genehub.dev", token="ghb_xxx")
genes = client.search_genes(q="code")
genes = client.search_genes("code")
gene = client.get_gene("clean-code")
manifest = client.get_manifest("clean-code", version="1.0.0")
published = client.publish(manifest)
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/python/src/genehub_sdk/adapters/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def install(

gene_yaml = target_dir / "gene.yaml"
gene_yaml.write_text(
yaml.dump(manifest, allow_unicode=True, default_flow_style=False), encoding="utf-8"
yaml.safe_dump(manifest, allow_unicode=True, default_flow_style=False),
encoding="utf-8",
)
files.append(str(gene_yaml))

Expand Down
33 changes: 17 additions & 16 deletions packages/sdk/python/src/genehub_sdk/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""GeneHub Registry HTTP 客户端,与 TypeScript SDK client 对齐。"""

import json
from typing import Any

import httpx
Expand Down Expand Up @@ -37,7 +38,11 @@ def _request(self, method: str, path: str, **kwargs: Any) -> Any:
headers=self._headers(),
**kwargs,
)
data = resp.json()
try:
data = resp.json()
except json.JSONDecodeError:
msg = resp.text or f"HTTP {resp.status_code}"
raise GeneHubError(msg) from None
Comment on lines +41 to +45

Copilot AI Mar 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new json.JSONDecodeError handling path (lines 41–45) is not covered by any test. The existing test file tests/test_client.py has tests for success responses and API error responses, but no test exercises the case where the server returns a non-JSON body (e.g., an HTML 502 page). A test using httpx_mock.add_response(content=b"<html>Bad Gateway</html>", status_code=502) and asserting that GeneHubError is raised would cover this branch.

Copilot uses AI. Check for mistakes.
body = data if isinstance(data, dict) else {}
code = body.get("code", -1)
if not resp.is_success or code != 0:
Expand All @@ -58,24 +63,22 @@ def search_genes(
page_size: int | None = None,
) -> list[Gene]:
"""搜索基因列表。返回当前页的 items;完整分页信息可后续扩展。"""
params: list[tuple[str, str]] = []
params: dict[str, str | int] = {}
if query:
params.append(("q", query))
params["q"] = query
if category:
params.append(("category", category))
params["category"] = category
if tags:
params.append(("tags", ",".join(tags)))
params["tags"] = ",".join(tags)
if compatibility:
params.append(("compatibility", compatibility))
params["compatibility"] = compatibility
if sort:
params.append(("sort", sort))
params["sort"] = sort
if page is not None:
params.append(("page", str(page)))
params["page"] = page
if page_size is not None:
params.append(("page_size", str(page_size)))
qs = "&".join(f"{k}={v}" for k, v in params)
path = f"/api/v1/genes?{qs}" if qs else "/api/v1/genes"
result = self._request("GET", path)
params["page_size"] = page_size
result = self._request("GET", "/api/v1/genes", params=params)
if isinstance(result, dict) and "items" in result:
return result["items"]
return result if isinstance(result, list) else []
Expand All @@ -86,10 +89,8 @@ def get_gene(self, slug: str) -> Gene:

def get_manifest(self, slug: str, version: str | None = None) -> GeneManifest:
"""获取基因 Manifest;可选 version 指定版本。"""
path = f"/api/v1/genes/{slug}/manifest"
if version:
path += f"?version={version}"
return self._request("GET", path)
params = {"version": version} if version else None
return self._request("GET", f"/api/v1/genes/{slug}/manifest", params=params)

def publish(self, manifest: GeneManifest, files: dict[str, str] | None = None) -> Gene:
"""发布新基因。body: { manifest, files? }。"""
Expand Down
5 changes: 2 additions & 3 deletions packages/sdk/python/src/genehub_sdk/learning/engine.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""标准学习协议引擎(最小可用):创建学习任务、检查结果。"""

import re
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -53,9 +54,7 @@ def create_learning_task(self, manifest: GeneManifest) -> dict[str, Any]:
"short_description": manifest.get("short_description") or "",
},
"callback_path": str(self._results_dir / f"{slug}.md"),
"created_at": __import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
"created_at": datetime.now(UTC).isoformat(),
}
if learning:
task["learning"] = {
Expand Down
20 changes: 11 additions & 9 deletions packages/sdk/python/src/genehub_sdk/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""GeneHub 数据类型,与 Registry API 及标准学习协议对齐。"""

from typing import Any, TypedDict
from typing import Any, NotRequired, TypedDict


class Author(TypedDict, total=False):
Expand Down Expand Up @@ -51,23 +51,25 @@ class Learning(TypedDict, total=False):
scenarios: list[LearningScenario]


class GeneManifest(TypedDict, total=False):
class GeneManifest(TypedDict, total=True):
"""基因清单;slug/name/version 等为必填,其余为可选。"""

slug: str
name: str
version: str
description: str
short_description: str
category: str
tags: list[str]
icon: str | None
author: Author | None
compatibility: list[CompatibilityEntry]
dependencies: list[DependencyEntry]
synergies: list[str]
skill: Skill
rules: list[Rule]
config: GeneConfig | None
learning: Learning | None
icon: NotRequired[str | None]
author: NotRequired[Author | None]
dependencies: NotRequired[list[DependencyEntry]]
synergies: NotRequired[list[str]]
rules: NotRequired[list[Rule]]
config: NotRequired[GeneConfig | None]
learning: NotRequired[Learning | None]


class Gene(TypedDict, total=False):
Expand Down
13 changes: 13 additions & 0 deletions packages/sdk/python/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,16 @@ def test_api_error_raises(httpx_mock: pytest.FixtureRequest) -> None:
with pytest.raises(GeneHubError) as exc_info:
client.get_gene("not-found")
assert "gene_not_found" in str(exc_info.value) or "基因" in str(exc_info.value)


def test_non_json_response_raises_genehub_error(httpx_mock: pytest.FixtureRequest) -> None:
"""服务端返回非 JSON(如 502 HTML)时应抛出 GeneHubError。"""
httpx_mock.add_response(
url="https://registry.example.com/api/v1/genes/clean-code",
status_code=502,
content=b"<html>Bad Gateway</html>",
)
client = GeneHubClient(base_url="https://registry.example.com")
with pytest.raises(GeneHubError) as exc_info:
client.get_gene("clean-code")
assert "502" in str(exc_info.value) or "Bad Gateway" in str(exc_info.value)