Skip to content

Commit

Permalink
blacken
Browse files Browse the repository at this point in the history
  • Loading branch information
aodag committed Feb 11, 2019
1 parent 55f8658 commit e74a63e
Show file tree
Hide file tree
Showing 14 changed files with 202 additions and 197 deletions.
23 changes: 12 additions & 11 deletions webdispatch/base.py
Expand Up @@ -7,9 +7,10 @@ class DispatchBase(object):
""" Base class for dispatcher application"""

def __init__(
self,
applications: Dict[str, Callable] = None,
extra_environ: Dict[str, Any] = None) -> None:
self,
applications: Dict[str, Callable] = None,
extra_environ: Dict[str, Any] = None,
) -> None:

if applications is None:
self.applications = {} # type: Dict[str, Callable]
Expand All @@ -23,11 +24,13 @@ def __init__(
def register_app(self, name: str, app: Callable = None) -> Callable:
""" register dispatchable wsgi application"""
if app is None:

def dec(app):
""" inner decorator for register app """
assert app is not None
self.register_app(name, app)
return app

return dec
self.applications[name] = app
return None
Expand All @@ -36,21 +39,19 @@ def get_extra_environ(self) -> Dict[str, Any]:
""" returns for environ values for wsgi environ"""
return self.extra_environ

def detect_view_name(
self, environ: Dict[str, Any]) -> str: # pragma: nocover
def detect_view_name(self, environ: Dict[str, Any]) -> str: # pragma: nocover
""" must returns view name for request """
raise NotImplementedError()

def on_view_not_found(
self,
environ: Dict[str, Any],
start_response: Callable) -> Iterable[bytes]: # pragma: nocover
self, environ: Dict[str, Any], start_response: Callable
) -> Iterable[bytes]: # pragma: nocover
""" called when view is not found"""
raise NotImplementedError()

def __call__(self,
environ: Dict[str, Any],
start_response: Callable) -> Iterable[bytes]:
def __call__(
self, environ: Dict[str, Any], start_response: Callable
) -> Iterable[bytes]:
extra_environ = self.get_extra_environ()
environ.update(extra_environ)
view_name = self.detect_view_name(environ)
Expand Down
12 changes: 4 additions & 8 deletions webdispatch/dummyapps.py
Expand Up @@ -3,15 +3,11 @@

def greeting(_, start_response):
""" dummy application returns Hello simply"""
start_response(
'200 OK',
[('Content-type', 'text/plain')])
return [b'Hello']
start_response("200 OK", [("Content-type", "text/plain")])
return [b"Hello"]


def bye(_, start_response):
""" dummy application returns by simply"""
start_response(
'200 OK',
[('Content-type', 'text/plain')])
return [b'bye']
start_response("200 OK", [("Content-type", "text/plain")])
return [b"bye"]
28 changes: 13 additions & 15 deletions webdispatch/methoddispatcher.py
Expand Up @@ -9,24 +9,22 @@
class MethodDispatcher(DispatchBase):
""" dispatch applications with request method.
"""

def __init__(self, **kwargs) -> None:
super(MethodDispatcher, self).__init__()
for name, app in kwargs.items():
self.register_app(name, app)

def detect_view_name(self, environ: Dict[str, Any]) -> str:
""" convert request method to view name """
return environ['REQUEST_METHOD'].lower()
return environ["REQUEST_METHOD"].lower()

def on_view_not_found(
self, _,
start_response: Callable[[str, List[Tuple[str, str]]], None],
self, _, start_response: Callable[[str, List[Tuple[str, str]]], None]
) -> Iterable[bytes]:
""" called when valid view is not found """

start_response(
"405 Method Not Allowed",
[('Content-type', 'text/plain')])
start_response("405 Method Not Allowed", [("Content-type", "text/plain")])
return [b"Method Not Allowed"]


Expand All @@ -41,35 +39,35 @@ def wsgiapp(environ, start_response):
""" inner app """
handler = handler_cls()
return getattr(handler, action_name)(environ, start_response)

return wsgiapp


class ActionDispatcher(DispatchBase):
""" wsgi application dispatching actions to registered classes"""

def __init__(self, action_var_name: str = 'action') -> None:
def __init__(self, action_var_name: str = "action") -> None:
super(ActionDispatcher, self).__init__()
self.action_var_name = action_var_name

def register_actionhandler(self, action_handler: type) -> None:
""" register class as action handler """
for k in action_handler.__dict__:
if k.startswith('_'):
if k.startswith("_"):
continue
app = action_handler_adapter(action_handler, k)
self.register_app(k, app)

def detect_view_name(self, environ: Dict[str, Any]) -> str:
""" get view name from routing args """
urlvars = environ.get('wsgiorg.routing_args', [(), {}])[1]
urlvars = environ.get("wsgiorg.routing_args", [(), {}])[1]
return urlvars.get(self.action_var_name)

