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

Feature/support python35 #499

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
language: python
python:
- "2.7"
- "3.5"
# command to install dependencies
install:
- "pip install setuptools --upgrade; pip install -r test_requirements.txt; pip install -e git+https://github.com/django/django-contrib-comments.git#egg=django-contrib-comments; python setup.py install"
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ troposphere==1.9.0
Werkzeug==0.11.11
wheel==0.29.0
wsgi-request-logger==0.4.6
letsencrypt
2 changes: 1 addition & 1 deletion test_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
},
"extendo2": {
"extends": "extendo",
"s3_bucket": "lmbda2",
"s3_bucket": "lmbda2"
},
"depricated_remote_env": {
"s3_bucket": "lmbda",
Expand Down
78 changes: 61 additions & 17 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# -*- coding: utf8 -*-
from __future__ import absolute_import

import platform

import base64
import collections
import json
from contextlib import nested


import mock
import os
Expand All @@ -27,11 +31,15 @@
from zappa.wsgi import create_wsgi_request, common_log
from zappa.zappa import Zappa, ASSUME_POLICY, ATTACH_POLICY



def random_string(length):
return ''.join(random.choice(string.printable) for _ in range(length))


class TestZappa(unittest.TestCase):
python_version = '.'.join(platform.python_version_tuple()[:2])

def setUp(self):
self.sleep_patch = mock.patch('time.sleep', return_value=None)
# Tests expect us-east-1.
Expand Down Expand Up @@ -75,8 +83,9 @@ def test_copy_editable_packages(self, mock_remove, mock_find_packages):
temp_egg_link = os.path.join(temp_package_dir, 'package-python.egg-link')

z = Zappa()
with nested(
patch_open(), mock.patch('glob.glob'), mock.patch('zappa.zappa.copytree')
with (
patch_open(), mock.patch('glob.glob'), mock.patch(
'zappa.util.copytree')
) as ((mock_open, mock_file), mock_glob, mock_copytree):
# We read in the contents of the egg-link file
mock_file.read.return_value = "{}\n.".format(egg_path)
Expand All @@ -102,7 +111,8 @@ def test_create_lambda_package(self):
# mock the pip.get_installed_distributions() to include a package in lambda_packages so that the code
# for zipping pre-compiled packages gets called
mock_named_tuple = collections.namedtuple('mock_named_tuple', ['project_name'])
mock_return_val = [mock_named_tuple(lambda_packages.keys()[0])] # choose name of 1st package in lambda_packages
mock_return_val = [mock_named_tuple(list(lambda_packages.keys())[0])]
# choose name of 1st package in lambda_packages
with mock.patch('pip.get_installed_distributions', return_value=mock_return_val):
z = Zappa()
path = z.create_lambda_zip(handler_file=os.path.realpath(__file__))
Expand Down Expand Up @@ -366,8 +376,17 @@ def test_b64_pattern(self):
self.assertRegexpMatches(document, pattern)

for bad_code in ['200', '301', '302']:
document = base64.b64encode(head + bad_code + random_string(50))
self.assertNotRegexpMatches(document, pattern)
try:
document = base64.b64encode(head + bad_code +
random_string(50))
except TypeError:
document = base64.b64encode(str.encode(head + bad_code +
random_string(50)))
try:
self.assertNotRegexpMatches(document, pattern)
except TypeError:
self.assertNotRegexpMatches(bytes.decode(document),
pattern)

def test_200_pattern(self):
pattern = Zappa.selection_pattern('200')
Expand Down Expand Up @@ -618,7 +637,7 @@ def test_handler(self, session):
# Annoyingly, this will fail during record, but
# the result will actually be okay to use in playback.
# See: https://github.com/garnaat/placebo/issues/48
self.assertEqual(os.environ['hello'], 'world')
self.assertEqual(os.environ.get('hello'), 'world')

event = {
"body": {},
Expand Down Expand Up @@ -955,10 +974,17 @@ def test_cli_init(self):
# Via http://stackoverflow.com/questions/2617057/how-to-supply-stdin-files-and-environment-variable-inputs-to-python-unit-tests
inputs = ['dev', 'lmbda', 'test_settings', 'y', '']


def test_for(inputs):
input_generator = (i for i in inputs)
with mock.patch('__builtin__.raw_input', lambda prompt: next(input_generator)):
zappa_cli.init()
if int(self.python_version[0]) < 3:
with mock.patch('__builtin__.input', lambda prompt: next(input_generator)):
zappa_cli.init()
else:
with mock.patch('builtins.input', lambda prompt: next(
input_generator)):
zappa_cli.init()


if os.path.isfile('zappa_settings.json'):
os.remove('zappa_settings.json')
Expand All @@ -973,10 +999,17 @@ def test_for(inputs):

# Test via handle()
input_generator = (i for i in inputs)
with mock.patch('__builtin__.raw_input', lambda prompt: next(input_generator)):
zappa_cli = ZappaCLI()
argv = ['init']
zappa_cli.handle(argv)
if int(self.python_version[0]) < 3:
with mock.patch('__builtin__.input', lambda prompt: next(input_generator)):
zappa_cli = ZappaCLI()
argv = ['init']
zappa_cli.handle(argv)
else:
with mock.patch('builtins.input', lambda prompt: next(
input_generator)):
zappa_cli = ZappaCLI()
argv = ['init']
zappa_cli.handle(argv)

if os.path.isfile('zappa_settings.json'):
os.remove('zappa_settings.json')
Expand Down Expand Up @@ -1200,8 +1233,10 @@ def test_dj_wsgi(self):

app = get_django_wsgi('dj_test_settings')
os.remove('dj_test_settings.py')
os.remove('dj_test_settings.pyc')

try:
os.remove('dj_test_settings.pyc')
except:
pass
##
# Util / Misc
##
Expand Down Expand Up @@ -1288,7 +1323,11 @@ def test_remote_env_package(self):
with zipfile.ZipFile(zappa_cli.zip_path, 'r') as lambda_zip:
content = lambda_zip.read('zappa_settings.py')
zappa_cli.remove_local_zip()
m = re.search("REMOTE_ENV='(.*)'", content)
try:
m = re.search("REMOTE_ENV='(.*)'", content)
except TypeError:
m = re.search("REMOTE_ENV='(.*)'", bytes.decode(content))

self.assertEqual(m.group(1), 's3://lmbda-env/dev/env.json')

zappa_cli = ZappaCLI()
Expand All @@ -1299,7 +1338,12 @@ def test_remote_env_package(self):
with zipfile.ZipFile(zappa_cli.zip_path, 'r') as lambda_zip:
content = lambda_zip.read('zappa_settings.py')
zappa_cli.remove_local_zip()
m = re.search("REMOTE_ENV='(.*)'", content)
try:

m = re.search("REMOTE_ENV='(.*)'", content)
except:
m = re.search("REMOTE_ENV='(.*)'", bytes.decode(content))

self.assertEqual(m.group(1), 's3://lmbda-env/prod/env.json')


Expand Down
37 changes: 24 additions & 13 deletions tests/tests_middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import print_function
import unittest
import base58
import json
Expand All @@ -8,6 +10,7 @@

from zappa.wsgi import create_wsgi_request
from zappa.middleware import ZappaWSGIMiddleware
import six


class TestWSGIMockMiddleWare(unittest.TestCase):
Expand Down Expand Up @@ -213,9 +216,12 @@ def simple_app(environ, start_response):
self.assertEqual(''.join(resp), body)

def test_wsgi_middleware_uglystring(self):
ugly_string = unicode("˝ÓÔÒÚÆ☃ЗИЙКЛМФХЦЧШ차를 타고 온 펲시맨(╯°□°)╯︵ ┻━┻)"
"לֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָt͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨ 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨",
encoding='utf8')
try:
ugly_string = unicode("˝ÓÔÒÚÆ☃ЗИЙКЛМФХЦЧШ차를 타고 온 펲시맨(╯°□°)╯︵ ┻━┻)"
"לֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָt͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨ 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨")
except:
ugly_string = "˝ÓÔÒÚÆ☃ЗИЙКЛМФХЦЧШ차를 타고 온 펲시맨(╯°□°)╯︵ ┻━┻)" + \
"לֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָt͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨ 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨"

# Pass some unicode through the middleware body
def simple_app(environ, start_response):
Expand All @@ -230,7 +236,7 @@ def simple_app(environ, start_response):

# Call with empty WSGI Environment
resp = app(dict(), self._start_response)
print(''.join(resp))
print((''.join(resp)))

# Pass some unicode through the middleware headers
def simple_app(environ, start_response):
Expand All @@ -245,7 +251,7 @@ def simple_app(environ, start_response):

# Call with empty WSGI Environment
resp = app(dict(), self._start_response)
print(''.join(resp))
print((''.join(resp)))

def test_wsgi_middleware_expiry(self):
# Setting the cookies
Expand Down Expand Up @@ -376,7 +382,7 @@ def test_wsgi_middleware_realcall(self):

def set_cookies(environ, start_response):
status = '200 OK'
print environ
print(environ)
response_headers = [('Set-Cookie', 'foo=123'),
('Set-Cookie', 'bar=456'),
('Set-Cookie', 'baz=789')]
Expand Down Expand Up @@ -445,7 +451,7 @@ def set_cookies(environ, start_response):

def change_cookie(environ, start_response):
status = '200 OK'
print 'environ', environ
print('environ', environ)
response_headers = [('Set-Cookie', 'foo=new_value')]
start_response(status, response_headers)
return ['Set cookies!']
Expand All @@ -459,10 +465,15 @@ def change_cookie(environ, start_response):
self.assertEqual(len(zappa_cookie), 1)
zappa_cookie1 = zappa_cookie[0]
self.assertTrue(zappa_cookie1.startswith('zappa='))

zdict = parse_cookie(zappa_cookie1)
print 'zdict', zdict
zdict2 = json.loads(base58.b58decode(zdict['zappa']))
print 'zdict2', zdict2
print('zdict', zdict)
try:
zdict2 = json.loads(base58.b58decode(zdict['zappa']))
except TypeError:
zdict2 = json.loads(bytes.decode(base58.b58decode(zdict['zappa'])))

print('zdict2', zdict2)
self.assertEqual(len(zdict2), 3)
self.assertEqual(zdict2['foo'], 'new_value')
self.assertEqual(zdict2['bar'], '456')
Expand All @@ -476,7 +487,7 @@ def change_cookie(environ, start_response):

def read_cookies(environ, start_response):
status = '200 OK'
print 'environ', environ
print('environ', environ)
response_headers = []
start_response(status, response_headers)
return [environ['HTTP_COOKIE']]
Expand All @@ -487,14 +498,14 @@ def read_cookies(environ, start_response):
trailing_slash=False)

response = Response.from_app(app, environ)
print "response", response
print("response", response)
# Filter the headers for Set-Cookie header
zappa_cookie = [x[1] for x in response.headers if x[0] == 'Set-Cookie']
self.assertEqual(len(zappa_cookie), 1)
zappa_cookie1 = zappa_cookie[0]
self.assertTrue(zappa_cookie1.startswith('zappa='))
zdict = parse_cookie(zappa_cookie1)
print 'zdict', zdict
print('zdict', zdict)
cookies = json.loads(base58.b58decode(zdict['zappa']))
self.assertEqual(cookies['foo'], 'new_value')
self.assertEqual(cookies['bar'], '456')
Expand Down
20 changes: 16 additions & 4 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import platform

import placebo
import boto3
import os
import functools
from contextlib import contextmanager

from mock import patch, MagicMock

PLACEBO_DIR = os.path.join(os.path.dirname(__file__), 'placebo')
Expand Down Expand Up @@ -59,13 +62,22 @@ def patch_open():
yielded.
Yields the mock for "open" and "file", respectively."""
mock_open = MagicMock(spec=open)
mock_file = MagicMock(spec=file)

try:
mock_file = MagicMock(spec=file)
except NameError:
mock_file = MagicMock(spec=open)
@contextmanager
def stub_open(*args, **kwargs):
mock_open(*args, **kwargs)
yield mock_file

with patch('__builtin__.open', stub_open):
yield mock_open, mock_file
python_version = '.'.join(platform.python_version_tuple()[:2])

if int(python_version[0]) < 3:

with patch('__builtin__.open', stub_open):
yield mock_open, mock_file
else:
with patch('builtins.open', stub_open):
yield mock_open, mock_file

Loading