Skip to content

Commit

Permalink
Merge pull request #1342 from hramezani/load_config_file_syntax_error
Browse files Browse the repository at this point in the history
Handle syntax error in load config file.
  • Loading branch information
sjsadowski committed Oct 11, 2018
2 parents fd61b9e + f4c55bb commit 6778f4d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions sanic/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import types

from sanic.exceptions import PyFileError


SANIC_PREFIX = 'SANIC_'

Expand Down Expand Up @@ -83,6 +85,9 @@ def from_pyfile(self, filename):
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

Expand Down
5 changes: 5 additions & 0 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
11 changes: 11 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest

from sanic import Sanic
from sanic.exceptions import PyFileError


@contextmanager
Expand Down Expand Up @@ -87,6 +88,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

Expand Down

0 comments on commit 6778f4d

Please sign in to comment.