From fe69735ca00b791c731ee583dcf19957ca6c98bf Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Thu, 16 Dec 2021 17:28:57 +0800 Subject: [PATCH] :white_check_mark: add test cases --- nonebot/__init__.py | 8 +++--- nonebot/config.py | 7 ++--- nonebot/log.py | 2 +- tests/.coveragerc | 6 +++++ tests/.env.test | 1 + tests/plugins/export.py | 6 +++++ tests/plugins/require.py | 8 ++++++ tests/pyproject.toml | 2 ++ tests/test_init.py | 57 +++++++++++++++++++++++++++++++++++++--- 9 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 tests/.coveragerc create mode 100644 tests/plugins/export.py create mode 100644 tests/plugins/require.py create mode 100644 tests/pyproject.toml diff --git a/nonebot/__init__.py b/nonebot/__init__.py index 9d90ac19..92d63d75 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -43,7 +43,7 @@ try: _dist: pkg_resources.Distribution = pkg_resources.get_distribution("nonebot2") __version__ = _dist.version VERSION = _dist.parsed_version -except pkg_resources.DistributionNotFound: +except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None VERSION = None @@ -252,7 +252,7 @@ def init(*, _env_file: Optional[str] = None, **kwargs): _driver = DriverClass(env, config) -def run(host: Optional[str] = None, port: Optional[int] = None, *args, **kwargs): +def run(*args: Any, **kwargs: Any) -> None: """ :说明: @@ -260,8 +260,6 @@ def run(host: Optional[str] = None, port: Optional[int] = None, *args, **kwargs) :参数: - * ``host: Optional[str]``: 主机名/IP,若不传入则使用配置文件中指定的值 - * ``port: Optional[int]``: 端口,若不传入则使用配置文件中指定的值 * ``*args``: 传入 Driver.run 的位置参数 * ``**kwargs``: 传入 Driver.run 的命名参数 @@ -277,7 +275,7 @@ def run(host: Optional[str] = None, port: Optional[int] = None, *args, **kwargs) """ logger.success("Running NoneBot...") - get_driver().run(host, port, *args, **kwargs) + get_driver().run(*args, **kwargs) import nonebot.params as params diff --git a/nonebot/config.py b/nonebot/config.py index 71fb532b..99507fa7 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -38,7 +38,7 @@ class CustomEnvSettings(EnvSettingsSource): d: Dict[str, Optional[str]] = {} if settings.__config__.case_sensitive: - env_vars: Mapping[str, Optional[str]] = os.environ + env_vars: Mapping[str, Optional[str]] = os.environ # pragma: no cover else: env_vars = {k.lower(): v for k, v in os.environ.items()} @@ -78,7 +78,7 @@ class CustomEnvSettings(EnvSettingsSource): if field.is_complex(): try: env_val = settings.__config__.json_loads(env_val) - except ValueError as e: + except ValueError as e: # pragma: no cover raise SettingsError( f'error parsing JSON for "{env_name}"' # type: ignore ) from e @@ -100,7 +100,8 @@ class CustomEnvSettings(EnvSettingsSource): class BaseConfig(BaseSettings): - def __getattr__(self, name: str) -> Any: + # dummy getattr for pylance checking, actually not used + def __getattr__(self, name: str) -> Any: # pragma: no cover return self.__dict__.get(name) class Config: diff --git a/nonebot/log.py b/nonebot/log.py index 8541f6b8..b39a0497 100644 --- a/nonebot/log.py +++ b/nonebot/log.py @@ -63,7 +63,7 @@ class Filter: return record["level"].no >= levelno -class LoguruHandler(logging.Handler): +class LoguruHandler(logging.Handler): # pragma: no cover def emit(self, record): try: level = logger.level(record.levelname).name diff --git a/tests/.coveragerc b/tests/.coveragerc new file mode 100644 index 00000000..97998b7f --- /dev/null +++ b/tests/.coveragerc @@ -0,0 +1,6 @@ +[report] +exclude_lines = + pragma: no cover + if TYPE_CHECKING: + @(abc\.)?abstractmethod + raise NotImplementedError diff --git a/tests/.env.test b/tests/.env.test index d3820de0..11b8445f 100644 --- a/tests/.env.test +++ b/tests/.env.test @@ -1 +1,2 @@ +NICKNAME=["test"] CONFIG_FROM_ENV= diff --git a/tests/plugins/export.py b/tests/plugins/export.py new file mode 100644 index 00000000..f7570e92 --- /dev/null +++ b/tests/plugins/export.py @@ -0,0 +1,6 @@ +from nonebot import export + + +@export() +def test(): + ... diff --git a/tests/plugins/require.py b/tests/plugins/require.py new file mode 100644 index 00000000..2b22504f --- /dev/null +++ b/tests/plugins/require.py @@ -0,0 +1,8 @@ +from nonebot import require + +from plugins.export import test +from .export import test as test_related + +test_require = require("export").test + +assert test is test_related and test is test_require, "Export Require Error" diff --git a/tests/pyproject.toml b/tests/pyproject.toml new file mode 100644 index 00000000..8f7f477a --- /dev/null +++ b/tests/pyproject.toml @@ -0,0 +1,2 @@ +[tool.isort] +known_local_folder = ["plugins"] diff --git a/tests/test_init.py b/tests/test_init.py index 61dbdae7..8038be9d 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,30 +1,81 @@ import os import sys +from re import A from typing import TYPE_CHECKING, Set import pytest + from utils import load_plugin if TYPE_CHECKING: from nonebot.plugin import Plugin -os.environ["CONFIG_FROM_ENV"] = "env" +os.environ["CONFIG_FROM_ENV"] = '{"test": "test"}' @pytest.mark.asyncio -@pytest.mark.parametrize("nonebug_init", [{"config_from_init": "init"}], indirect=True) +@pytest.mark.parametrize( + "nonebug_init", + [{"config_from_init": "init", "driver": "nonebot.drivers.fastapi:FullDriver"}], + indirect=True, +) async def test_init(nonebug_init): from nonebot import get_driver + from nonebot.drivers.fastapi import FullDriver env = get_driver().env assert env == "test" + assert isinstance(get_driver(), FullDriver) + config = get_driver().config - assert config.config_from_env == "env" + assert config.config_from_env == {"test": "test"} assert config.config_from_init == "init" assert config.common_config == "common" +@pytest.mark.asyncio +async def test_get(monkeypatch: pytest.MonkeyPatch, nonebug_clear): + import nonebot + from nonebot.drivers import ForwardDriver, ReverseDriver + from nonebot import get_app, get_bot, get_asgi, get_bots, get_driver + + try: + get_driver() + assert False, "Driver can only be got after initialization" + except ValueError: + assert True + + nonebot.init(driver="nonebot.drivers.fastapi") + + driver = get_driver() + assert isinstance(driver, ReverseDriver) + assert get_asgi() == driver.asgi + assert get_app() == driver.server_app + + runned = False + + def mock_run(*args, **kwargs): + nonlocal runned + runned = True + assert args == ("arg",) and kwargs == {"kwarg": "kwarg"} + + monkeypatch.setattr(driver, "run", mock_run) + nonebot.run("arg", kwarg="kwarg") + assert runned + + try: + get_bot() + assert False + except ValueError: + assert True + + monkeypatch.setattr(driver, "_clients", {"test": "test"}) + assert get_bot() == "test" + assert get_bot("test") == "test" + assert get_bots() == {"test": "test"} + + @pytest.mark.asyncio async def test_load_plugin(load_plugin: Set["Plugin"]): import nonebot