Skip to content

Commit

Permalink
Merge pull request #267 from mozilla-services/flake8
Browse files Browse the repository at this point in the history
Flake8 pass.
  • Loading branch information
almet committed Jan 28, 2015
2 parents bbf18f9 + 5eb0c84 commit 9588123
Show file tree
Hide file tree
Showing 21 changed files with 171 additions and 121 deletions.
2 changes: 1 addition & 1 deletion cornice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def includeme(config):
# attributes required to maintain services
config.registry.cornice_services = {}

#config.add_directive('add_apidoc', add_apidoc)
# config.add_directive('add_apidoc', add_apidoc)
config.add_directive('add_cornice_service', register_service_views)
config.add_directive('add_cornice_deserializer', add_deserializer)
config.add_subscriber(add_renderer_globals, BeforeRender)
Expand Down
11 changes: 6 additions & 5 deletions cornice/cors.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _preflight_view(request):
supported_headers = set(supported_headers) | set(requested_headers)

response.headers['Access-Control-Allow-Headers'] = (
','.join(supported_headers))
','.join(supported_headers))

response.headers['Access-Control-Allow-Methods'] = (
','.join(service.cors_supported_methods))
Expand All @@ -65,7 +65,7 @@ def _preflight_view(request):
if max_age is not None:
response.headers['Access-Control-Max-Age'] = str(max_age)

return {}
return None
return _preflight_view


Expand Down Expand Up @@ -96,7 +96,8 @@ def ensure_origin(service, request, response=None):
for o in service.cors_origins_for(method)]):
request.errors.add('header', 'Origin',
'%s not allowed' % origin)
elif request.headers.get('Access-Control-Allow-Credentials', False):
elif request.headers.get(
'Access-Control-Allow-Credentials', False):
response.headers['Access-Control-Allow-Origin'] = origin
else:
if any([o == "*" for o in service.cors_origins_for(method)]):
Expand All @@ -121,14 +122,14 @@ def apply_cors_post_request(service, request, response):
method = _get_method(request)

if (service.cors_support_credentials(method) and
not 'Access-Control-Allow-Credentials' in response.headers):
'Access-Control-Allow-Credentials' not in response.headers):
response.headers['Access-Control-Allow-Credentials'] = 'true'

if request.method is not 'OPTIONS':
# Which headers are exposed?
supported_headers = service.cors_supported_headers
if supported_headers:
response.headers['Access-Control-Expose-Headers'] = (
', '.join(supported_headers))
', '.join(supported_headers))

return response
8 changes: 5 additions & 3 deletions cornice/ext/sphinxext.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

MODULES = {}


def convert_to_list(argument):
"""Convert a comma separated list into a list of python values"""
if argument is None:
Expand Down Expand Up @@ -61,7 +62,8 @@ def __init__(self, *args, **kwargs):
self.env = self.state.document.settings.env

def run(self):
# clear the SERVICES variable, which will allow to use this directive multiple times
# clear the SERVICES variable, which will allow to use this
# directive multiple times
clear_services()

# import the modules, which will populate the SERVICES variable.
Expand Down Expand Up @@ -95,7 +97,7 @@ def _render_service(self, service):

for method, view, args in service.definitions:
if method == 'HEAD':
#Skip head - this is essentially duplicating the get docs.
# Skip head - this is essentially duplicating the get docs.
continue
method_id = '%s-%s' % (service_id, method)
method_node = nodes.section(ids=[method_id])
Expand All @@ -117,7 +119,7 @@ def _render_service(self, service):
attributes = schema.get_attributes(location=location)
if attributes:
attrs_node += nodes.inline(
text='values in the %s' % location)
text='values in the %s' % location)
location_attrs = nodes.bullet_list()

for attr in attributes:
Expand Down
2 changes: 1 addition & 1 deletion cornice/ext/spore.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def generate_spore_description(services, name, base_url, version, **kwargs):
# we have the values, but we need to merge this with
# possible previous values for this method.
method_name = '{method}_{service}'.format(
method=method.lower(), service=service.name.lower())
method=method.lower(), service=service.name.lower())
spore_doc['methods'][method_name] = view_info

return spore_doc
19 changes: 11 additions & 8 deletions cornice/pyramidhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ def _fallback_view(request):

if 'accept' in args:
acceptable.extend(
service.get_acceptable(method, filter_callables=True))
service.get_acceptable(method, filter_callables=True))
acceptable.extend(
request.info.get('acceptable', []))
request.info.get('acceptable', []))
acceptable = list(set(acceptable))

# Now check if that was actually the source of the problem.
Expand All @@ -76,10 +76,10 @@ def _fallback_view(request):

if 'content_type' in args:
supported_contenttypes.extend(
service.get_contenttypes(method,
filter_callables=True))
service.get_contenttypes(method,
filter_callables=True))
supported_contenttypes.extend(
request.info.get('supported_contenttypes', []))
request.info.get('supported_contenttypes', []))
supported_contenttypes = list(set(supported_contenttypes))

