Alternatate classes on instantiation for Config and Sanic.ctx (#2119)

This commit is contained in:
Adam Hopkins 2021-06-01 00:21:31 +03:00 committed by GitHub
parent d16b9e5a02
commit b1f31f2eeb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 2 deletions

View File

@ -123,6 +123,8 @@ class Sanic(BaseSanic):
def __init__(
self,
name: str = None,
config: Optional[Config] = None,
ctx: Optional[Any] = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
@ -141,6 +143,12 @@ class Sanic(BaseSanic):
if configure_logging:
logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)
if config and (load_env is not True or env_prefix != SANIC_PREFIX):
raise SanicException(
"When instantiating Sanic with config, you cannot also pass "
"load_env or env_prefix"
)
self._asgi_client = None
self._blueprint_order: List[Blueprint] = []
self._test_client = None
@ -148,9 +156,11 @@ class Sanic(BaseSanic):
self.asgi = False
self.auto_reload = False
self.blueprints: Dict[str, Blueprint] = {}
self.config = Config(load_env=load_env, env_prefix=env_prefix)
self.config = config or Config(
load_env=load_env, env_prefix=env_prefix
)
self.configure_logging = configure_logging
self.ctx = SimpleNamespace()
self.ctx = ctx or SimpleNamespace()
self.debug = None
self.error_handler = error_handler or ErrorHandler()
self.is_running = False

View File

@ -9,6 +9,7 @@ from unittest.mock import Mock, patch
import pytest
from sanic import Sanic
from sanic.config import Config
from sanic.exceptions import SanicException
from sanic.response import text
@ -412,3 +413,42 @@ def test_subclass_initialisation():
pass
CustomSanic("test_subclass_initialisation")
def test_bad_custom_config():
with pytest.raises(
SanicException,
match=(
"When instantiating Sanic with config, you cannot also pass "
"load_env or env_prefix"
),
):
Sanic("test", config=1, load_env=1)
with pytest.raises(
SanicException,
match=(
"When instantiating Sanic with config, you cannot also pass "
"load_env or env_prefix"
),
):
Sanic("test", config=1, env_prefix=1)
def test_custom_config():
class CustomConfig(Config):
...
config = CustomConfig()
app = Sanic("custom", config=config)
assert app.config == config
def test_custom_context():
class CustomContext:
...
ctx = CustomContext()
app = Sanic("custom", ctx=ctx)
assert app.ctx == ctx