<commit_before># -*- coding: utf-8 -*-
"""
repoze.what & repoze.what-pylons **integration** tests.

Note that it is not necessary to have integration tests for the other auth*
software in this package. They must be in tg.devtools, specifically in the test
suite of the quickstarted applications (and there's where they are, as of
this writing).

"""

from unittest import TestCase
from shutil import rmtree
from urllib import unquote
import os

from paste import httpexceptions
from paste.registry import RegistryManager
from webob import Response, Request
from webtest import TestApp
from beaker.middleware import CacheMiddleware, SessionMiddleware

from tg import response, expose, require, allow_only
from tg.controllers import TGController, WSGIAppController, RestController
import pylons
from pylons import tmpl_context
from pylons.controllers.util import abort
from pylons.util import ContextObj, PylonsContext
from pylons.testutil import ControllerWrap, SetupCacheGlobal

from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
from repoze.what.middleware import setup_auth
from repoze.what.predicates import Not, is_user, not_anonymous


#{ AUT's setup
NOT_AUTHENTICATED = "The current user must have been authenticated"

data_dir = os.path.dirname(os.path.abspath(__file__))
session_dir = os.path.join(data_dir, 'session')

# Just in case...
rmtree(session_dir, ignore_errors=True)


def make_app(controller_klass, environ={}):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app, groups_adapters, permissions_adapters,
                     identifiers=identifiers, authenticators=[],
                     challengers=[], skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)


#{ Mock objects


def wsgi_app(environ, start_response):
    """Mock WSGI application"""
    req = Request(environ)
    resp = Response("Hello from %s" % req.script_name + req.path_info)
    return resp(environ, start_response)


class DaRestController(RestController):
    """Mock REST controller"""

    allow_only = is_user('gustavo')

    @expose()
    def new(self):
        return "new here"


class HRManagementController(TGController):
    """Mock TG2 protected controller using the .allow_only attribute"""

    allow_only = is_user('hiring-manager')

    @expose()
    def index(self):
        return 'you can manage Human Resources'

    @expose()
    def hire(self, person_name):
        return "%s was just hired" % person_name


class ControlPanel(TGController):
    """Mock TG2 protected controller using @allow_only directly."""

    hr = HRManagementController()
    allow_only = not_anonymous()

    @expose()
    def index(self):
        return 'you are in the panel'

    @expose()
    @require(is_user('admin'))
    def add_user(self, user_name):
        return "%s was just registered" % user_name

#ControlPanel = allow_only(not_anonymous())(ControlPanel)


class RootController(TGController):

    cp = ControlPanel()

    rest = DaRestController()

    mounted_app = WSGIAppController(wsgi_app, allow_only=is_user('gustavo'))

    @expose()
    def index(self):
        return "you're in the main page"

    @expose()
    @require(is_user('developer'))
    def commit(self):
        return 'you can commit'


class ControllerWithAllowOnlyAttributeAndAuthzDenialHandler(TGController):
    """Mock TG2 protected controller using the .allow_only attribute"""

    allow_only = is_user('foobar')<commit_msg>auth tests are brought back to life<commit_after># -*- coding: utf-8 -*-
"""
repoze.what & repoze.what-pylons **integration** tests.

Note that it is not necessary to have integration tests for the other auth*
software in this package. They must be in tg.devtools, specifically in the test
suite of the quickstarted applications (and there's where they are, as of
this writing).

"""

from unittest import TestCase
from shutil import rmtree
from urllib import unquote
import os

from paste import httpexceptions
from paste.registry import RegistryManager
from webob import Response, Request
from webtest import TestApp
from beaker.middleware import CacheMiddleware, SessionMiddleware

from tg import response, expose, require, allow_only
from tg.controllers import TGController, WSGIAppController, RestController
import pylons
from pylons import tmpl_context
from pylons.controllers.util import abort
from pylons.util import ContextObj, PylonsContext
from pylons.testutil import ControllerWrap, SetupCacheGlobal

from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
from repoze.what.middleware import setup_auth
from repoze.what.predicates import Not, is_user, not_anonymous


#{ AUT's setup
NOT_AUTHENTICATED = "The current user must have been authenticated"

data_dir = os.path.dirname(os.path.abspath(__file__))
session_dir = os.path.join(data_dir, 'session')

# Just in case...
rmtree(session_dir, ignore_errors=True)


def make_app(controller_klass, environ={}):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app, groups_adapters, permissions_adapters,
                     identifiers=identifiers, authenticators=[],
                     challengers=[], skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)


#{ Mock objects


def wsgi_app(environ, start_response):
    """Mock WSGI application"""
    req = Request(environ)
    resp = Response("Hello from %s" % req.script_name + req.path_info)
    return resp(environ, start_response)


class DaRestController(RestController):
    """Mock REST controller"""

    allow_only = is_user('gustavo')

    @expose()
    def new(self):
        return "new here"


class HRManagementController(TGController):
    """Mock TG2 protected controller using the .allow_only attribute"""

    allow_only = is_user('hiring-manager')

    @expose()
    def index(self):
        return 'you can manage Human Resources'

    @expose()
    def hire(self, person_name):
        return "%s was just hired" % person_name


class ControlPanel(TGController):
    """Mock TG2 protected controller using @allow_only directly."""

    hr = HRManagementController()
    allow_only = not_anonymous()

    @expose()
    def index(self):
        return 'you are in the panel'

    @expose()
    #@require(is_user('admin'))
    def add_user(self, user_name):
        return "%s was just registered" % user_name

#ControlPanel = allow_only(not_anonymous())(ControlPanel)


class RootController(TGController):

    cp = ControlPanel()

    rest = DaRestController()

    mounted_app = WSGIAppController(wsgi_app, allow_only=is_user('gustavo'))

    @expose()
    def index(self):
        return "you're in the main page"

    @expose()
    @require(is_user('developer'))
    def commit(self):
        return 'you can commit'


class ControllerWithAllowOnlyAttributeAndAuthzDenialHandler(TGController):
    """Mock TG2 protected controller using the .allow_only attribute"""

    allow_only = is_user('foobar')
{'fraction_non_alphanumeric': 0.09605214610748986, 'fraction_numerical': 0.0009838888205632764, 'mean_word_length': 4.249838605551969, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4794862', 'n_tokens_mistral': 2450, 'n_tokens_neox': 2347, 'n_words': 701}