Skip to content

Commit

Permalink
Coverage.
Browse files Browse the repository at this point in the history
  • Loading branch information
jamadden committed Apr 27, 2017
1 parent 674be6f commit 10f8e50
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 153 deletions.
1 change: 1 addition & 0 deletions .coveragerc
Expand Up @@ -5,3 +5,4 @@ source = src
exclude_lines =
pragma: no cover
if __name__ == '__main__':
raise NotImplementedError
25 changes: 11 additions & 14 deletions src/zope/app/authentication/browser/granting.py
Expand Up @@ -42,8 +42,6 @@
except NameError:
text_type = str

import base64

settings_vocabulary = GrantVocabulary([
SimpleTerm(Allow, token="allow", title=_('Allow')),
SimpleTerm(Unset, token="unset", title=_('Unset')),
Expand Down Expand Up @@ -114,16 +112,12 @@ def renderSelectedItem(self, index, text, value, name, cssClass):
def renderItems(self, value):
# check if we want to select first item, the previously selected item
# or the "no value" item.
no_value = None
if (value == self.context.missing_value
and getattr(self, 'firstItem', False)
and len(self.vocabulary) > 0):
if self.context.required:
# Grab the first item from the iterator:
values = [iter(self.vocabulary).next().value]
else:
# the "no value" option will be checked
no_value = 'checked'
values = [next(iter(self.vocabulary)).value]
elif value != self.context.missing_value:
values = [value]
else:
Expand All @@ -150,6 +144,9 @@ class Granting(object):
def __init__(self, context, request):
self.context = context
self.request = request
self.permissions = None
self.roles = None
self.principal_widget = None

def status(self):
setUpWidget(self, 'principal', self.principal_field, IInputWidget)
Expand Down Expand Up @@ -181,7 +178,7 @@ def status(self):
vocabulary=settings_vocabulary)
setUpWidget(self, name, field, IInputWidget,
principal_roles.getSetting(role.id, principal))
self.roles.append(getattr(self, name+'_widget'))
self.roles.append(getattr(self, name + '_widget'))

perms = [perm for name, perm in getUtilitiesFor(IPermission)]
perms.sort(key=lambda x: x.title)
Expand All @@ -191,7 +188,7 @@ def status(self):
for perm in perms:
if perm.id == 'zope.Public':
continue
name = principal_token + '.permission.'+perm.id
name = principal_token + '.permission.' + perm.id
field = zope.schema.Choice(__name__=name,
title=perm.title,
vocabulary=settings_vocabulary)
Expand All @@ -204,12 +201,12 @@ def status(self):
return u''

for role in roles:
name = principal_token + '.role.'+role.id
role_widget = getattr(self, name+'_widget')
name = principal_token + '.role.' + role.id
role_widget = getattr(self, name + '_widget')
if role_widget.hasInput():
try:
setting = role_widget.getInputValue()
except MissingInputError:
except MissingInputError: # pragma: no cover
pass
else:
# Arrgh!
Expand All @@ -227,11 +224,11 @@ def status(self):
if perm.id == 'zope.Public':
continue
name = principal_token + '.permission.'+perm.id
perm_widget = getattr(self, name+'_widget')
perm_widget = getattr(self, name + '_widget')
if perm_widget.hasInput():
try:
setting = perm_widget.getInputValue()
except MissingInputError:
except MissingInputError: # pragma: no cover
pass
else:
# Arrgh!
Expand Down
19 changes: 12 additions & 7 deletions src/zope/app/authentication/browser/loginform.py
Expand Up @@ -13,30 +13,35 @@
##############################################################################
"""Login Form
$Id$
"""
from zope.authentication.interfaces import IUnauthenticatedPrincipal

class LoginForm(object):
"""Mix-in class to implement login form logic"""


context = None
request = None
unauthenticated = None
camefrom = None

def __call__(self):
request = self.request
principal = request.principal

unauthenticated = IUnauthenticatedPrincipal.providedBy(principal)
self.unauthenticated = unauthenticated

camefrom = request.get('camefrom')
if isinstance(camefrom, list):
if isinstance(camefrom, list): # pragma: no cover
# this can happen on python2.6, as it changed the
# behaviour of cgi.FieldStorage a bit.
# XXX: Just Python 2.6 or later too? Tests don't produce this.
camefrom = camefrom[0]
self.camefrom = camefrom
if (not unauthenticated) and ('SUBMIT' in request):

if not unauthenticated and 'SUBMIT' in request:
# authenticated by submitting
request.response.redirect(camefrom or '.')
return ''

return self.index() # call template
47 changes: 22 additions & 25 deletions src/zope/app/authentication/browser/rolepermissionview.py
Expand Up @@ -34,6 +34,11 @@ class RolePermissionView(object):
Roles are shown accross the top.
""")

request = None
context = None
_roles = None
_permissions = None

def pagetip(self):
return translate(self._pagetip, context=self.request)

Expand Down Expand Up @@ -68,10 +73,8 @@ def availableSettings(self, noacquire=False):
{'id': Deny.getName(), 'shorttitle': '-',
'title': _('permission-deny', 'Deny')},
]
if noacquire:
return rest
else:
return [aq]+rest

return rest if noacquire else [aq] + rest

def permissionRoles(self):
context = self.context.__parent__
Expand Down Expand Up @@ -113,7 +116,7 @@ def update(self, testing=None):
elif setting == Deny.getName():
prm.denyPermissionToRole(rperm, rrole)
else:
raise ValueError("Incorrect setting: %s" % setting)
raise ValueError("Incorrect setting: %s" % setting) # pragma: no cover
changed = True

if 'SUBMIT_PERMS' in self.request:
Expand Down Expand Up @@ -171,24 +174,21 @@ class PermissionRoles(object):

def __init__(self, permission, context, roles):
self._permission = permission
self._context = context
self._roles = roles
self._context = context
self._roles = roles

def _getId(self):
@property
def id(self):
return self._permission.id

id = property(_getId)

def _getTitle(self):
@property
def title(self):
return self._permission.title

title = property(_getTitle)

def _getDescription(self):
@property
def description(self):
return self._permission.description

description = property(_getDescription)

def roleSettings(self):
"""
Returns the list of setting names of each role for this permission.
Expand All @@ -209,21 +209,18 @@ def __init__(self, role, context, permissions):
self._context = context
self._permissions = permissions

def _getId(self):
@property
def id(self):
return self._role.id

id = property(_getId)

def _getTitle(self):
@property
def title(self):
return self._role.title

title = property(_getTitle)

def _getDescription(self):
@property
def description(self):
return self._role.description

description = property(_getDescription)

def permissionsInfo(self):
prm = IRolePermissionManager(self._context)
rperms = prm.getPermissionsForRole(self._role.id)
Expand Down
20 changes: 10 additions & 10 deletions src/zope/app/authentication/browser/schemasearch.py
Expand Up @@ -67,7 +67,7 @@ def render(self, name):
# start row for search fields
html.append('<div class="row">')

for field_name, field in getFieldsInOrder(schema):
for field_name, _field in getFieldsInOrder(schema):
widget = getattr(self, field_name+'_widget')

# for each field add label...
Expand All @@ -82,7 +82,7 @@ def render(self, name):
html.append(' <div class="field">')
html.append(' %s' % widget())

if widget.error():
if widget.error(): # pragma: no cover
html.append(' <div class="error">')
html.append(' %s' % widget.error())
html.append(' </div>')
Expand All @@ -105,22 +105,22 @@ def results(self, name):
if (name + '.search') not in self.request:
return None
schema = self.context.schema
setUpWidgets(self, schema, IInputWidget, prefix=name+'.field')
setUpWidgets(self, schema, IInputWidget, prefix=name + '.field')
# XXX inline the original getWidgetsData call in
# zope.app.form.utility to lift the dependency on zope.app.form.
data = {}
errors = []
for name, field in getFieldsInOrder(schema):
widget = getattr(self, name + '_widget')
for widget_name, field in getFieldsInOrder(schema):
widget = getattr(self, widget_name + '_widget')
if IInputWidget.providedBy(widget):
if widget.hasInput():
try:
data[name] = widget.getInputValue()
except InputErrors as error:
data[widget_name] = widget.getInputValue()
except InputErrors as error: # pragma: no cover
errors.append(error)
elif field.required:
elif field.required: # pragma: no cover
errors.append(MissingInputError(
name, widget.label, 'the field is required'))
if errors:
widget_name, widget.label, 'the field is required'))
if errors: # pragma: no cover
raise WidgetsError(errors, widgetsData=data)
return self.context.search(data)
20 changes: 5 additions & 15 deletions src/zope/app/authentication/browser/tests/rolepermissionmanager.py
Expand Up @@ -15,7 +15,7 @@
"""

from zope.interface import implementer
from zope.securitypolicy.interfaces import Allow, Deny, Unset
from zope.securitypolicy.interfaces import Allow, Deny
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.interfaces import IRolePermissionMap
from zope.securitypolicy.securitymap import SecurityMap
Expand Down Expand Up @@ -51,32 +51,22 @@ def getRolesForPermission(self, permission_id):
rp = self._getRolePermissions()
if rp:
return rp.getRow(permission_id)
else:
return []
raise NotImplementedError("Should never get here")

def getPermissionsForRole(self, role_id):
'''See interface IRolePermissionMap'''
rp = self._getRolePermissions()
if rp:
return rp.getCol(role_id)
else:
return []
raise NotImplementedError("Should never get here")

def getRolesAndPermissions(self):
'''See interface IRolePermissionMap'''
rp = self._getRolePermissions()
if rp:
return rp.getAllCells()
else:
return []
raise NotImplementedError("Not used by tests")

def getSetting(self, permission_id, role_id):
'''See interface IRolePermissionMap'''
rp = self._getRolePermissions()
if rp:
return rp.queryCell(permission_id, role_id)
else:
return Unset
raise NotImplementedError("Not used by tests")

def _getRolePermissions(self, create=0):
"""Get the role permission map stored in the context, optionally
Expand Down
44 changes: 21 additions & 23 deletions src/zope/app/authentication/browser/tests/test_doctests.py
Expand Up @@ -45,14 +45,12 @@ def setUp(self):

