From c1626bbbfeceebbc5fac687bfbe25e5d751371f5 Mon Sep 17 00:00:00 2001 From: HibiKier <775757368@qq.com> Date: Thu, 3 Jul 2025 17:35:43 +0800 Subject: [PATCH] =?UTF-8?q?:bug:=20=E6=B5=8B=E8=AF=95=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/conftest.py | 1 + zhenxun/utils/http_utils.py | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 0fce1583..d6a7e9fa 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -116,6 +116,7 @@ async def app(app: App, tmp_path: Path, mocker: MockerFixture): await init() # await driver._lifespan.startup() os.environ["AIOCACHE_DISABLE"] = "1" + os.environ["PYTEST_CURRENT_TEST"] = "1" yield app diff --git a/zhenxun/utils/http_utils.py b/zhenxun/utils/http_utils.py index f99c7fc1..9f00e9af 100644 --- a/zhenxun/utils/http_utils.py +++ b/zhenxun/utils/http_utils.py @@ -1,6 +1,7 @@ import asyncio from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence from contextlib import asynccontextmanager +import os from pathlib import Path import time from typing import Any, ClassVar, cast @@ -33,7 +34,7 @@ driver = nonebot.get_driver() _client: AsyncClient | None = None -@PriorityLifecycle.on_startup(priority=5) +@PriorityLifecycle.on_startup(priority=0) async def _(): """ 在Bot启动时初始化全局httpx客户端。 @@ -83,8 +84,16 @@ def get_client() -> AsyncClient: """ 获取全局 httpx.AsyncClient 实例。 """ + global _client if not _client: - raise RuntimeError("全局 httpx.AsyncClient 未初始化,请检查启动流程。") + if not os.environ.get("PYTEST_CURRENT_TEST"): + raise RuntimeError("全局 httpx.AsyncClient 未初始化,请检查启动流程。") + # 在测试环境中创建临时客户端 + logger.warning("在测试环境中创建临时HTTP客户端", "HTTPClient") + _client = httpx.AsyncClient( + headers=get_user_agent(), + follow_redirects=True, + ) return _client