Skip to content

Commit

Permalink
Introduce post_init() (#1458)
Browse files Browse the repository at this point in the history
* Introduce post_init()

* Add missing test

* Add missing coverage mark

* Fix typo
  • Loading branch information
asvetlov authored Dec 7, 2016
1 parent d8ddbc2 commit 95e4376
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
4 changes: 4 additions & 0 deletions aiohttp/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class AbstractRouter(ABC):
def __init__(self):
self._frozen = False

@abstractmethod
def post_init(self, app):
pass # pragma: no cover

@property
def frozen(self):
return self._frozen
Expand Down
4 changes: 3 additions & 1 deletion aiohttp/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ def __init__(self, *, logger=web_logger, loop=None,
if loop is None:
loop = asyncio.get_event_loop()
if router is None:
router = web_urldispatcher.UrlDispatcher(self)
router = web_urldispatcher.UrlDispatcher()
assert isinstance(router, AbstractRouter), router

router.post_init(self)

if debug is ...:
debug = loop.get_debug()

Expand Down
9 changes: 8 additions & 1 deletion aiohttp/web_urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,10 +710,14 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping):
ROUTE_RE = re.compile(r'(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})')
NAME_SPLIT_RE = re.compile(r'[.:-]')

def __init__(self, app):
def __init__(self):
super().__init__()
self._resources = []
self._named_resources = {}
self._app = None

def post_init(self, app):
assert app is not None
self._app = app

@asyncio.coroutine
Expand Down Expand Up @@ -759,6 +763,9 @@ def _reg_resource(self, resource):
assert isinstance(resource, AbstractResource), \
'Instance of AbstractResource class is required, got {!r}'.format(
resource)
if self._app is None:
raise RuntimeError(".post_init() should be called before "
"first resource registering")
if self.frozen:
raise RuntimeError("Cannot register a resource into "
"frozen router.")
Expand Down
8 changes: 7 additions & 1 deletion tests/test_urldispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from aiohttp.test_utils import make_mocked_request
from aiohttp.web import HTTPMethodNotAllowed, HTTPNotFound, Response
from aiohttp.web_urldispatcher import (AbstractResource, ResourceRoute,
SystemRoute, View,
SystemRoute, UrlDispatcher, View,
_defaultExpectHandler)


Expand Down Expand Up @@ -1011,3 +1011,9 @@ def test_convert_empty_path_to_slash_on_freezing(router):
assert resource.get_info() == {'path': ''}
router.freeze()
assert resource.get_info() == {'path': '/'}


def test_add_to_non_initialized_router():
router = UrlDispatcher()
with pytest.raises(RuntimeError):
router.add_get('/', make_handler())

0 comments on commit 95e4376

Please sign in to comment.