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
12 changes: 5 additions & 7 deletions src/wop_sdk/config/_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _read_packaged(resource: str) -> str:
resource_name = resource.split("/", 1)[-1] if "/" in resource else resource
try:
data = resources.files(package).joinpath(resource_name).read_text(encoding="utf-8")
except (FileNotFoundError, OSError, TypeError) as exc:
except (OSError, TypeError) as exc:
raise ConfigurationError(f"打包资源不存在: {resource}") from exc
return data

Expand All @@ -87,11 +87,9 @@ def _discover() -> tuple[str, Callable[[], str]]:
"""§4.2 六来源发现顺序。"""
explicit = os.environ.get(CONFIG_FILE_OVERRIDE_ENV, "").strip()
if explicit:
path = Path(explicit)
return _file_discovery(path, explicit=True)
return _file_discovery(Path(explicit), explicit=True)

env = os.environ.get(CONFIG_FILE_ENV, "").strip()
if env:
if env := os.environ.get(CONFIG_FILE_ENV, "").strip():
path = Path(env)
return _file_discovery(path, explicit=True)

Expand All @@ -108,12 +106,12 @@ def _discover() -> tuple[str, Callable[[], str]]:
packaged = PACKAGED_CONFIG.rsplit("/", 1)[-1]
try:
resources.files("wop_sdk.config").joinpath(packaged).read_bytes()
except (FileNotFoundError, OSError, TypeError):
except (OSError, TypeError) as exc:
expanded = ", ".join(str(item) for item in candidates)
raise ConfigurationError(
"未找到可读配置文件,已尝试: "
f"WOP_SDK_CONFIG_FILE, {CONFIG_FILE_ENV}, {expanded}, 打包资源 {PACKAGED_CONFIG}"
)
) from exc
cache_key = f"pkg:{PACKAGED_CONFIG}"
return cache_key, lambda: _read_packaged(PACKAGED_CONFIG)

Expand Down
2 changes: 1 addition & 1 deletion src/wop_sdk/config/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(self) -> None:
self._merchant_private_key: Optional[str] = None
self._platform_public_key: Optional[str] = None
self._server_root: Optional[str] = None
self._backup_server_roots: Tuple[str, ...] = tuple()
self._backup_server_roots: Tuple[str, ...] = ()
self._expired_seconds: int = DEFAULT_EXPIRED_SECONDS
self._http_client: HttpClientSettings = HttpClientSettings()
self._transport: Optional["Transport"] = None
Expand Down
10 changes: 2 additions & 8 deletions src/wop_sdk/config/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ def _duplicate_key_hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:


def _strip_bom(text: str) -> str:
if text.startswith("\ufeff"):
return text[1:]
return text
return text[1:] if text.startswith("\ufeff") else text


def parse_config_json(text: str) -> WopSdkConfig:
Expand All @@ -73,11 +71,7 @@ def parse_config_json(text: str) -> WopSdkConfig:


def _bind_root(root: Mapping[str, Any]) -> WopSdkConfig:
unknown = set(root.keys()) - _ALLOWED_TOP_LEVEL
if unknown:
# 未知字段忽略:仅处理已知键
pass

# 未知字段忽略:仅处理已知键
app_key = _require_string(root.get("appKey"), "appKey", required=False)
suite = _require_string(root.get("suite"), "suite", required=False)
merchant_private_key = _require_string(
Expand Down
2 changes: 1 addition & 1 deletion src/wop_sdk/config/_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def validate_gateway_url(value: str, field_name: str) -> str:

def validate_api_path(path: str) -> None:
"""§7.7 API path 语法校验。"""
if path is None or path == "":
if path is None or not path:
raise ConfigurationError("请求路径为空")
if not path.startswith("/"):
raise ConfigurationError(f"path 须以 / 开头: {path}")
Expand Down
7 changes: 2 additions & 5 deletions src/wop_sdk/transport_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ def discover_transport() -> Transport:
available = _available_transports()
if not available:
raise ConfigurationError("未找到可用 HTTP 传输,请确认 wop-python-sdk 安装完整")
explicit = os.environ.get(_TRANSPORT_ENV, "").strip().lower()
if explicit:
if explicit := os.environ.get(_TRANSPORT_ENV, "").strip().lower():
transport = available.get(explicit)
if transport is None:
names = ", ".join(sorted(available))
Expand Down Expand Up @@ -47,7 +46,5 @@ def _available_transports() -> Dict[str, type]:
from .transports.requests_transport import RequestsTransport

found["requests"] = RequestsTransport
# P0:仅 urllib 时不视为「多个」——过滤后若显式 env 未设且仅 urllib,直接返回
if set(found.keys()) == {"urllib"}:
return found
# P0:仅 urllib 时不视为「多个」——显式 env 未设且仅 urllib 时直接返回
return found
6 changes: 3 additions & 3 deletions src/wop_sdk/transports/urllib_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
def _urllib_chunks(resp) -> Iterator[bytes]:
"""resp.read(n) 循环取块,直至 EOF;配合 read_capped 流式限量。"""
while True:
chunk = resp.read(_READ_CHUNK)
if not chunk:
if chunk := resp.read(_READ_CHUNK):
yield chunk
else:
break
yield chunk


class UrllibTransport:
Expand Down
27 changes: 27 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""测试共享 helper(独立模块:test 模块间禁止互相 import,Sourcery dont-import-test-modules)。"""
import json
from pathlib import Path

RSA_REQ = "WOP-RSA3072-SHA256"


def _valid_config_dict(vec_keys) -> dict:
return {
"appKey": "app_10012481831",
"suite": RSA_REQ,
"merchantPrivateKey": vec_keys["rsa3072"]["privatePkcs8B64"],
"platformPublicKey": vec_keys["rsa3072"]["publicSpkiB64"],
"serverRoot": "https://gw.example.com/gateway",
"backupServerRoots": ["https://gw-backup.example.com/gateway"],
"expiredSeconds": 1800,
"httpClient": {
"connectTimeout": 10000,
"readTimeout": 30000,
"maxRetryCount": 3,
},
}


def _write_config(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
24 changes: 2 additions & 22 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,11 @@
from wop_sdk.config._validator import join_url, validate_api_path, validate_gateway_url
from wop_sdk.errors import ConfigurationError, WopGatewayResponseError
from wop_sdk.transports import HttpResponse
from helpers import RSA_REQ, _valid_config_dict, _write_config

RSA_REQ = "WOP-RSA3072-SHA256"
PATH = "/gateway/order/create"

PATH = "/gateway/order/create"

def _valid_config_dict(vec_keys) -> dict:
return {
"appKey": "app_10012481831",
"suite": RSA_REQ,
"merchantPrivateKey": vec_keys["rsa3072"]["privatePkcs8B64"],
"platformPublicKey": vec_keys["rsa3072"]["publicSpkiB64"],
"serverRoot": "https://gw.example.com/gateway",
"backupServerRoots": ["https://gw-backup.example.com/gateway"],
"expiredSeconds": 1800,
"httpClient": {
"connectTimeout": 10000,
"readTimeout": 30000,
"maxRetryCount": 3,
},
}


def _write_config(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")


@pytest.fixture
Expand Down
2 changes: 1 addition & 1 deletion tests/test_config_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from wop_sdk.config._parser import parse_config_json
from wop_sdk.config._validator import validate_api_path, validate_gateway_url
from wop_sdk.errors import ConfigurationError
from test_config import _valid_config_dict, _write_config
from helpers import _valid_config_dict, _write_config


def _raw(vec_keys, **overrides):
Expand Down
Loading