mirror of
https://github.com/nonebot/nonebot2.git
synced 2026-01-13 23:31:50 +00:00
✨ Feature: 允许插件从环境变量中读取配置项并支持 alias (#3673)
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
This commit is contained in:
@@ -10,6 +10,7 @@ NESTED__C__C=3
|
||||
NESTED__COMPLEX=[1, 2, 3]
|
||||
NESTED_INNER__A=1
|
||||
NESTED_INNER__B=2
|
||||
ALIAS_SIMPLE=aliased_simple
|
||||
OTHER_SIMPLE=simple
|
||||
OTHER_NESTED={"a": 1}
|
||||
OTHER_NESTED__B=2
|
||||
|
||||
@@ -37,6 +37,7 @@ class Example(BaseSettings):
|
||||
complex_union: Union[int, list[int]] = 1
|
||||
nested: Simple = Simple()
|
||||
nested_inner: Simple = Simple()
|
||||
aliased_simple: str = Field(default="", alias="alias_simple")
|
||||
|
||||
|
||||
class ExampleWithoutDelimiter(Example):
|
||||
@@ -85,6 +86,8 @@ def test_config_with_env():
|
||||
with pytest.raises(AttributeError):
|
||||
config.nested_inner__b
|
||||
|
||||
assert config.aliased_simple == "aliased_simple"
|
||||
|
||||
assert config.common_config == "common"
|
||||
|
||||
assert config.other_simple == "simple"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
import pytest
|
||||
|
||||
import nonebot
|
||||
from nonebot.plugin import PluginManager, _managers
|
||||
@@ -67,3 +68,27 @@ def test_get_plugin_config():
|
||||
config = nonebot.get_plugin_config(Config)
|
||||
assert isinstance(config, Config)
|
||||
assert config.plugin_config == 1
|
||||
|
||||
|
||||
def test_get_plugin_config_with_env(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("PLUGIN_CONFIG_ONE", "no_dummy_val")
|
||||
monkeypatch.setenv("PLUGIN_SUB_CONFIG__TWO", "two")
|
||||
monkeypatch.setenv("PLUGIN_CFG_THREE", "33")
|
||||
monkeypatch.setenv("CONFIG_FROM_INIT", "impossible")
|
||||
|
||||
class SubConfig(BaseModel):
|
||||
two: str = "dummy_val"
|
||||
|
||||
class Config(BaseModel):
|
||||
plugin_config: int
|
||||
plugin_config_one: str = "dummy_val"
|
||||
plugin_sub_config: SubConfig = Field(default_factory=SubConfig)
|
||||
plugin_config_three: int = Field(default=3, alias="plugin_cfg_three")
|
||||
config_from_init: str = "dummy_val"
|
||||
|
||||
config = nonebot.get_plugin_config(Config)
|
||||
assert config.plugin_config == 1
|
||||
assert config.plugin_config_one == "no_dummy_val"
|
||||
assert config.plugin_sub_config.two == "two"
|
||||
assert config.plugin_config_three == 33
|
||||
assert config.config_from_init == "init"
|
||||
|
||||
Reference in New Issue
Block a user