# Now check if that was actually the source of the problem.
Expand Down Expand Up @@ -256,7 +256,8 @@ def _pop_complex_predicates(args):
product_input = filter(None, [accept_list, content_type_list])

# In Python 3, the filter() function returns an iterator, not a list.
# http://getpython3.com/diveintopython3/porting-code-to-python-3-with-2to3.html#filter
# http://getpython3.com/diveintopython3/ \
# porting-code-to-python-3-with-2to3.html#filter
predicate_product = list(filter(None, itertools.product(*product_input)))

return predicate_product
Expand All @@ -270,7 +271,8 @@ def _pop_predicate_definition(args, kind):
values = to_list(args.pop(kind, ()))
# In much the same way as filter(), the map() function [in Python 3] now
# returns an iterator. (In Python 2, it returned a list.)
# http://getpython3.com/diveintopython3/porting-code-to-python-3-with-2to3.html#map
# http://getpython3.com/diveintopython3/ \
# porting-code-to-python-3-with-2to3.html#map
values = list(map(lambda value: {'kind': kind, 'value': value}, values))
return values

Expand Down Expand Up @@ -307,7 +309,8 @@ def _mungle_view_args(args, predicate_list):
predicates.append(predicate_checker)
args['custom_predicates'] = predicates
else:
raise ValueError('No function defined for ' +
raise ValueError(
'No function defined for ' +
'handling callables for field "{0}"'.format(kind))
else:
# otherwise argument value is just a scalar
Expand Down
5 changes: 3 additions & 2 deletions cornice/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def wrapper(klass):
if views:
for view_args in views:
service.add_view(verb, view_attr, klass=klass,
**view_args)
**view_args)
else:
service.add_view(verb, view_attr, klass=klass)

Expand All @@ -77,7 +77,8 @@ def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_cornice_service(service)

info = venusian.attach(klass, callback, category='pyramid', depth=depth)
info = venusian.attach(klass, callback, category='pyramid',
depth=depth)
return klass
return wrapper

