From f4c55bbc07b04e363aed480c9164c173637d7625 Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Wed, 3 Oct 2018 14:27:59 +0200 Subject: [PATCH] Handle config error in load config file. --- sanic/config.py | 5 +++++ sanic/exceptions.py | 5 +++++ tests/test_config.py | 11 +++++++++++ 3 files changed, 21 insertions(+) diff --git a/sanic/config.py b/sanic/config.py index c5e42de5..3e968117 100644 --- a/sanic/config.py +++ b/sanic/config.py @@ -1,6 +1,8 @@ import os import types +from sanic.exceptions import PyFileError + SANIC_PREFIX = 'SANIC_' @@ -83,6 +85,9 @@ class Config(dict): except IOError as e: e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise + except Exception as e: + raise PyFileError(filename) from e + self.from_object(module) return True diff --git a/sanic/exceptions.py b/sanic/exceptions.py index 25dbd47d..0b834e75 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -223,6 +223,11 @@ class InvalidRangeType(ContentRangeError): pass +class PyFileError(Exception): + def __init__(self, file): + super().__init__('could not execute config file %s', file) + + @add_status_code(401) class Unauthorized(SanicException): """ diff --git a/tests/test_config.py b/tests/test_config.py index 08461b81..f8322036 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,6 +3,7 @@ import pytest from tempfile import NamedTemporaryFile from sanic import Sanic +from sanic.exceptions import PyFileError def test_load_from_object(app): @@ -79,6 +80,16 @@ def test_load_from_missing_envvar(app): "could not be loaded.") +def test_load_config_from_file_invalid_syntax(app): + config = b"VALUE = some value" + with NamedTemporaryFile() as config_file: + config_file.write(config) + config_file.seek(0) + + with pytest.raises(PyFileError): + app.config.from_pyfile(config_file.name) + + def test_overwrite_exisiting_config(app): app.config.DEFAULT = 1