Skip to content

Commit

Permalink
Merge pull request #58 from enter-at/fix/remove-context-update
Browse files Browse the repository at this point in the history
BREAKING CHANGE: The context option has been removed
  • Loading branch information
sleistner authored Aug 1, 2019
2 parents 5c58d2d + 29f71c3 commit d79deb8
Show file tree
Hide file tree
Showing 16 changed files with 54 additions and 110 deletions.
10 changes: 4 additions & 6 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
max_line_length = 80
max_line_length = 120

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml,json}]
[*.{yml, yaml, json}]
indent_size = 2

[Makefile]
indent_style = tab

[LICENSE]
insert_final_newline = none
trim_trailing_whitespace = none
indent_style = none
indent_size = none
insert_final_newline = false
trim_trailing_whitespace = false
6 changes: 1 addition & 5 deletions lambda_handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
InternalServerError,
)
from lambda_handlers.version import __version__ # noqa
from lambda_handlers.handlers import ( # noqa
HTTPHandler,
EventHandler,
LambdaHandler,
)
from lambda_handlers.handlers import HTTPHandler, EventHandler, LambdaHandler # noqa
from lambda_handlers.response import cors_headers, response_builder # noqa
from lambda_handlers.formatters import input_format, output_format # noqa
from lambda_handlers.validators import jsonschema, marshmallow # noqa
2 changes: 1 addition & 1 deletion lambda_handlers/handlers/event_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def validator(self) -> Validator:

def before(self, event, context):
"""Event hook called before the handler. It formats and validates `event`."""
return self.validate_event(self.format_input(event), context)
return self.validate_event(self.format_input(event)), context

def after(self, result):
"""Event method called after the handler. It formats and validates `result`."""
Expand Down
11 changes: 3 additions & 8 deletions lambda_handlers/handlers/http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@
from typing import Any, Dict