Expand Down
7 changes: 4 additions & 3 deletions cornice/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def as_dict(self):
"""returns a dict containing keys for the different attributes, and
for each of them, a dict containing information about them::
>>> schema.as_dict()
>>> schema.as_dict() # NOQA
{'foo': {'type': 'string',
'location': 'body',
'description': 'yeah',
Expand Down Expand Up @@ -109,13 +109,14 @@ def _validate_fields(location, data):

for attr in schema.get_attributes(location=location,
request=request):
if attr.required and not attr.name in data and attr.default == null:
if attr.required and attr.name not in data and \
attr.default == null:
# missing
request.errors.add(location, attr.name,
"%s is missing" % attr.name)
else:
try:
if not attr.name in data:
if attr.name not in data:
if attr.default != null:
deserialized = attr.deserialize(attr.serialize())
else:
Expand Down
15 changes: 8 additions & 7 deletions cornice/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ class Service(object):
A service is composed of a path and many potential methods, associated
with context.
All the class attributes defined in this class or in children are considered
default values.
All the class attributes defined in this class or in children are
considered default values.
:param name:
The name of the service. Should be unique among all the services.
Expand Down Expand Up @@ -234,9 +234,10 @@ def get_arguments(self, conf=None):
arguments[arg] = conf.pop(arg, getattr(self, arg, None))

for arg in self.list_arguments:
# rather than overwriting, extend the defined lists if any.
# take care of re-creating the lists before appending items to them,
# to avoid modifications to the already existing ones
# rather than overwriting, extend the defined lists if
# any. take care of re-creating the lists before appending
# items to them, to avoid modifications to the already
# existing ones
value = list(getattr(self, arg, []))
if arg in conf:
value.extend(to_list(conf.pop(arg)))
Expand Down Expand Up @@ -278,8 +279,8 @@ def add_view(self, method, view, **kwargs):
can be overwritten here. Additionally,
:meth:`~cornice.service.Service.api` has following keyword params:
:param method: The request method. Should be one of 'GET', 'POST', 'PUT',
'DELETE', 'OPTIONS', 'TRACE', or 'CONNECT'.
:param method: The request method. Should be one of 'GET', 'POST',
'PUT', 'DELETE', 'OPTIONS', 'TRACE', or 'CONNECT'.
:param view: the view to hook to
:param **kwargs: additional configuration for this view,
including `permission`.
Expand Down
8 changes: 4 additions & 4 deletions cornice/tests/ext/test_spore.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ def post_coffees(request):

services = get_services(names=('coffee', 'Coffees'))
spore = generate_spore_description(
services, name="oh yeah",
base_url="http://localhost/", version="1.0")
services, name="oh yeah",
base_url="http://localhost/", version="1.0")

# basic fields
self.assertEqual(spore['name'], "oh yeah")
Expand Down Expand Up @@ -77,8 +77,8 @@ def test_rxjson_spore(self):

services = get_services(names=('coffee', 'Coffees'))
spore = generate_spore_description(
services, name="oh yeah",
base_url="http://localhost/", version="1.0")
services, name="oh yeah",
base_url="http://localhost/", version="1.0")

with open(os.path.join(HERE, 'spore_validation.rx')) as f:
spore_json_schema = json.loads(f.read())
Expand Down
1 change: 1 addition & 0 deletions cornice/tests/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def __repr__(self):

class DummyRequest(testing.DummyRequest):
errors = []

def __init__(self, *args, **kwargs):
super(DummyRequest, self).__init__(*args, **kwargs)
self.context = DummyContext()
Expand Down
71 changes: 37 additions & 34 deletions cornice/tests/test_cors.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,15 @@ def test_preflight_cors_klass_post(self):
headers={
'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'POST'})
self.assertEqual('POST,OPTIONS', dict(resp.headers)['Access-Control-Allow-Methods'])
self.assertEqual('POST,OPTIONS',
dict(resp.headers)['Access-Control-Allow-Methods'])

def test_preflight_cors_klass_put(self):
resp = self.app.options('/cors_klass',
status=400,
headers={
'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'PUT'})
self.app.options('/cors_klass',
status=400,
headers={
'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'PUT'})

def test_preflight_missing_headers(self):
# we should have an OPTION method defined.
Expand Down Expand Up @@ -170,36 +171,35 @@ def test_preflight_correct_origin(self):

def test_preflight_deactivated_method(self):
self.app.options('/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'},
status=400)
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'},
status=400)

def test_preflight_origin_not_allowed_for_method(self):
self.app.options('/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'PUT'},
status=400)
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'PUT'},
status=400)

def test_preflight_credentials_are_supported(self):
resp = self.app.options('/spam',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})

resp = self.app.options(
'/spam', headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})
self.assertIn('Access-Control-Allow-Credentials', resp.headers)
self.assertEqual(resp.headers['Access-Control-Allow-Credentials'],
'true')
'true')

def test_preflight_credentials_header_not_included_when_not_needed(self):
resp = self.app.options('/spam',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'})
resp = self.app.options(
'/spam', headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'})

self.assertNotIn('Access-Control-Allow-Credentials', resp.headers)

def test_preflight_contains_max_age(self):
resp = self.app.options('/spam',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})
resp = self.app.options(
'/spam', headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})

self.assertIn('Access-Control-Max-Age', resp.headers)
self.assertEqual(resp.headers['Access-Control-Max-Age'], '42')
Expand Down Expand Up @@ -227,19 +227,20 @@ def test_origin_is_not_wildcard_if_allow_credentials(self):
'Access-Control-Request-Method': 'POST',
'Access-Control-Allow-Credentials': 'true'
})
self.assertEqual(resp.headers['Access-Control-Allow-Origin'], 'lolnet.org')
self.assertEqual(resp.headers['Access-Control-Allow-Origin'],
'lolnet.org')

def test_responses_include_an_allow_origin_header(self):
resp = self.app.get('/squirel', headers={'Origin': 'notmyidea.org'})
self.assertIn('Access-Control-Allow-Origin', resp.headers)
self.assertEqual(resp.headers['Access-Control-Allow-Origin'],
'notmyidea.org')
'notmyidea.org')

def test_credentials_are_included(self):
resp = self.app.get('/spam', headers={'Origin': 'notmyidea.org'})
self.assertIn('Access-Control-Allow-Credentials', resp.headers)
self.assertEqual(resp.headers['Access-Control-Allow-Credentials'],
'true')
'true')

def test_headers_are_exposed(self):
resp = self.app.get('/squirel', headers={'Origin': 'notmyidea.org'})
Expand All @@ -249,10 +250,11 @@ def test_headers_are_exposed(self):
self.assertIn('X-My-Header', headers)

def test_preflight_request_headers_are_included(self):
resp = self.app.options('/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'foo, bar,baz '})
resp = self.app.options(
'/squirel', headers={
'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'foo, bar,baz '})
# The specification says we can have any number of LWS (Linear white
# spaces) in the values and that it should be removed.

Expand All @@ -264,10 +266,11 @@ def test_preflight_request_headers_are_included(self):
self.assertIn('baz', headers)

def test_preflight_request_headers_isnt_too_permissive(self):
self.app.options('/eggs',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'foo,bar,baz'},
self.app.options(
'/eggs', headers={
'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'foo,bar,baz'},
status=400)

def test_preflight_headers_arent_case_sensitive(self):
Expand Down

0 comments on commit 9588123

Please sign in to comment.