Author: chrisz
Date: Tue Jan 18 07:22:04 2011
New Revision: 7210
URL: http://trac.turbogears.org/changeset/7210
Log:
Refactored visit/identity tests in ORM dependent and independent parts (see
#1453).
Added:
branches/1.5/turbogears/identity/tests/test_identity.py
branches/1.5/turbogears/identity/tests/test_visit.py
Modified:
branches/1.5/turbogears/identity/tests/test_identity_sa.py
branches/1.5/turbogears/identity/tests/test_identity_so.py
branches/1.5/turbogears/identity/tests/test_visit_sa.py
branches/1.5/turbogears/identity/tests/test_visit_so.py
branches/1.5/turbogears/identity/visitor.py
Added: branches/1.5/turbogears/identity/tests/test_identity.py
==============================================================================
--- /dev/null 00:00:00 1970 (empty, because file is newly added)
+++ branches/1.5/turbogears/identity/tests/test_identity.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -0,0 +1,277 @@
+# -*- coding: UTF-8 -*-
+
+"""ORM independent Identity tests and test controllers."""
+
+import unittest
+
+import formencode
+import cherrypy
+
+from turbogears import identity, expose
+from turbogears.controllers import Controller, RootController
+from turbogears.identity import (SecureObject, SecureResource,
+ in_group, in_all_groups, in_any_group, not_anonymous,
+ has_permission, has_all_permissions, has_any_permission,
+ from_host, from_any_host, Any, All, NotAny)
+from turbogears.identity.conditions import _remoteHost
+from turbogears.identity.exceptions import RequestRequiredException
+
+
+def mycustomencrypt(password):
+ """A custom password encryption function."""
+ return password + '_custom'
+
+
+class MockIdentity(object):
+ """Identity mock object."""
+
+ anonymous = False
+ groups = ('admin', 'edit')
+ permissions = ('read', 'write')
+
+mock_identity = MockIdentity()
+
+
+class TestPredicates(unittest.TestCase):
+
+ def met(self, predicate):
+ return predicate.eval_with_object(mock_identity)
+
+ def test_in_group(self):
+ """Test the predicate for requiring a group."""
+ assert self.met(in_group('admin'))
+ assert not self.met(in_group('guest'))
+
+ def test_in_all_groups(self):
+ """Test the predicate for requiring a number of group."""
+ assert self.met(in_all_groups('admin', 'edit'))
+ assert not self.met(in_all_groups('admin', 'guest', 'edit'))
+
+ def test_in_any_group(self):
+ """Test the predicate for requiring at least one group."""
+ assert self.met(in_any_group('guest', 'edit', 'user'))
+ assert not self.met(in_all_groups('guest', 'user'))
+
+ def test_anonymous(self):
+ """Test predicate for checking anonymous visitors."""
+ assert self.met(not_anonymous())
+
+ def test_has_permission(self):
+ """Test predicate for checking particular permissions."""
+ assert self.met(has_permission('read'))
+ assert not self.met(has_permission('delete'))
+
+ def test_has_all_permissions(self):
+ """Test the predicate for requiring a number of permissions."""
+ assert self.met(has_all_permissions('read', 'write'))
+ assert not self.met(has_all_permissions('read', 'delete', 'write'))
+
+ def test_has_any_permission(self):
+ """Test the predicate for requiring at least one permission."""
+ assert self.met(has_any_permission('delete', 'write', 'update'))
+ assert not self.met(has_any_permission('delete', 'update'))
+
+ def test_any(self):
+ """Test the Any predicate."""
+ yes = in_group('edit')
+ no1, no2 = in_group('guest'), in_group('user')
+ met = self.met
+ assert met(Any(yes))
+ assert not met(Any(no1, no2))
+ assert met(Any(no1, yes, no2))
+
+ def test_all(self):
+ """Test the All predicate."""
+ yes1, yes2 = in_group('admin'), in_group('edit')
+ no = in_group('guest')
+ met = self.met
+ assert not met(All(no))
+ assert met(All(yes1, yes2))
+ assert not met(All(yes1, no, yes2))
+
+ def test_not_any(self):
+ """Test the Not Any predicate."""
+ yes = in_group('edit')
+ no1, no2 = in_group('guest'), in_group('user')
+ met = self.met
+ assert not met(NotAny(yes))
+ assert met(NotAny(no1, no2))
+ assert not met(NotAny(no1, yes, no2))
+
+ def test_remote_host_request_required(self):
+ """Test that _remoteHost raises exception when request is not
available.
+ """
+ self.assertRaises(RequestRequiredException, _remoteHost)
+
+
+class TestSecureObject(unittest.TestCase):
+
+ def test_secure_object_proxies_cp_attributes(self):
+ """Test that SecureObject properly proxies CherryPy (_cp)
attributes."""
+
+ test_config = {'request.methods_with_bodies': ('POST', 'PUT')}
+
+ class TestObject(object):
+ _cp_config = test_config
+
+ test_object = SecureObject(TestObject(), None)
+ assert test_object._cp_config == test_config
+
+ test_object = SecureObject(RootController(), None)
+ test_object._cp_config = test_config
+ assert test_object._cp_config == test_config
+
+
+class RestrictedArea(Controller, SecureResource):
+
+ require = in_group('peon')
+
+ @expose()
+ def index(self):
+ return "restricted_index"
+
+ @expose()
+ @identity.require(in_group('admin'))
+ def in_admin_group(self):
+ return 'in_admin_group'
+
+ @expose()
+ @identity.require(in_group('other'))
+ def in_other_group(self):
+ return 'in_other_group'
+
+ @expose()
+ def in_admin_group_explicit_check(self):
+ if 'admin' not in identity.current.groups:
+ raise identity.IdentityFailure("You need to be an Admin")
+ else:
+ return 'in_admin_group'
+
+ @expose()
+ def in_other_group_explicit_check(self):
+ if 'other' not in identity.current.groups:
+ raise identity.IdentityException
+ else:
+ return 'in_other_group'
+
+ @expose(format='json')
+ def json(self):
+ return dict(json="restricted_json")
+
+
+class IdentityRoot(RootController):
+
+ @expose()
+ def index(self):
+ return dict()
+
+ @expose(format='html')
+ def identity_failed(self, **kw):
+ """Identity failure - this usually returns a login form."""
+ return 'identity_failed_answer'
+
+ @expose()
+ @identity.require(not_anonymous())
+ def logged_in_only(self):
+ return 'logged_in_only'
+
+ @expose()
+ @identity.require(in_group('peon'))
+ def in_peon_group(self):
+ current = identity.current
+ self.current_in_peon_group(current)
+ request = cherrypy.serving.request
+ assert current.user_name == request.identity.user_name
+ return 'in_peon_group'
+
+ @expose()
+ def remote_ip(self):
+ return dict(remote_ip=_remoteHost())
+
+ @expose()
+ @identity.require(from_host('127.0.0.1'))
+ def from_localhost(self):
+ return 'localhost_only'
+
+ @expose()
+ @identity.require(from_any_host(('127.0.0.1', '127.0.0.2')))
+ def from_any_host(self):
+ return 'hosts_on_list_only'
+
+ @expose()
+ def test_exposed_require(self):
+ if not hasattr(self.in_peon_group, '_require'):
+ return 'no _require attr'
+ if not isinstance(self.in_peon_group._require, in_group):
+ return 'not correct class'
+ if 'peon' != self.in_peon_group._require.group_name:
+ return 'not correct group name'
+ return '_require is exposed'
+
+ @expose()
+ @identity.require(in_group('admin'))
+ def in_admin_group(self):
+ return 'in_admin_group'
+
+ @expose()
+ @identity.require(has_permission('chops_wood'))
+ def has_chopper_permission(self):
+ return 'has_chopper_permission'
+
+ @expose()
+ @identity.require(has_permission('bosses_people'))
+ def has_boss_permission(self):
+ return 'has_boss_permission'
+
+ @expose()
+ def logout(self):
+ identity.current.logout()
+ return 'logged out'
+
+ @expose()
+ @identity.require(not_anonymous())
+ def user_email(self):
+ return identity.current.user.email_address
+
+ peon_area = RestrictedArea()
+
+ @expose()
+ def new_user_setup(self, user_name, password):
+ return '%s %s' % (user_name, password)
+
+ _test_encoded_params = 'b=krümel&d.a=klöße1'
+
+ @expose()
+ @identity.require(not_anonymous())
+ def test_params(self, **kwargs):
+ params = self._test_encoded_params
+ # formencode's variable_decode create a datastructure
+ # but does not "decode" anything
+ to_datastruct = formencode.variabledecode.variable_decode
+ expected_params = to_datastruct(
+ dict([p.split('=') for p in params.split('&')]))
+ params_ok = True
+ if not expected_params['b'].decode(
+ 'utf-8') == cherrypy.request.params['b']:
+ params_ok = False
+ if not expected_params['d']['a'].decode(
+ 'utf-8') == cherrypy.request.params['d']['a']:
+ params_ok = False
+ if params_ok:
+ return 'params ok'
+ else:
+ return ("wrong params: %s\n"
+ "expected unicode objects for all strings"
+ % cherrypy.request.params)
+
+ @expose()
+ def is_anonymous(self):
+ assert cherrypy.serving.request.identity.user_name is None
+ assert cherrypy.serving.request.identity.anonymous
+ assert identity.current.anonymous
+ return 'is_anonymous'
+
+ @expose(format='json')
+ @identity.require(in_group('peon'))
+ def json(self):
+ return dict(json='restricted_json')
Modified: branches/1.5/turbogears/identity/tests/test_identity_sa.py
==============================================================================
--- branches/1.5/turbogears/identity/tests/test_identity_sa.py Mon Jan 17
17:44:30 2011 (r7209)
+++ branches/1.5/turbogears/identity/tests/test_identity_sa.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -1,288 +1,18 @@
# -*- coding: UTF-8 -*-
+"""SQLAlchemy based Identity tests."""
+
import unittest
import urllib
import base64
-import formencode
-import cherrypy
-
-from turbogears import testutil, identity, config, expose
-from turbogears.controllers import Controller, RootController
+from turbogears import testutil, config
from turbogears.database import session
-from turbogears.identity import (SecureObject, SecureResource,
- in_group, in_all_groups, in_any_group, not_anonymous,
- has_permission, has_all_permissions, has_any_permission,
- from_host, from_any_host, Any, All, NotAny)
-from turbogears.identity.conditions import _remoteHost
from turbogears.identity.saprovider import TG_User, TG_Group, TG_Permission
-from turbogears.identity.exceptions import (IdentityConfigurationException,
- RequestRequiredException)
+from turbogears.identity.exceptions import IdentityConfigurationException
from turbogears.identity.visitor import IdentityVisitPlugin
-
-def mycustomencrypt(password):
- """A custom password encryption function."""
- return password + '_custom'
-
-
-class MockIdentity(object):
- """Identity mock object."""
-
- anonymous = False
- groups = ('admin', 'edit')
- permissions = ('read', 'write')
-
-mock_identity = MockIdentity()
-
-
-class TestPredicates(unittest.TestCase):
-
- def met(self, predicate):
- return predicate.eval_with_object(mock_identity)
-
- def test_in_group(self):
- """Test the predicate for requiring a group."""
- assert self.met(in_group('admin'))
- assert not self.met(in_group('guest'))
-
- def test_in_all_groups(self):
- """Test the predicate for requiring a number of group."""
- assert self.met(in_all_groups('admin', 'edit'))
- assert not self.met(in_all_groups('admin', 'guest', 'edit'))
-
- def test_in_any_group(self):
- """Test the predicate for requiring at least one group."""
- assert self.met(in_any_group('guest', 'edit', 'user'))
- assert not self.met(in_all_groups('guest', 'user'))
-
- def test_anonymous(self):
- """Test predicate for checking anonymous visitors."""
- assert self.met(not_anonymous())
-
- def test_has_permission(self):
- """Test predicate for checking particular permissions."""
- assert self.met(has_permission('read'))
- assert not self.met(has_permission('delete'))
-
- def test_has_all_permissions(self):
- """Test the predicate for requiring a number of permissions."""
- assert self.met(has_all_permissions('read', 'write'))
- assert not self.met(has_all_permissions('read', 'delete', 'write'))
-
- def test_has_any_permission(self):
- """Test the predicate for requiring at least one permission."""
- assert self.met(has_any_permission('delete', 'write', 'update'))
- assert not self.met(has_any_permission('delete', 'update'))
-
- def test_any(self):
- """Test the Any predicate."""
- yes = in_group('edit')
- no1, no2 = in_group('guest'), in_group('user')
- met = self.met
- assert met(Any(yes))
- assert not met(Any(no1, no2))
- assert met(Any(no1, yes, no2))
-
- def test_all(self):
- """Test the All predicate."""
- yes1, yes2 = in_group('admin'), in_group('edit')
- no = in_group('guest')
- met = self.met
- assert not met(All(no))
- assert met(All(yes1, yes2))
- assert not met(All(yes1, no, yes2))
-
- def test_not_any(self):
- """Test the Not Any predicate."""
- yes = in_group('edit')
- no1, no2 = in_group('guest'), in_group('user')
- met = self.met
- assert not met(NotAny(yes))
- assert met(NotAny(no1, no2))
- assert not met(NotAny(no1, yes, no2))
-
- def test_remote_host_request_required(self):
- """Test that _remoteHost raises exception when request is not
available.
- """
- self.assertRaises(RequestRequiredException, _remoteHost)
-
-
-class TestSecureObject(unittest.TestCase):
-
- def test_secure_object_proxies_cp_attributes(self):
- """Test that SecureObject properly proxies CherryPy (_cp)
attributes."""
-
- test_config = {'request.methods_with_bodies': ('POST', 'PUT')}
-
- class TestObject(object):
- _cp_config = test_config
-
- test_object = SecureObject(TestObject(), None)
- assert test_object._cp_config == test_config
-
- test_object = SecureObject(RootController(), None)
- test_object._cp_config = test_config
- assert test_object._cp_config == test_config
-
-
-class RestrictedArea(Controller, SecureResource):
-
- require = in_group('peon')
-
- @expose()
- def index(self):
- return "restricted_index"
-
- @expose()
- @identity.require(in_group('admin'))
- def in_admin_group(self):
- return 'in_admin_group'
-
- @expose()
- @identity.require(in_group('other'))
- def in_other_group(self):
- return 'in_other_group'
-
- @expose()
- def in_admin_group_explicit_check(self):
- if 'admin' not in identity.current.groups:
- raise identity.IdentityFailure("You need to be an Admin")
- else:
- return 'in_admin_group'
-
- @expose()
- def in_other_group_explicit_check(self):
- if 'other' not in identity.current.groups:
- raise identity.IdentityException
- else:
- return 'in_other_group'
-
- @expose(format='json')
- def json(self):
- return dict(json="restricted_json")
-
-
-class IdentityRoot(RootController):
-
- @expose()
- def index(self):
- return dict()
-
- @expose(format='html')
- def identity_failed(self, **kw):
- """Identity failure - this usually returns a login form."""
- return 'identity_failed_answer'
-
- @expose()
- @identity.require(not_anonymous())
- def logged_in_only(self):
- return 'logged_in_only'
-
- @expose()
- @identity.require(in_group('peon'))
- def in_peon_group(self):
- user = TG_User.by_user_name(u'samIam')
- group_ids = set((TG_Group.by_group_name(u'peon').group_id,
- TG_Group.by_group_name(u'other').group_id))
- assert identity.current.user == user
- assert identity.current.user_name == user.user_name
- assert identity.current.user_id == user.user_id
- assert identity.current.groups == set(('peon', 'other'))
- assert identity.current.group_ids == group_ids
- assert 'samIam' == cherrypy.serving.request.identity.user_name
- return 'in_peon_group'
-
- @expose()
- def remote_ip(self):
- return dict(remote_ip=_remoteHost())
-
- @expose()
- @identity.require(from_host('127.0.0.1'))
- def from_localhost(self):
- return 'localhost_only'
-
- @expose()
- @identity.require(from_any_host(('127.0.0.1', '127.0.0.2')))
- def from_any_host(self):
- return 'hosts_on_list_only'
-
- @expose()
- def test_exposed_require(self):
- if not hasattr(self.in_peon_group, '_require'):
- return 'no _require attr'
- if not isinstance(self.in_peon_group._require, in_group):
- return 'not correct class'
- if 'peon' != self.in_peon_group._require.group_name:
- return 'not correct group name'
- return '_require is exposed'
-
- @expose()
- @identity.require(in_group('admin'))
- def in_admin_group(self):
- return 'in_admin_group'
-
- @expose()
- @identity.require(has_permission('chops_wood'))
- def has_chopper_permission(self):
- return 'has_chopper_permission'
-
- @expose()
- @identity.require(has_permission('bosses_people'))
- def has_boss_permission(self):
- return 'has_boss_permission'
-
- @expose()
- def logout(self):
- identity.current.logout()
- return 'logged out'
-
- @expose()
- @identity.require(not_anonymous())
- def user_email(self):
- return identity.current.user.email_address
-
- peon_area = RestrictedArea()
-
- @expose()
- def new_user_setup(self, user_name, password):
- return '%s %s' % (user_name, password)
-
- _test_encoded_params = 'b=krümel&d.a=klöße1'
-
- @expose()
- @identity.require(not_anonymous())
- def test_params(self, **kwargs):
- params = self._test_encoded_params
- # formencode's variable_decode create a datastructure
- # but does not "decode" anything
- to_datastruct = formencode.variabledecode.variable_decode
- expected_params = to_datastruct(
- dict([p.split('=') for p in params.split('&')]))
- params_ok = True
- if not expected_params['b'].decode(
- 'utf-8') == cherrypy.request.params['b']:
- params_ok = False
- if not expected_params['d']['a'].decode(
- 'utf-8') == cherrypy.request.params['d']['a']:
- params_ok = False
- if params_ok:
- return 'params ok'
- else:
- return 'wrong params: %s\nexpected unicode objects' \
- ' for all strings' % cherrypy.request.params
-
- @expose()
- def is_anonymous(self):
- assert cherrypy.serving.request.identity.user_name is None
- assert cherrypy.serving.request.identity.anonymous
- assert identity.current.anonymous
- return 'is_anonymous'
-
- @expose(format='json')
- @identity.require(in_group('peon'))
- def json(self):
- return dict(json="restricted_json")
+from turbogears.identity.tests.test_identity import IdentityRoot
class TestIdentity(testutil.TGTest):
@@ -354,6 +84,19 @@
admin_group.permissions.append(boss_perm)
user.groups.append(peon_group)
user.groups.append(other_group)
+ self.root.current_in_peon_group = self.current_in_peon_group
+
+
+ def current_in_peon_group(self, current):
+ user = TG_User.by_user_name(u'samIam')
+ group_ids = set((TG_Group.by_group_name(u'peon').group_id,
+ TG_Group.by_group_name(u'other').group_id))
+ assert current.user == user
+ assert current.user_name == user.user_name
+ assert current.user_id == user.user_id
+ assert current.groups == set(('peon', 'other'))
+ assert current.group_ids == group_ids
+
def test_user_password_parameters(self):
"""Test that controller can receive user_name and password
parameters."""
@@ -443,7 +186,7 @@
"""Test if a custom hashed password is stored in the database."""
config.update({'identity.saprovider.encryption_algorithm': 'custom',
'identity.custom_encryption':
- 'identity.tests.test_identity_sa.mycustomencrypt'})
+ 'identity.tests.test_identity.mycustomencrypt'})
self.app.get('/')
user = TG_User()
user.password = 'password'
@@ -768,6 +511,11 @@
assert plug.identity_from_http_auth in plug.identity_sources
assert plug.identity_from_visit in plug.identity_sources
+ def test_no_identity_source(self):
+ """Test that empty identity source raises identity configuration
error."""
+ config.update({'identity.source': ''})
+ self.assertRaises(IdentityConfigurationException, IdentityVisitPlugin)
+
def test_unknown_identity_source(self):
"""Test that unknown identity source raises identity configuration
error."""
config.update({'identity.source': 'bogus'})
Modified: branches/1.5/turbogears/identity/tests/test_identity_so.py
==============================================================================
--- branches/1.5/turbogears/identity/tests/test_identity_so.py Mon Jan 17
17:44:30 2011 (r7209)
+++ branches/1.5/turbogears/identity/tests/test_identity_so.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -1,292 +1,22 @@
# -*- coding: UTF-8 -*-
+"""SQLObject based Identity tests."""
+
import unittest
import urllib
import base64
-import formencode
-import cherrypy
-
-from turbogears import testutil, database, identity, config, expose
-from turbogears.controllers import Controller, RootController
-from turbogears.identity import (SecureObject, SecureResource,
- in_group, in_all_groups, in_any_group, not_anonymous,
- has_permission, has_all_permissions, has_any_permission,
- from_host, from_any_host, Any, All, NotAny)
-from turbogears.identity.conditions import _remoteHost
+from turbogears import testutil, database, config
from turbogears.identity.soprovider import TG_User, TG_Group, TG_Permission
-from turbogears.identity.exceptions import (IdentityConfigurationException,
- RequestRequiredException)
+from turbogears.identity.exceptions import IdentityConfigurationException
from turbogears.identity.visitor import IdentityVisitPlugin
+from turbogears.identity.tests.test_identity import IdentityRoot
+
# hub = database.AutoConnectHub("sqlite:///:memory:")
hub = database.PackageHub("turbogears.identity")
-def mycustomencrypt(password):
- """A custom password encryption function."""
- return password + '_custom'
-
-
-class MockIdentity(object):
- """Identity mock object."""
-
- anonymous = False
- groups = ('admin', 'edit')
- permissions = ('read', 'write')
-
-mock_identity = MockIdentity()
-
-
-class TestPredicates(unittest.TestCase):
-
- def met(self, predicate):
- return predicate.eval_with_object(mock_identity)
-
- def test_in_group(self):
- """Test the predicate for requiring a group."""
- assert self.met(in_group('admin'))
- assert not self.met(in_group('guest'))
-
- def test_in_all_groups(self):
- """Test the predicate for requiring a number of group."""
- assert self.met(in_all_groups('admin', 'edit'))
- assert not self.met(in_all_groups('admin', 'guest', 'edit'))
-
- def test_in_any_group(self):
- """Test the predicate for requiring at least one group."""
- assert self.met(in_any_group('guest', 'edit', 'user'))
- assert not self.met(in_all_groups('guest', 'user'))
-
- def test_anonymous(self):
- """Test predicate for checking anonymous visitors."""
- assert self.met(not_anonymous())
-
- def test_has_permission(self):
- """Test predicate for checking particular permissions."""
- assert self.met(has_permission('read'))
- assert not self.met(has_permission('delete'))
-
- def test_has_all_permissions(self):
- """Test the predicate for requiring a number of permissions."""
- assert self.met(has_all_permissions('read', 'write'))
- assert not self.met(has_all_permissions('read', 'delete', 'write'))
-
- def test_has_any_permission(self):
- """Test the predicate for requiring at least one permission."""
- assert self.met(has_any_permission('delete', 'write', 'update'))
- assert not self.met(has_any_permission('delete', 'update'))
-
- def test_any(self):
- """Test the Any predicate."""
- yes = in_group('edit')
- no1, no2 = in_group('guest'), in_group('user')
- met = self.met
- assert met(Any(yes))
- assert not met(Any(no1, no2))
- assert met(Any(no1, yes, no2))
-
- def test_all(self):
- """Test the All predicate."""
- yes1, yes2 = in_group('admin'), in_group('edit')
- no = in_group('guest')
- met = self.met
- assert not met(All(no))
- assert met(All(yes1, yes2))
- assert not met(All(yes1, no, yes2))
-
- def test_not_any(self):
- """Test the Not Any predicate."""
- yes = in_group('edit')
- no1, no2 = in_group('guest'), in_group('user')
- met = self.met
- assert not met(NotAny(yes))
- assert met(NotAny(no1, no2))
- assert not met(NotAny(no1, yes, no2))
-
- def test_remote_host_request_required(self):
- """Test that _remoteHost raises exception when request is not
available.
- """
- self.assertRaises(RequestRequiredException, _remoteHost)
-
-
-class TestSecureObject(unittest.TestCase):
-
- def test_secure_object_proxies_cp_attributes(self):
- """Test that SecureObject properly proxies CherryPy (_cp)
attributes."""
-
- test_config = {'request.methods_with_bodies': ('POST', 'PUT')}
-
- class TestObject(object):
- _cp_config = test_config
-
- test_object = SecureObject(TestObject(), None)
- assert test_object._cp_config == test_config
-
- test_object = SecureObject(RootController(), None)
- test_object._cp_config = test_config
- assert test_object._cp_config == test_config
-
-
-class RestrictedArea(Controller, SecureResource):
-
- require = in_group('peon')
-
- @expose()
- def index(self):
- return "restricted_index"
-
- @expose()
- @identity.require(in_group('admin'))
- def in_admin_group(self):
- return 'in_admin_group'
-
- @expose()
- @identity.require(in_group('other'))
- def in_other_group(self):
- return 'in_other_group'
-
- @expose()
- def in_admin_group_explicit_check(self):
- if 'admin' not in identity.current.groups:
- raise identity.IdentityFailure("You need to be an Admin")
- else:
- return 'in_admin_group'
-
- @expose()
- def in_other_group_explicit_check(self):
- if 'other' not in identity.current.groups:
- raise identity.IdentityException
- else:
- return 'in_other_group'
-
- @expose(format='json')
- def json(self):
- return dict(json="restricted_json")
-
-
-class IdentityRoot(RootController):
-
- @expose()
- def index(self):
- return dict()
-
- @expose(format='html')
- def identity_failed(self, **kw):
- """Identity failure - this usually returns a login form."""
- return 'identity_failed_answer'
-
- @expose()
- @identity.require(not_anonymous())
- def logged_in_only(self):
- return 'logged_in_only'
-
- @expose()
- @identity.require(in_group('peon'))
- def in_peon_group(self):
- user = TG_User.by_user_name('samIam')
- group_ids = set((TG_Group.by_group_name('peon').id,
- TG_Group.by_group_name('other').id))
- assert identity.current.user == user
- assert identity.current.user_name == user.user_name
- assert identity.current.user_id == user.id
- assert identity.current.groups == set(('peon', 'other'))
- assert identity.current.group_ids == group_ids
- assert 'samIam' == cherrypy.serving.request.identity.user_name
- return 'in_peon_group'
-
- @expose()
- def remote_ip(self):
- return dict(remote_ip=_remoteHost())
-
- @expose()
- @identity.require(from_host('127.0.0.1'))
- def from_localhost(self):
- return 'localhost_only'
-
- @expose()
- @identity.require(from_any_host(('127.0.0.1', '127.0.0.2')))
- def from_any_host(self):
- return 'hosts_on_list_only'
-
- @expose()
- def test_exposed_require(self):
- if not hasattr(self.in_peon_group, '_require'):
- return 'no _require attr'
- if not isinstance(self.in_peon_group._require, in_group):
- return 'not correct class'
- if 'peon' != self.in_peon_group._require.group_name:
- return 'not correct group name'
- return '_require is exposed'
-
- @expose()
- @identity.require(in_group('admin'))
- def in_admin_group(self):
- return 'in_admin_group'
-
- @expose()
- @identity.require(has_permission('chops_wood'))
- def has_chopper_permission(self):
- return 'has_chopper_permission'
-
- @expose()
- @identity.require(has_permission('bosses_people'))
- def has_boss_permission(self):
- return 'has_boss_permission'
-
- @expose()
- def logout(self):
- identity.current.logout()
- return 'logged out'
-
- @expose()
- @identity.require(not_anonymous())
- def user_email(self):
- return identity.current.user.email_address
-
- peon_area = RestrictedArea()
-
- @expose()
- def new_user_setup(self, user_name, password):
- return '%s %s' % (user_name, password)
-
- _test_encoded_params = 'b=krümel&d.a=klöße1'
-
- @expose()
- @identity.require(not_anonymous())
- def test_params(self, **kwargs):
- params = self._test_encoded_params
- # formencode's variable_decode create a datastructure
- # but does not "decode" anything
- to_datastruct = formencode.variabledecode.variable_decode
- expected_params = to_datastruct(
- dict([p.split('=') for p in params.split('&')]))
- params_ok = True
- if not expected_params['b'].decode(
- 'utf-8') == cherrypy.request.params['b']:
- params_ok = False
- if not expected_params['d']['a'].decode(
- 'utf-8') == cherrypy.request.params['d']['a']:
- params_ok = False
- if params_ok:
- return 'params ok'
- else:
- return 'wrong params: %s\nexpected unicode objects' \
- ' for all strings' % cherrypy.request.params
-
- @expose()
- def is_anonymous(self):
- assert cherrypy.serving.request.identity.user_name is None
- assert cherrypy.serving.request.identity.anonymous
- assert identity.current.anonymous
- return 'is_anonymous'
-
- @expose(format='json')
- @identity.require(in_group('peon'))
- def json(self):
- return dict(json="restricted_json")
-
-
class TestIdentity(testutil.TGTest):
root = IdentityRoot
@@ -294,7 +24,6 @@
stop_tg_only = True
def setUp(self):
- # identity requires visit and a failure_url
test_config = {
'visit.on': True,
'visit.manager': 'sqlobject',
@@ -321,6 +50,7 @@
super(TestIdentity, self).setUp()
self.init_model()
+
def init_model(self):
if TG_User.select().count() == 0:
user = TG_User(user_name='samIam',
@@ -340,6 +70,19 @@
admin_group.addTG_Permission(boss_perm)
user.addTG_Group(peon_group)
user.addTG_Group(other_group)
+ self.root.current_in_peon_group = self.current_in_peon_group
+
+
+ def current_in_peon_group(self, current):
+ user = TG_User.by_user_name('samIam')
+ group_ids = set((TG_Group.by_group_name('peon').id,
+ TG_Group.by_group_name('other').id))
+ assert current.user == user
+ assert current.user_name == user.user_name
+ assert current.user_id == user.id
+ assert current.groups == set(('peon', 'other'))
+ assert current.group_ids == group_ids
+
def test_user_password_parameters(self):
"""Test that controller can receive user_name and password
parameters."""
@@ -465,7 +208,7 @@
"""Test if a custom hashed password is stored in the database."""
config.update({'identity.soprovider.encryption_algorithm': 'custom',
'identity.custom_encryption':
- 'identity.tests.test_identity_so.mycustomencrypt'})
+ 'identity.tests.test_identity.mycustomencrypt'})
self.app.get('/')
hub.begin()
user = TG_User.by_user_name('samIam')
@@ -791,6 +534,11 @@
assert plug.identity_from_http_auth in plug.identity_sources
assert plug.identity_from_visit in plug.identity_sources
+ def test_no_identity_source(self):
+ """Test that empty identity source raises identity configuration
error."""
+ config.update({'identity.source': ''})
+ self.assertRaises(IdentityConfigurationException, IdentityVisitPlugin)
+
def test_unknown_identity_source(self):
"""Test that unknown identity source raises identity configuration
error."""
config.update({'identity.source': 'bogus'})
Added: branches/1.5/turbogears/identity/tests/test_visit.py
==============================================================================
--- /dev/null 00:00:00 1970 (empty, because file is newly added)
+++ branches/1.5/turbogears/identity/tests/test_visit.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -0,0 +1,40 @@
+# -*- coding: UTF-8 -*-
+
+"""ORM independent Visit tests and test controllers."""
+
+import cherrypy
+
+from turbogears import config, controllers, expose, visit
+
+
+def cookie_header(response):
+ """Returns a dict containing cookie information to pass to a server."""
+ return dict(Cookie=response.headers['Set-Cookie'])
+
+
+class SimpleVisitPlugin(object):
+
+ def record_request(self, visit):
+ cherrypy.request.simple_visit_plugin = visit
+
+ def register(self):
+ visit.enable_visit_plugin(self)
+
+
+class VisitRoot(controllers.RootController):
+
+ @expose()
+ def index(self):
+ new = key = None
+ cur_visit = visit.current()
+ if cur_visit:
+ new = cur_visit.is_new
+ key = cur_visit.key
+ visit_on = config.get('visit.on')
+ return dict(new=new, key=key, visit_on=visit_on)
+
+ @expose()
+ def visit_plugin(self):
+ vi = cherrypy.request.simple_visit_plugin
+ return dict(key=vi.key, is_new=vi.is_new)
+
Modified: branches/1.5/turbogears/identity/tests/test_visit_sa.py
==============================================================================
--- branches/1.5/turbogears/identity/tests/test_visit_sa.py Mon Jan 17
17:44:30 2011 (r7209)
+++ branches/1.5/turbogears/identity/tests/test_visit_sa.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -1,53 +1,18 @@
+# -*- coding: UTF-8 -*-
+
+"""SQLAlchemy based Visit tests."""
+
import time
from Cookie import SimpleCookie
from unittest import TestCase
-import cherrypy
-
import turbogears.visit.api
-from turbogears import config, controllers, expose, testutil, visit
+from turbogears import config, testutil, visit
from turbogears.visit.savisit import SqlAlchemyVisitManager
-
-def cookie_header(response):
- """Returns a dict containing cookie information to pass to a server."""
- return dict(Cookie=response.headers['Set-Cookie'])
-
-
-def setup_module():
- testutil.start_server()
-
-
-def teardown_module():
- testutil.stop_server()
-
-
-class SimpleVisitPlugin(object):
-
- def record_request(self, visit):
- cherrypy.request.simple_visit_plugin = visit
-
- def register(self):
- visit.enable_visit_plugin(self)
-
-
-class VisitRoot(controllers.RootController):
-
- @expose()
- def index(self):
- new = key = None
- cur_visit = visit.current()
- if cur_visit:
- new = cur_visit.is_new
- key = cur_visit.key
- visit_on = config.get('visit.on')
- return dict(new=new, key=key, visit_on=visit_on)
-
- @expose()
- def visit_plugin(self):
- vi = cherrypy.request.simple_visit_plugin
- return dict(key=vi.key, is_new=vi.is_new)
+from turbogears.identity.tests.test_visit import (
+ SimpleVisitPlugin, VisitRoot, cookie_header)
class TestVisit(TestCase):
Modified: branches/1.5/turbogears/identity/tests/test_visit_so.py
==============================================================================
--- branches/1.5/turbogears/identity/tests/test_visit_so.py Mon Jan 17
17:44:30 2011 (r7209)
+++ branches/1.5/turbogears/identity/tests/test_visit_so.py Tue Jan 18
07:22:04 2011 (r7210)
@@ -1,53 +1,18 @@
+# -*- coding: UTF-8 -*-
+
+"""SQLObject based Visit tests."""
+
import time
from Cookie import SimpleCookie
from unittest import TestCase
-import cherrypy
-
import turbogears.visit.api
-from turbogears import config, controllers, expose, testutil, visit
+from turbogears import config, testutil, visit
from turbogears.visit.sovisit import SqlObjectVisitManager
-
-def cookie_header(response):
- """Returns a dict containing cookie information to pass to a server."""
- return dict(Cookie=response.headers['Set-Cookie'])
-
-
-def setup_module():
- testutil.start_server()
-
-
-def teardown_module():
- testutil.stop_server()
-
-
-class SimpleVisitPlugin(object):
-
- def record_request(self, visit):
- cherrypy.request.simple_visit_plugin = visit
-
- def register(self):
- visit.enable_visit_plugin(self)
-
-
-class VisitRoot(controllers.RootController):
-
- @expose()
- def index(self):
- new = key = None
- cur_visit = visit.current()
- if cur_visit:
- new = cur_visit.is_new
- key = cur_visit.key
- visit_on = config.get('visit.on')
- return dict(new=new, key=key, visit_on=visit_on)
-
- @expose()
- def visit_plugin(self):
- vi = cherrypy.request.simple_visit_plugin
- return dict(key=vi.key, is_new=vi.is_new)
+from turbogears.identity.tests.test_visit import (
+ SimpleVisitPlugin, VisitRoot, cookie_header)
class TestVisit(TestCase):
Modified: branches/1.5/turbogears/identity/visitor.py
==============================================================================
--- branches/1.5/turbogears/identity/visitor.py Mon Jan 17 17:44:30 2011
(r7209)
+++ branches/1.5/turbogears/identity/visitor.py Tue Jan 18 07:22:04 2011
(r7210)
@@ -21,7 +21,7 @@
IdentityException, IdentityFailure)
-log = logging.getLogger("turbogears.identity")
+log = logging.getLogger('turbogears.identity')
# Global Visit plugin