Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for case insensitve header names #398

Merged
merged 6 commits into from
May 21, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion samcli/local/apigw/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@
LOG = logging.getLogger(__name__)


class CaseInsensitiveDict(dict):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add tests for this class. It will help me (and others) understanding the application of this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a test in tests/functional/local/apigw/test_service.py

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have both unit and functional. We need to make sure we are unit testing everything. The CodeCoverage show branch 22-23 missing and we are not really testing the other paths, it just so happens we execute those paths by creating the object. Ideally, we would mock out this class in the other tests, and then add explicit tests for this class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added unit tests to tests/functional/local/apigw/test_service.py you should now have full code coverage of this class.

"""
Implement a simple case insensitive dictionary for storing headers. To preserve the original
case of the given Header (e.g. X-FooBar-Fizz) this only touches the get and contains magic
methods rather than implementing a __setitem__ where we normalize the case of the headers.
"""

def __getitem__(self, key):
matches = [v for k, v in self.items() if k.lower() == key.lower()]
if not matches:
raise KeyError(key)
return matches[0]

def __contains__(self, key):
return key.lower() in [k.lower() for k in self.keys()]


class Route(object):

def __init__(self, methods, function_name, path, binary_types=None):
Expand Down Expand Up @@ -270,7 +287,7 @@ def _parse_lambda_output(lambda_output, binary_types, flask_request):
raise TypeError("Lambda returned %{s} instead of dict", type(json_output))

status_code = json_output.get("statusCode") or 200
headers = json_output.get("headers") or {}
headers = CaseInsensitiveDict(json_output.get("headers") or {})
body = json_output.get("body") or "no data"
is_base_64_encoded = json_output.get("isBase64Encoded") or False

Expand Down
9 changes: 9 additions & 0 deletions tests/functional/function_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@
}
"""

API_GATEWAY_CONTENT_TYPE_LOWER = """
exports.handler = function(event, context, callback){
body = JSON.stringify("hello")

response = {"statusCode":200,"headers":{"content-type":"text/plain"},"body":body,"isBase64Encoded":false}
context.done(null, response);
}
"""

API_GATEWAY_ECHO_BASE64_EVENT = """
exports.base54request = function(event, context, callback){

Expand Down
83 changes: 81 additions & 2 deletions tests/functional/local/apigw/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import random
from mock import Mock

from samcli.local.apigw.service import Route, Service
from tests.functional.function_code import nodejs_lambda, API_GATEWAY_ECHO_EVENT, API_GATEWAY_BAD_PROXY_RESPONSE, API_GATEWAY_ECHO_BASE64_EVENT
from samcli.local.apigw.service import Route, Service, CaseInsensitiveDict
from tests.functional.function_code import nodejs_lambda, API_GATEWAY_ECHO_EVENT, API_GATEWAY_BAD_PROXY_RESPONSE, API_GATEWAY_ECHO_BASE64_EVENT, API_GATEWAY_CONTENT_TYPE_LOWER
from samcli.commands.local.lib import provider
from samcli.local.lambdafn.runtime import LambdaRuntime
from samcli.commands.local.lib.local_lambda import LocalLambdaRunner
Expand Down Expand Up @@ -63,6 +63,58 @@ def test_non_proxy_response(self):
self.assertEquals(response.headers.get('Content-Type'), "application/json")


class TestService_ContentType(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_CONTENT_TYPE_LOWER)

# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD

cls.function_name = "name"

cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None)

cls.base64_response_function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None)

cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function

list_of_routes = [
Route(['GET'], cls.function_name, '/'),
]

cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()

@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)

def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None

def test_calling_service_root(self):
expected = "hello"

response = requests.get(self.url)

actual = response.json()

self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('content-type'), "text/plain")


class TestService_EventSerialization(TestCase):
@classmethod
def setUpClass(cls):
Expand Down Expand Up @@ -450,6 +502,33 @@ def test_post_binary_with_incorrect_content_type(self):
self.assertEquals(response.headers.get('Content-Type'), "application/json")


class TestService_CaseInsensiveDict(TestCase):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unit tests should go in the tests/unit/local/apigw/test_service.py not in the tests/functional. Can you move this to the correct folder/file?

def test_contains(self):
data = CaseInsensitiveDict({
'Content-Type': 'text/html',
'Browser': 'APIGW',
})

self.assertTrue('content-type' in data)
self.assertTrue('Content-Type' in data)
self.assertTrue('CONTENT-TYPE' in data)
self.assertTrue('Browser' in data)
self.assertTrue('Dog-Food' not in data)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We try and keep unit tests to only one assert as much as possible. There are always exceptions but generally if you are testing two different cases, even if they are related, you should split them out into different tests.

Unit tests are cheep and fast. While this seems very much copy-paste, it leads to better isolated tests in overall. The main advantage here is when you make code changes that impact multiple asserts. When chaining asserts like this in one test, the test will fail when the first assert fails. This gives no indication of the bigger picture and state of your system. Devs following TDD constantly run unit test and rely heavily on this idea. I should be able to run the tests and see/understand everything that went wrong.

You can very easily parameterize this and the following function to achieve this. Here is an example how we are doing this already: https://github.com/awslabs/aws-sam-cli/blob/develop/tests/unit/local/apigw/test_service.py#L520


def test_getitem(self):
data = CaseInsensitiveDict({
'Content-Type': 'text/html'
})
data['Browser'] = 'APIGW'

self.assertTrue(data['content-type'])
self.assertTrue(data['Content-Type'])
self.assertTrue(data['CONTENT-TYPE'])
self.assertTrue(data['browser'])
with self.assertRaises(KeyError):
data['does-not-exist']


def make_service(list_of_routes, function_provider, cwd):
port = random_port()
manager = ContainerManager()
Expand Down