def on_view_not_found(
self, environ: Dict[str, Any],
start_response: Callable[[str, List[Tuple[str, str]]], None],
self,
environ: Dict[str, Any],
start_response: Callable[[str, List[Tuple[str, str]]], None],
) -> Iterable[bytes]:
""" called when action is not found """
start_response(
"404 Not Found",
[('Content-type', 'text/plain')])
return [b"Not Found ", application_uri(environ).encode('utf-8')]
start_response("404 Not Found", [("Content-type", "text/plain")])
return [b"Not Found ", application_uri(environ).encode("utf-8")]
3 changes: 2 additions & 1 deletion webdispatch/mixins.py
Expand Up @@ -7,6 +7,7 @@
class URLMapperMixin(object):
""" mixin to add :meth:`generate_url` method.
"""

environ = {} # type: Dict[str, Any]

def generate_url(self, name: str, **kwargs) -> str:
Expand All @@ -16,4 +17,4 @@ def generate_url(self, name: str, **kwargs) -> str:
@property
def urlmapper(self) -> URLGenerator:
""" get urlmapper object from wsgi environ """
return self.environ['webdispatch.urlgenerator']
return self.environ["webdispatch.urlgenerator"]
4 changes: 1 addition & 3 deletions webdispatch/paster.py
Expand Up @@ -6,9 +6,7 @@

def make_urldispatch_application(_, **settings):
""" paste.app_factory interface for URLDispatcher"""
patterns = [p.split("=", 1)
for p in settings['patterns'].split('\n')
if p]
patterns = [p.split("=", 1) for p in settings["patterns"].split("\n") if p]
application = URLDispatcher()

for pattern, app in patterns:
Expand Down
7 changes: 3 additions & 4 deletions webdispatch/testing.py
Expand Up @@ -6,6 +6,7 @@ def setup_environ(**kwargs):
""" setup basic wsgi environ"""
environ = {}
from wsgiref.util import setup_testing_defaults

setup_testing_defaults(environ)
environ.update(kwargs)
return environ
Expand All @@ -15,9 +16,7 @@ def make_env(path_info, script_name):
""" set up basic wsgi environ"""

from wsgiref.util import setup_testing_defaults
environ = {
"PATH_INFO": path_info,
"SCRIPT_NAME": script_name,
}

environ = {"PATH_INFO": path_info, "SCRIPT_NAME": script_name}
setup_testing_defaults(environ)
return environ
9 changes: 5 additions & 4 deletions webdispatch/tests/test_base.py
Expand Up @@ -10,6 +10,7 @@ class TestDispatchBase(object):
def _get_target():
""" get class under test """
from webdispatch.base import DispatchBase

return DispatchBase

def _make_one(self, *args, **kwargs):
Expand All @@ -28,19 +29,19 @@ def test_init_apps(self):
""" init with app and no environ"""

testing_app = object()
result = self._make_one(applications={'testing': testing_app})
result = self._make_one(applications={"testing": testing_app})

compare(result.applications, {'testing': testing_app})
compare(result.applications, {"testing": testing_app})
compare(result.extra_environ, {})

def test_init_env(self):
""" init with app and no environ"""

environ = {'test_value': 1}
environ = {"test_value": 1}
result = self._make_one(extra_environ=environ)

compare(result.applications, {})
compare(result.extra_environ, {'test_value': 1})
compare(result.extra_environ, {"test_value": 1})

def test_not_found(self):
""" init with app and no environ"""
Expand Down
46 changes: 25 additions & 21 deletions webdispatch/tests/test_methoddispatcher.py
Expand Up @@ -11,10 +11,12 @@ def dummy_get_app(*dummy):

class TestMethodDispatcher(object):
""" test for webdispatch.methoddispatcher.MethodDispatcher"""

@staticmethod
def _get_target():
""" get class under test """
from webdispatch.methoddispatcher import MethodDispatcher

return MethodDispatcher

def _make_one(self, *args, **kwargs):
Expand All @@ -32,12 +34,13 @@ def test_it(self):
def test_not_allowed(self):
""" test not found views"""
app = self._make_one(get=dummy_get_app)
environ = setup_environ(REQUEST_METHOD='POST')
environ = setup_environ(REQUEST_METHOD="POST")
start_response = mock.Mock()
result = app(environ, start_response)
compare(result, [b"Method Not Allowed"])
start_response.assert_called_with(
'405 Method Not Allowed', [('Content-type', 'text/plain')])
"405 Method Not Allowed", [("Content-type", "text/plain")]
)

def test_register_app(self):
""" test registering app"""
Expand All @@ -63,17 +66,20 @@ def test_register_app_decorator(self):

class TestActionHandlerAdapter(object):
""" test for webdispatch.methoddispatcher.action_handler_adapter"""