from lambda_handlers.types import Headers, APIGatewayProxyResult
from lambda_handlers.errors import (
FormatError,
NotFoundError,
BadRequestError,
ValidationError,
ResultValidationError,
)
from lambda_handlers.errors import FormatError, NotFoundError, BadRequestError, ValidationError, ResultValidationError
from lambda_handlers.response import CORSHeaders
from lambda_handlers.handlers.event_handler import EventHandler
from lambda_handlers.response.response_builder import (
Expand Down Expand Up @@ -96,7 +90,8 @@ def _create_headers(self, headers: Headers) -> Headers:

return headers or None

def _handle_error(self, error) -> APIGatewayProxyResult:
@staticmethod
def _handle_error(error) -> APIGatewayProxyResult:
if isinstance(error, NotFoundError):
return not_found(error.description)
if isinstance(error, ResultValidationError):
Expand Down
17 changes: 6 additions & 11 deletions lambda_handlers/handlers/lambda_handler.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""A base class for AWS Lambda handlers."""

from abc import ABC
from typing import Any, Dict, Tuple, Callable, Optional
from typing import Any, Dict, Tuple, NewType, Callable, Optional
from functools import wraps

Event = Dict[str, Any]
Context = Dict[str, Any]
LambdaContext = NewType('LambdaContext', object)


class LambdaHandler(ABC):
Expand All @@ -17,25 +17,20 @@ class LambdaHandler(ABC):
def __init__(self, handler: Optional[Callable] = None):
self._handler = handler

def __call__(self, handler: Callable):
"""Decorate `handler`."""
def __call__(self, handler: Callable): # noqa: D102
@wraps(handler)
def wrapper(event, context):
return self._call_handler(handler, event, context)

return wrapper

def _call_handler(
self,
handler: Callable,
event: Event,
context: Context,
) -> Any:
def _call_handler(self, handler: Callable, event: Event, context: LambdaContext) -> Any:
try:
return self.after(handler(*self.before(event, context)))
except Exception as exception:
return self.on_exception(exception)

def before(self, event: Event, context: Context) -> Tuple[Event, Context]:
def before(self, event: Event, context: LambdaContext) -> Tuple[Event, LambdaContext]:
"""Event method to be called just before the handler is executed."""
return event, context

Expand Down
8 changes: 3 additions & 5 deletions lambda_handlers/handlers/mixins/validation_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,12 @@ def validator(self):
"""Return the validator for events and results."""
pass

def validate_event(self, event, context):
def validate_event(self, event):
"""Validate the event with `self.validator`, return event and context."""
if self.validator:
transformed_event, transformed_context = self.validator.validate_event(event, context)
transformed_event = self.validator.validate_event(event)
event.update(transformed_event)
if context is not None:
context.update(transformed_context)
return event, context
return event

def validate_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
"""Validate and return the result with `self.validator`."""
Expand Down
4 changes: 2 additions & 2 deletions lambda_handlers/handlers/tests/test_lambda_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from lambda_handlers.handlers.lambda_handler import Context, LambdaHandler
from lambda_handlers.handlers.lambda_handler import LambdaContext, LambdaHandler

Event = Dict[str, Any]

Expand All @@ -14,7 +14,7 @@ def __init__(self, message: str, event: Event):


class CallOrderAwareHandler(LambdaHandler):
def before(self, event: Event, context: Context) -> Tuple[Event, Context]:
def before(self, event: Event, context: LambdaContext) -> Tuple[Event, LambdaContext]:
event['route'].append('before')
return super().before(event, context)

Expand Down
8 changes: 1 addition & 7 deletions lambda_handlers/response/response_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@
from typing import Any, Union

from lambda_handlers.types import APIGatewayProxyResult
from lambda_handlers.errors import (
LambdaError,
NotFoundError,
ForbiddenError,
BadRequestError,
InternalServerError,
)
from lambda_handlers.errors import LambdaError, NotFoundError, ForbiddenError, BadRequestError, InternalServerError


def ok(result: Any) -> APIGatewayProxyResult:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
"""A AWS HTTP event validator that uses Marshmallow."""

from lambda_handlers.validators.http.http_validator import HttpValidator
from lambda_handlers.validators.marshmallow_validator import (
MarshmallowValidator,
)
from lambda_handlers.validators.marshmallow_validator import MarshmallowValidator


class HttpMarshmallowValidator(MarshmallowValidator, HttpValidator):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

from lambda_handlers.validators.http.http_validator import HttpValidator
from lambda_handlers.validators.jsonschema_validator import JSONSchemaValidator
from lambda_handlers.validators.http.http_jsonschema_validator import (
HttpJSONSchemaValidator,
)
from lambda_handlers.validators.http.http_jsonschema_validator import HttpJSONSchemaValidator


@pytest.fixture(scope='session')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,8 @@

from lambda_handlers.errors import EventValidationError
from lambda_handlers.validators.http.http_validator import HttpValidator
from lambda_handlers.validators.marshmallow_validator import (
MarshmallowValidator,
)
from lambda_handlers.validators.http.http_marshmallow_validator import (
HttpMarshmallowValidator,
)
from lambda_handlers.validators.marshmallow_validator import MarshmallowValidator
from lambda_handlers.validators.http.http_marshmallow_validator import HttpMarshmallowValidator


class TestHttpMarshmallowSchemaValidator:
Expand Down Expand Up @@ -39,19 +35,16 @@ def test_validate_valid_request(self, subject):
'accountable': True,
},
}
context = {}
assert subject.validate_event(event, context)
assert subject.validate_event(event)

def test_validate_invalid_request(self, subject):
event = {
'pathParameters': {
'user_name': True,
},
}
context = {}

with pytest.raises(EventValidationError) as error:
subject.validate_event(event, context)
subject.validate_event(event)

nested_errors = error.value.description
assert isinstance(nested_errors, list)
Expand Down
31 changes: 11 additions & 20 deletions lambda_handlers/validators/http/tests/test_http_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ def subject(self, simple_schema_validator):

def test_validate_event(self, subject, mocker):
event = {}
context = {}
validate_spy = mocker.spy(subject, 'validate')
assert (event, context) == subject.validate_event(event, context)
assert event == subject.validate_event(event)
assert validate_spy.call_count == 0

def test_validate_result(self, subject, mocker):
Expand All @@ -46,21 +45,19 @@ def test_validate_valid_request(self, subject):
'accountable': True,
'comment': 'some comment',
}
context = {}
assert subject.validate_event(event, context)
assert subject.validate_event(event)

def test_validate_invalid_request(self, subject):
event = {
'price': '12',
'price': '13',
}
context = {}

with pytest.raises(EventValidationError) as error:
subject.validate_event(event, context)
subject.validate_event(event)

assert isinstance(error.value.description, list)
assert len(error.value.description) == 3
assert {'price': ['12 is not of type <class \'int\'>']} in error.value.description
assert {'price': ['13 is not of type <class \'int\'>']} in error.value.description
assert {'accountable': ['missing']} in error.value.description
assert {'comment': ['missing']} in error.value.description

Expand Down Expand Up @@ -113,19 +110,17 @@ def test_validate_valid_request(self, subject):
'accountable': True,
},
}
context = {}
assert subject.validate_event(event, context)
assert subject.validate_event(event)

def test_validate_invalid_request(self, subject):
event = {
'pathParameters': {
'user_name': True,
},
}
context = {}

with pytest.raises(EventValidationError) as error:
subject.validate_event(event, context)
subject.validate_event(event)

nested_errors = error.value.description
assert isinstance(nested_errors, list)
Expand Down Expand Up @@ -162,8 +157,7 @@ def test_validate_valid_request(self, subject):
'filter': 'a,b,c',
},
}
context = {}
assert subject.validate_event(event, context)
assert subject.validate_event(event)

def test_validate_invalid_request(self, subject):
event = {
Expand All @@ -174,10 +168,9 @@ def test_validate_invalid_request(self, subject):
'filter': 100,
},
}
context = {}

with pytest.raises(EventValidationError) as error:
subject.validate_event(event, context)
subject.validate_event(event)

nested_errors = error.value.description
assert isinstance(nested_errors, list)
Expand Down Expand Up @@ -230,8 +223,7 @@ def test_validate_valid_request(self, subject):
'content': 'some long text',
},
}
context = {}
assert subject.validate_event(event, context)
assert subject.validate_event(event)

def test_validate_invalid_request(self, subject):
event = {
Expand All @@ -242,10 +234,9 @@ def test_validate_invalid_request(self, subject):
'filter': 100,
},
}
context = {}

with pytest.raises(EventValidationError) as error:
subject.validate_event(event, context)
subject.validate_event(event)

nested_errors = error.value.description
assert isinstance(nested_errors, list)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
from marshmallow.validate import Range

from lambda_handlers.validators.validator import Validator
from lambda_handlers.validators.marshmallow_validator import (
MarshmallowValidator,
)
from lambda_handlers.validators.marshmallow_validator import MarshmallowValidator


class EventSchema(Schema):
Expand Down
Loading

0 comments on commit d79deb8

Please sign in to comment.