def publish(self, path, basic=None, form=None, headers=None):
assert basic
assert form
self._testapp.authorization = ('Basic', tuple(basic.split(':')))

env = {'wsgi.handleErrors': False}
if form:
response = self._testapp.post(path, params=form,
extra_environ=env, headers=headers)
else:
response = self._testapp.get(path, extra_environ=env, headers=headers)
response = self._testapp.post(path, params=form,
extra_environ=env, headers=headers)
return response

def getRootFolder(self):
Expand Down Expand Up @@ -85,15 +83,15 @@ def test_copypaste_duplicated_id_object(self):


# Try to paste the file
try:
response = self.publish('/pf/@@contents.html',
basic='mgr:mgrpw',
form={'container_paste_button': ''})
self.fail("Should raise exception")
except UserError as e:
self.assertIn("The given name(s)", str(e))
self.assertIn("p1", str(e))
self.assertIn("are already being used", str(e))
with self.assertRaises(UserError) as r:
self.publish('/pf/@@contents.html',
basic='mgr:mgrpw',
form={'container_paste_button': ''})

e = r.exception
self.assertIn("The given name(s)", str(e))
self.assertIn("p1", str(e))
self.assertIn("are already being used", str(e))

def test_cutpaste_duplicated_id_object(self):

Expand Down Expand Up @@ -122,15 +120,15 @@ def test_cutpaste_duplicated_id_object(self):


# Try to paste the file
try:
response = self.publish('/pf/@@contents.html',
basic='mgr:mgrpw',
form={'container_paste_button': ''})
self.fail("Should raise UserError")
except UserError as e:
self.assertIn("The given name(s)", str(e))
self.assertIn("p1", str(e))
self.assertIn("are already being used", str(e))
with self.assertRaises(UserError) as r:
self.publish('/pf/@@contents.html',
basic='mgr:mgrpw',
form={'container_paste_button': ''})

e = r.exception
self.assertIn("The given name(s)", str(e))
self.assertIn("p1", str(e))
self.assertIn("are already being used", str(e))


checker = renormalizing.RENormalizing([
Expand Down

0 comments on commit 10f8e50

Please sign in to comment.