@staticmethod
def _call_fut(*args, **kwargs):
""" call function under test """
from webdispatch.methoddispatcher import action_handler_adapter

return action_handler_adapter(*args, **kwargs)

def test_call(self):
""" test basic using """

class DummyAction(object):
""" dummy action class"""

def __init__(self):
self.message = b"Hello"

Expand All @@ -83,17 +89,15 @@ def get_message(self):

def action(self, _, start_response):
""" dummy action """
start_response("200 OK",
[("Content-type", "text/plain")])
start_response("200 OK", [("Content-type", "text/plain")])
return [self.get_message()]

target = self._call_fut(DummyAction, "action")
environ = setup_environ(REQUEST_METHOD='POST')
environ = setup_environ(REQUEST_METHOD="POST")
start_response = mock.Mock()
result = target(environ, start_response)
compare(result, [b"Hello"])
start_response.assert_called_with(
'200 OK', [('Content-type', 'text/plain')])
start_response.assert_called_with("200 OK", [("Content-type", "text/plain")])

def test_invalid_name(self):
""" test using invalid attr name """
Expand All @@ -104,10 +108,12 @@ def test_invalid_name(self):

class TestActionDispatcher(object):
""" test for webdispatch.methoddispatcher.ActionDispatcher"""

@staticmethod
def _get_target():
""" get class under test"""
from webdispatch.methoddispatcher import ActionDispatcher

return ActionDispatcher

def _make_one(self, *args, **kwargs):
Expand All @@ -120,12 +126,12 @@ def test_it(self):

def test_app(*_):
""" dummy app"""
return [b'got action']
return [b"got action"]

app.register_app('test_app', test_app)
routing_args = [(), {'action': 'test_app'}]
app.register_app("test_app", test_app)
routing_args = [(), {"action": "test_app"}]
environ = setup_environ()
environ.update({'wsgiorg.routing_args': routing_args})
environ.update({"wsgiorg.routing_args": routing_args})
start_response = mock.Mock()
result = app(environ, start_response)
compare(result, [b"got action"])
Expand All @@ -147,9 +153,9 @@ def test_action(self, *_):
return self.get_body()

app.register_actionhandler(DummyHandler)
routing_args = [(), {'action': 'test_action'}]
routing_args = [(), {"action": "test_action"}]
environ = setup_environ()
environ.update({'wsgiorg.routing_args': routing_args})
environ.update({"wsgiorg.routing_args": routing_args})
start_response = mock.Mock()
result = app(environ, start_response)
compare(result, [b"test action"])
Expand All @@ -158,17 +164,15 @@ def test_not_found(self):
""" test called not registered action """

app = self._make_one()
app.register_app('test_app',
None)
routing_args = [(), {'action': 'no_app'}]
env = {'wsgiorg.routing_args': routing_args}
app.register_app("test_app", None)
routing_args = [(), {"action": "no_app"}]
env = {"wsgiorg.routing_args": routing_args}
environ = setup_environ()
environ.update(env)
start_response = mock.Mock()
result = app(environ, start_response)
start_response.assert_called_with(
'404 Not Found', [('Content-type', 'text/plain')])
"404 Not Found", [("Content-type", "text/plain")]
)

compare(result,
[b"Not Found ",
b"http://127.0.0.1/"])
compare(result, [b"Not Found ", b"http://127.0.0.1/"])
14 changes: 7 additions & 7 deletions webdispatch/tests/test_mixins.py
Expand Up @@ -10,6 +10,7 @@ class TestURLMapperMixin(object):
def _get_target():
""" get class under test """
from webdispatch.mixins import URLMapperMixin

return URLMapperMixin

def _make_one(self, *args, **kwargs):
Expand All @@ -20,19 +21,18 @@ def test_generate_url(self):
""" test generate_url """
target = self._make_one()
dummy_generator = mock.Mock()
dummy_generator.generate.return_value = 'generated'
target.environ = {'webdispatch.urlgenerator': dummy_generator}
result = target.generate_url('a', v1='1', v2='2')
dummy_generator.generate.return_value = "generated"
target.environ = {"webdispatch.urlgenerator": dummy_generator}
result = target.generate_url("a", v1="1", v2="2")

compare(result, 'generated')
dummy_generator.generate.assert_called_with(
'a', v1='1', v2='2')
compare(result, "generated")
dummy_generator.generate.assert_called_with("a", v1="1", v2="2")

def test_urlmapper(self):
""" test urlmapper property """
target = self._make_one()
dummy_generator = object()
target.environ = {'webdispatch.urlgenerator': dummy_generator}
target.environ = {"webdispatch.urlgenerator": dummy_generator}
result = target.urlmapper

compare(result, dummy_generator)

0 comments on commit e74a63e

Please sign in to comment.