⬆️ 升级至 NoneBug 0.3

* 🚧 第一次尝试 50/82

* 62/82 调整了清除数据库的位置

* 🚧 pytest-mock

* 🚧 fix test_send

* 🚧 intruduce app request

* 🚧 close and remove tinydb after each test

* 🚧 clean ScheduleTimeWeight table

* 🚧 reload http module to test proxy

*  合并 main 的代码

* 🚧 在每次测试结束后关闭browser

* 🧑‍💻 在mcbbsnews渲染异常时添加logger

---------

Co-authored-by: hemengyang <hmy0119@gmail.com>
Co-authored-by: Azide <rukuy@qq.com>
This commit is contained in:
felinae98
2023-03-03 15:12:25 +08:00
committed by GitHub
parent bc521cd38a
commit 0201d5b316
13 changed files with 258 additions and 171 deletions
+6 -1
View File
@@ -1,4 +1,5 @@
import typing
from pathlib import Path
import pytest
from nonebug.app import App
@@ -16,7 +17,11 @@ def config_legacy(app: App, use_legacy_config):
from nonebot_bison.config import config_legacy as config
config.start_up()
return config.Config()
yield config.Config()
config.Config().db.close()
legacy_config = Path(config.get_config_path()[0])
legacy_config.unlink(missing_ok=True)
def test_create_and_get(config_legacy: "Config", app: App):
+6 -5
View File
@@ -1,9 +1,10 @@
from datetime import time
from nonebug import App
from pytest_mock import MockerFixture
async def test_create_config(app: App, init_scheduler):
async def test_create_config(init_scheduler):
from nonebot_bison.config.db_config import TimeWeightConfig, WeightConfig, config
from nonebot_bison.config.db_model import Subscribe, Target, User
from nonebot_bison.types import Target as T_Target
@@ -52,7 +53,7 @@ async def test_create_config(app: App, init_scheduler):
assert test_config1.time_config == []
async def test_get_current_weight(app: App, init_scheduler):
async def test_get_current_weight(init_scheduler, mocker: MockerFixture):
from datetime import time
from nonebot_bison.config import db_config
@@ -99,19 +100,19 @@ async def test_get_current_weight(app: App, init_scheduler):
],
),
)
app.monkeypatch.setattr(db_config, "_get_time", lambda: time(1, 30))
mocker.patch.object(db_config, "_get_time", return_value=time(1, 30))
weight = await config.get_current_weight_val(["weibo", "bilibili"])
assert len(weight) == 3
assert weight["weibo-weibo_id"] == 20
assert weight["weibo-weibo_id1"] == 10
assert weight["bilibili-weibo_id1"] == 10
app.monkeypatch.setattr(db_config, "_get_time", lambda: time(4, 0))
mocker.patch.object(db_config, "_get_time", return_value=time(4, 0))
weight = await config.get_current_weight_val(["weibo", "bilibili"])
assert len(weight) == 3
assert weight["weibo-weibo_id"] == 30
assert weight["weibo-weibo_id1"] == 10
assert weight["bilibili-weibo_id1"] == 10
app.monkeypatch.setattr(db_config, "_get_time", lambda: time(5, 0))
mocker.patch.object(db_config, "_get_time", return_value=time(5, 0))
weight = await config.get_current_weight_val(["weibo", "bilibili"])
assert len(weight) == 3
assert weight["weibo-weibo_id"] == 10
+56 -32
View File
@@ -1,29 +1,67 @@
import asyncio
import typing
import sys
from pathlib import Path
import nonebot
import pytest
from nonebug.app import App
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import delete
from nonebug import NONEBOT_INIT_KWARGS, App
from pytest_mock.plugin import MockerFixture
from sqlalchemy import delete
from .utils import AppReq
def pytest_configure(config: pytest.Config) -> None:
config.stash[NONEBOT_INIT_KWARGS] = {
"datastore_database_url": "sqlite+aiosqlite:///:memory:",
"superusers": {"10001"},
"command_start": {""},
"log_level": "TRACE",
}
@pytest.fixture
async def app(nonebug_init: None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
import nonebot
async def app(tmp_path: Path, request: pytest.FixtureRequest, mocker: MockerFixture):
sys.path.append(str(Path(__file__).parent.parent / "src" / "plugins"))
config = nonebot.get_driver().config
config.bison_config_path = str(tmp_path / "legacy_config")
config.datastore_config_dir = str(tmp_path / "config")
config.datastore_cache_dir = str(tmp_path / "cache")
config.datastore_data_dir = str(tmp_path / "data")
config.command_start = {""}
config.superusers = {"10001"}
config.log_level = "TRACE"
config.bison_filter_log = False
nonebot.require("nonebot_bison")
return App(monkeypatch)
from nonebot_bison import plugin_config
from nonebot_bison.config.db_model import (
ScheduleTimeWeight,
Subscribe,
Target,
User,
)
from nonebot_plugin_datastore.config import plugin_config as datastore_config
from nonebot_plugin_datastore.db import create_session, init_db
from nonebot_plugin_htmlrender.browser import shutdown_browser
plugin_config.bison_config_path = str(tmp_path / "legacy_config")
plugin_config.bison_filter_log = False
datastore_config.datastore_config_dir = tmp_path / "config"
datastore_config.datastore_cache_dir = tmp_path / "cache"
datastore_config.datastore_data_dir = tmp_path / "data"
param: AppReq = getattr(request, "param", AppReq())
if not param.get("no_init_db"):
await init_db()
if not param.get("refresh_bot"):
import nonebot_bison.utils.get_bot
mocker.patch.object(nonebot_bison.utils.get_bot, "refresh_bots")
yield App()
# cleanup
async with create_session() as session, session.begin():
await session.execute(delete(User))
await session.execute(delete(Subscribe))
await session.execute(delete(Target))
await session.execute(delete(ScheduleTimeWeight))
# 关闭渲染图片时打开的浏览器
await shutdown_browser()
@pytest.fixture
@@ -35,21 +73,7 @@ def dummy_user_subinfo(app: App):
@pytest.fixture
async def db_migration(app: App):
from nonebot_bison.config.db_model import Subscribe, Target, User
from nonebot_plugin_datastore.db import get_engine, init_db
await init_db()
async with AsyncSession(get_engine()) as sess:
await sess.execute(delete(User))
await sess.execute(delete(Subscribe))
await sess.execute(delete(Target))
await sess.commit()
await sess.close()
@pytest.fixture
async def init_scheduler(db_migration):
async def init_scheduler(app: App):
from nonebot_bison.scheduler.manager import init_scheduler
await init_scheduler()
-1
View File
@@ -65,7 +65,6 @@ async def test_fetch_new(weibo, dummy_user_subinfo):
assert not detail_router.called
mock_data = get_json("weibo_ak_list_1.json")
ak_list_router.mock(return_value=Response(200, json=mock_data))
# import ipdb; ipdb.set_trace()
res2 = await weibo.fetch_new_post(target, [dummy_user_subinfo])
assert len(res2) == 0
mock_data["data"]["cards"][1]["mblog"]["created_at"] = datetime.now(
+5 -3
View File
@@ -3,6 +3,7 @@ from datetime import time
from typing import Type
from nonebug import App
from pytest_mock import MockerFixture
if typing.TYPE_CHECKING:
from nonebot_bison.utils.scheduler_config import SchedulerConfig
@@ -60,7 +61,7 @@ async def test_scheduler_without_time(init_scheduler):
assert static_res["bilibili-live-t2"] == 3
async def test_scheduler_with_time(app: App, init_scheduler):
async def test_scheduler_with_time(app: App, init_scheduler, mocker: MockerFixture):
from nonebot_bison.config import config, db_config
from nonebot_bison.config.db_config import TimeWeightConfig, WeightConfig
from nonebot_bison.platform.bilibili import BilibiliSchedConf
@@ -93,7 +94,8 @@ async def test_scheduler_with_time(app: App, init_scheduler):
await init_scheduler()
app.monkeypatch.setattr(db_config, "_get_time", lambda: time(1, 30))
mocker.patch.object(db_config, "_get_time", return_value=time(1, 30))
static_res = await get_schedule_times(BilibiliSchedConf, 6)
assert static_res["bilibili-t1"] == 1
assert static_res["bilibili-t2"] == 2
@@ -104,7 +106,7 @@ async def test_scheduler_with_time(app: App, init_scheduler):
assert static_res["bilibili-t2"] == 2
assert static_res["bilibili-live-t2"] == 3
app.monkeypatch.setattr(db_config, "_get_time", lambda: time(10, 30))
mocker.patch.object(db_config, "_get_time", return_value=time(10, 30))
static_res = await get_schedule_times(BilibiliSchedConf, 6)
assert static_res["bilibili-t2"] == 6
+3 -2
View File
@@ -2,6 +2,7 @@ import pytest
import respx
from httpx import Response
from nonebug.app import App
from pytest_mock import MockerFixture
from .platforms.utils import get_json
from .utils import BotReply, fake_admin_user, fake_group_message_event
@@ -289,7 +290,7 @@ async def test_add_no_target(app: App, init_scheduler):
@pytest.mark.asyncio
async def test_platform_name_err(app: App, db_migration):
async def test_platform_name_err(app: App):
from nonebot.adapters.onebot.v11.event import Sender
from nonebot.adapters.onebot.v11.message import Message
from nonebot_bison.config_manager import add_sub_matcher, common_platform
@@ -324,7 +325,7 @@ async def test_platform_name_err(app: App, db_migration):
@pytest.mark.asyncio
@respx.mock
async def test_add_with_get_id(app: App, db_migration):
async def test_add_with_get_id(app: App):
from nonebot.adapters.onebot.v11.event import Sender
from nonebot.adapters.onebot.v11.message import Message, MessageSegment
from nonebot_bison.config import config
+5
View File
@@ -1,8 +1,11 @@
import pytest
from nonebug import App
from .utils import AppReq
@pytest.mark.asyncio
@pytest.mark.parametrize("app", [{"refresh_bot": True}], indirect=True)
async def test_get_bots(app: App) -> None:
from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot as BotV11
@@ -23,6 +26,7 @@ async def test_get_bots(app: App) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("app", [{"refresh_bot": True}], indirect=True)
async def test_refresh_bots(app: App) -> None:
from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot as BotV11
@@ -57,6 +61,7 @@ async def test_refresh_bots(app: App) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("app", [{"refresh_bot": True}], indirect=True)
async def test_get_bot_two_bots(app: App) -> None:
from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot as BotV11
+12 -6
View File
@@ -1,5 +1,7 @@
import pytest
import importlib
from nonebug import App
from pytest_mock import MockerFixture
async def test_without_proxy(app: App):
@@ -11,11 +13,15 @@ async def test_without_proxy(app: App):
assert "Chrome" in req.headers["User-Agent"]
@pytest.mark.parametrize(
"nonebug_init", [{"bison_proxy": "http://example.com"}], indirect=True
)
async def test_with_proxy(app: App):
from nonebot_bison.utils import http_client
async def test_with_proxy(app: App, mocker: MockerFixture):
from nonebot_bison.plugin_config import plugin_config
mocker.patch.object(plugin_config, "bison_proxy", "http://example.com")
from nonebot_bison.utils import http
importlib.reload(http)
from nonebot_bison.utils.http import http_client
c = http_client()
assert c._mounts
+7 -5
View File
@@ -4,20 +4,21 @@ import typing
import pytest
from flaky import flaky
from nonebug import App
from pytest_mock.plugin import MockerFixture
if typing.TYPE_CHECKING:
from nonebot.adapters.onebot.v11.message import Message, MessageSegment
@pytest.mark.asyncio
async def test_send_no_queue(app: App):
async def test_send_no_queue(app: App, mocker: MockerFixture):
from nonebot.adapters.onebot.v11.bot import Bot
from nonebot.adapters.onebot.v11.message import Message
from nonebot_bison.plugin_config import plugin_config
from nonebot_bison.send import send_msgs
mocker.patch.object(plugin_config, "bison_use_queue", False)
async with app.test_api() as ctx:
app.monkeypatch.setattr(plugin_config, "bison_use_queue", False, True)
bot = ctx.create_bot(base=Bot)
assert isinstance(bot, Bot)
ctx.should_call_api(
@@ -35,17 +36,18 @@ async def test_send_no_queue(app: App):
@pytest.mark.asyncio
@pytest.mark.parametrize("nonebug_init", [{"bison_use_queue": True}], indirect=True)
async def test_send_queue(app: App):
async def test_send_queue(app: App, mocker: MockerFixture):
import nonebot
from nonebot.adapters.onebot.v11.bot import Bot
from nonebot.adapters.onebot.v11.message import Message, MessageSegment
from nonebot_bison import send
from nonebot_bison.plugin_config import plugin_config
from nonebot_bison.send import MESSGE_SEND_INTERVAL, do_send_msgs, send_msgs
mocker.patch.object(plugin_config, "bison_use_queue", True)
async with app.test_api() as ctx:
new_bot = ctx.create_bot(base=Bot)
app.monkeypatch.setattr(nonebot, "get_bot", lambda: new_bot, True)
mocker.patch.object(nonebot, "get_bot", lambda: new_bot)
bot = nonebot.get_bot()
assert isinstance(bot, Bot)
assert bot == new_bot
+6 -1
View File
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import Literal
@@ -6,6 +6,11 @@ if TYPE_CHECKING:
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent
class AppReq(TypedDict, total=False):
refresh_bot: bool
no_init_db: bool
def fake_group_message_event(**field) -> "GroupMessageEvent":
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.event import Sender