예제 #1
0
 def __init__(self, *args, **kwargs):
     if pylons.test.pylonsapp:
         wsgiapp = pylons.test.pylonsapp
     else:
         wsgiapp = loadapp('config:%s' % config['__file__'])
     self.app = TestApp(wsgiapp)
     url._push_object(URLGenerator(config['routes.map'], environ))
예제 #2
0
def mock_pylons():
    from paste.registry import Registry
    import pylons
    from pylons.util import AttribSafeContextObj
    import ckan.lib.app_globals as app_globals
    from ckan.lib.cli import MockTranslator
    from ckan.config.routing import make_map
    from pylons.controllers.util import Request, Response
    from routes.util import URLGenerator

    class TestPylonsSession(dict):
        last_accessed = None

        def save(self):
            pass

    registry = Registry()
    registry.prepare()

    context_obj = AttribSafeContextObj()
    registry.register(pylons.c, context_obj)

    app_globals_obj = app_globals.app_globals
    registry.register(pylons.g, app_globals_obj)

    request_obj = Request(dict(HTTP_HOST="nohost", REQUEST_METHOD="GET"))
    registry.register(pylons.request, request_obj)

    translator_obj = MockTranslator()
    registry.register(pylons.translator, translator_obj)

    registry.register(pylons.response, Response())
    mapper = make_map()
    registry.register(pylons.url, URLGenerator(mapper, {}))
    registry.register(pylons.session, TestPylonsSession())
예제 #3
0
 def setUp(self):
     from paste.fixture import TestApp
     from routes.util import URLGenerator
     
     app = make_app({})
     self.app = TestApp(app)
     self.url = URLGenerator(app.config['routes.map'], {})
예제 #4
0
파일: __init__.py 프로젝트: zhao07/LinOTP
    def __init__(self, *args, **kwargs):
        '''
        initialize the test class
        '''
        TestCase.__init__(self, *args, **kwargs)

        LOG.debug("ConfigFile: %s " % config['__file__'])

        conffile = config['__file__']

        if pylons.test.pylonsapp:
            wsgiapp = pylons.test.pylonsapp
        else:
            wsgiapp = loadapp('config: %s' % config['__file__'])

        self.app = TestApp(wsgiapp)

        conf = None
        if conffile.startswith('/'):
            conf = appconfig('config:%s' % config['__file__'], relative_to=None)
        else:
            raise Exception('dont know how to load the application relatively')
         #conf = appconfig('config: %s' % config['__file__'], relative_to=rel)

        load_environment(conf.global_conf, conf.local_conf)
        self.appconf = conf

        url._push_object(URLGenerator(config['routes.map'], environ))

        self.isSelfTest = False
        if env.has_key("linotp.selfTest"):
            self.isSelfTest = True

        return
예제 #5
0
    def setup_class(cls):
        cls.registry = Registry()
        cls.registry.prepare()

        cls.context_obj = AttribSafeContextObj()
        cls.registry.register(pylons.c, cls.context_obj)

        cls.app_globals_obj = app_globals.Globals()
        cls.registry.register(pylons.g, cls.app_globals_obj)

        cls.request_obj = Request(dict(HTTP_HOST="nohost"))
        cls.registry.register(pylons.request, cls.request_obj)

        cls.translator_obj = MockTranslator()
        cls.registry.register(pylons.translator, cls.translator_obj)

        cls.buffet = pylons.templating.Buffet('genshi',
                                              template_root='ckan.templates')
        cls.registry.register(pylons.buffet, cls.buffet)

        cls.registry.register(pylons.response, Response())
        mapper = make_map()
        cls.registry.register(pylons.url, URLGenerator(mapper, {}))
        cls.registry.register(pylons.session, TestSession())

        # Templates often want to find out the request's routes info, so put
        # some dummy values into the routes_dict, so the templates that do
        # this don't cause an exception.
        pylons.request.environ.update({
            'pylons.routes_dict': {
                'action': 'test-action',
                'controller': 'test-package::',
            }
        })
예제 #6
0
    def __init__(self, *args, **kwargs):
        wsgiapp = pylons.test.pylonsapp
        config = wsgiapp.config
        self.app = TestApp(wsgiapp)
        # Decorate with an OPTIONS method
        # The webtest version in el6 does not have it
        if not hasattr(self.app, 'options'):
            setattr(self.app, 'options',
                    types.MethodType(_app_options, self.app))

        # Decorate with a post_json method
        # Same thing, version in el6 does not have it
        if not hasattr(self.app, 'post_json'):
            setattr(self.app, 'post_json',
                    types.MethodType(_app_post_json, self.app))

        # Decorate with a get_json method
        if not hasattr(self.app, 'get_json'):
            setattr(self.app, 'get_json',
                    types.MethodType(_app_get_json, self.app))

        url._push_object(URLGenerator(config['routes.map'], environ))
        TestCase.__init__(self, *args, **kwargs)

        self.pkey, self.cert = _generate_mock_cert()
 def __init__(self, *args, **kwargs):
     wsgiapp = pylons.test.pylonsapp
     config = wsgiapp.application.config
     self.config = config
     self.app = TestApp(wsgiapp)
     self.g = self.config['pylons.app_globals']
     url._push_object(URLGenerator(config['routes.map'], environ))
     TestCase.__init__(self, *args, **kwargs)
예제 #8
0
 def __init__(self, *args, **kwargs):
     wsgiapp = pylons.test.pylonsapp
     config = wsgiapp.config
     self.app = TestApp(wsgiapp)
     url._push_object(URLGenerator(config['routes.map'], environ))
     TestCase.__init__(self, *args, **kwargs)
     self.from_date = datetime(1990, 1, 1).isoformat() + "Z"
     self.until_date = datetime.utcnow().isoformat() + "Z"
예제 #9
0
 def __init__(self, *args, **kwargs):
     wsgiapp = pylons.test.pylonsapp
     config = wsgiapp.config
     self.app = webtest.TestApp(wsgiapp)
     url._push_object(URLGenerator(config['routes.map'], environ))
     self.__setattrs__()
     self.__setcreateparams__()
     TestCase.__init__(self, *args, **kwargs)
예제 #10
0
    def __init__(self, *args, **kwargs):
        import sys
        self.wsgiapp = pylons.test.pylonsapp
        self.config = self.wsgiapp.config
        self.app = fixture.TestApp(self.wsgiapp)
        url._push_object(URLGenerator(self.config['routes.map'], environ))

        TestRollback.__init__(self, *args, **kwargs)
예제 #11
0
    def __init__(self, *args, **kwargs):
        wsgiapp = pylons.test.pylonsapp
        config = wsgiapp.config

        self.app = TestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        self.Session = Session
        self.index_location = config['app_conf']['index_dir']
        TestCase.__init__(self, *args, **kwargs)
예제 #12
0
def init_stack(config=None):
    if not config:
        config = pylons.test.pylonsapp.config
    url._push_object(URLGenerator(config['routes.map'], environ))
    pylons.app_globals._push_object(config['pylons.app_globals'])
    pylons.config._push_object(config)
    pylons.tmpl_context._push_object(ContextObj())
    # Initialize a translator for tests that utilize i18n
    translator = _get_translator(pylons.config.get('lang'))
    pylons.translator._push_object(translator)
예제 #13
0
 def __call__(self, req):
     results = self.map.routematch(environ=req.environ)
     if not results:
         return exc.HTTPNotFound()
     match, route = results
     url = URLGenerator(self.map, req.environ)
     req.match = match
     req.route = route
     controller = match['controller'](req, url, self.config, self)
     return controller()
예제 #14
0
    def __init__(self, *args, **kwargs):
        wsgiapp = pylons.test.pylonsapp
        config = wsgiapp.config
        self.app = TestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        # should perhaps be in setup
        pylons.app_globals._push_object(Globals(config))
        # pylons.app_globals._pop_object() # should perhaps be in teardown

        super(TestControllerBase, self).__init__(*args, **kwargs)
예제 #15
0
 def _inject_url_generator_for_request(self, request):
     url_mapper = self.pylons_config['routes.map']
     url_generator = URLGenerator(url_mapper, request.environ)
     
     routes_dict = url_mapper.match(environ=request.environ)
     request.environ.update({
         'routes.url': url_generator,
         'wsgiorg.routing_args': (url_generator, routes_dict),
         'pylons.routes_dict': routes_dict,
     })
     return url_generator
예제 #16
0
    def _url(self, req, *args, **kw):
        """Generate an URL pointing to some REST service.

        `req` is the current request.

        Arguments and keywords are passed on to the generated
        :class:`routes.util.URLGenerator` instance. So you can use it
        like the `url` method described in the `routes` docs, except
        that you have to pass in the `req` parameter first.
        """
        url = URLGenerator(self.map, req.environ)
        return url(*args, **kw)
예제 #17
0
    def __init__(self, *args, **kwargs):
        if pylons.test.pylonsapp:
            wsgiapp = pylons.test.pylonsapp
        else:
            wsgiapp = loadapp('config:%s' % config['__file__'])
        self.app = TestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        # should perhaps be in setup
        pylons.app_globals._push_object(Globals())
        # pylons.app_globals._pop_object() # should perhaps be in teardown

        super(TestControllerBase, self).__init__(*args, **kwargs)
예제 #18
0
    def __init__(self, *args, **kwargs):
        '''
        initialize the test class
        '''

        wsgiapp = pylons.test.pylonsapp
        self.app = webtest.TestApp(wsgiapp)

        self.session = 'justatest'
        self.resolvers = {}  # Set up of resolvers in create_common_resolvers

        # dict of all autheticated users cookies
        self.user_service = {}

        url._push_object(URLGenerator(config['routes.map'], environ))
        unittest2.TestCase.__init__(self, *args, **kwargs)

        self.appconf = config
        self.here = self.appconf.get('here')

        self.fixture_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'functional',
            'fixtures',
        )

        # ------------------------------------------------------------------ --

        current_webtest = LooseVersion(
            pkg_resources.get_distribution('webtest').version
        )
        if current_webtest <= LooseVersion('2.0.14'):
            # Fix application cookies for localhost for webtest versions
            # 2.0.0 to 2.0.14 (https://github.com/Pylons/webtest/issues/84)
            # The CookiePolicy code is taken from webtest

            class CookiePolicy(cookielib.DefaultCookiePolicy):
                """A subclass of DefaultCookiePolicy to allow cookie set for
                Domain=localhost."""

                def return_ok_domain(self, cookie, request):
                    if cookie.domain == '.localhost':
                        return True
                    return cookielib.DefaultCookiePolicy.return_ok_domain(
                        self, cookie, request)

                def set_ok_domain(self, cookie, request):
                    if cookie.domain == '.localhost':
                        return True
                    return cookielib.DefaultCookiePolicy.set_ok_domain(
                        self, cookie, request)

            self.app.cookiejar = cookielib.CookieJar(policy=CookiePolicy())
예제 #19
0
def fake_request(pylons_config,
                 server_name='mediadrop.example',
                 language='en',
                 method='GET',
                 request_uri='/',
                 post_vars=None,
                 registry=None):
    paste_registry = registry or _paste_registry(pylons.request)
    app_globals = pylons_config['pylons.app_globals']

    if post_vars and method.upper() != 'POST':
        raise ValueError(
            'You must not specify post_vars for request method %r' % method)
    wsgi_environ = create_wsgi_environ('http://%s%s' %
                                       (server_name, request_uri),
                                       method.upper(),
                                       request_body=post_vars)
    wsgi_environ['paste.registry'] = paste_registry
    request = Request(wsgi_environ, charset='utf-8')
    request.language = language
    request.settings = app_globals.settings
    register_instance(paste_registry, 'request', request)
    response = Response(content_type='application/xml', charset='utf-8')
    register_instance(paste_registry, 'response', response)
    setup_session(paste_registry, if_not_registered=True)

    routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
    register_instance(paste_registry, 'url', routes_url)

    # Use ContextObj() when we get rid of 'pylons.strict_tmpl_context=False' in
    # mediadrop.lib.environment
    tmpl_context = AttribSafeContextObj()
    tmpl_context.paginators = Bunch()
    register_instance(paste_registry, 'tmpl_context', tmpl_context)
    # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
    # use the '.c' alias instead.
    pylons.c = pylons.tmpl_context
    register_instance(paste_registry, 'c', tmpl_context)

    engines = create_tw_engine_manager(app_globals)
    host_framework = PylonsHostFramework(engines=engines)
    paste_registry.register(tw.framework, host_framework)
    setup_translator(language=language,
                     registry=paste_registry,
                     locale_dirs=pylons_config.get('locale_dirs'))

    wsgi_environ.update({
        'pylons.pylons': pylons,
        'paste.registry': paste_registry,
        'routes.url': routes_url,
    })
    return request
예제 #20
0
    def __init__(self, *args, **kwargs):
        wsgiapp = loadapp('config:test.ini', relative_to=conf_dir)
        config = wsgiapp.config
        pylons.app_globals._push_object(config['pylons.app_globals'])
        pylons.config._push_object(config)

        # Initialize a translator for tests that utilize i18n
        translator = _get_translator(pylons.config.get('lang'))
        pylons.translator._push_object(translator)

        url._push_object(URLGenerator(config['routes.map'], environ))
        self.app = TestApp(wsgiapp)
        TestCase.__init__(self, *args, **kwargs)
예제 #21
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        url = URLGenerator(self.mapper, environ)
        environ['routes.url'] = url

        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self
        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError(
                'No routes match. Provide a fallback to avoid this.')
        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
            del kargs['controller']
        except:
            raise TypeError(
                'Controller is not set, or not formatted in the form "my.module.name:MyControllerName".'
            )
        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except:
            raise ImportError(
                'Controller %s from module %s could not be initialized.' %
                (class_name, module_name))
        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in [
                    'get', 'post', 'head', 'options', 'put', 'delete', 'trace'
            ]:
                action = None
        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except Exception, e:
                controller.handle_exception(e, self.__debug)
            response.wsgi_write(start_response)
            return ['']
예제 #22
0
def _init_stack(config=None, environ=None):
    if not config:
        config = pylons.test.pylonsapp.config
    if not environ:
        environ = {}
    pylons.url._push_object(URLGenerator(config['routes.map'], environ or {}))
    pylons.app_globals._push_object(config['pylons.app_globals'])
    pylons.config._push_object(config)
    pylons.tmpl_context._push_object(ContextObj())
    # Initialize a translator for tests that utilize i18n
    translator = _get_translator(pylons.config.get('lang'))
    pylons.translator._push_object(translator)
    pylons.session._push_object(SessionObject(environ or {}))
    pylons.request._push_object(webob.Request.blank('', environ=environ))
예제 #23
0
    def __init__(self, *args, **kwargs):
        wsgiapp = pylons.test.pylonsapp
        config = wsgiapp.config
        self.app = OptionsTestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        TestCase.__init__(self, *args, **kwargs)
        self.from_date = datetime(1990, 1, 1).isoformat() + "Z"
        self.controllerName = None

        def get_wsgiapp():
            return wsgiapp

        wsgi_intercept.add_wsgi_intercept('localhost', 80, get_wsgiapp)
        wsgi_intercept.add_wsgi_intercept('127.0.0.1', 80, get_wsgiapp)
예제 #24
0
def fake_request(pylons_config,
                 server_name='mediacore.example',
                 language='en',
                 method='GET',
                 request_uri='/',
                 post_vars=None):
    app_globals = pylons_config['pylons.app_globals']
    pylons.app_globals._push_object(app_globals)

    if post_vars and method.upper() != 'POST':
        raise ValueError(
            'You must not specify post_vars for request method %r' % method)
    wsgi_environ = create_wsgi_environ('http://%s%s' %
                                       (server_name, request_uri),
                                       method.upper(),
                                       request_body=post_vars)
    request = Request(wsgi_environ, charset='utf-8')
    request.language = language
    request.settings = app_globals.settings
    pylons.request._push_object(request)
    response = Response(content_type='application/xml', charset='utf-8')
    pylons.response._push_object(response)

    session = SessionObject(wsgi_environ)
    pylons.session._push_object(session)

    routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
    pylons.url._push_object(routes_url)

    # Use ContextObj() when we get rid of 'pylons.strict_tmpl_context=False' in
    # mediacore.lib.environment
    tmpl_context = AttribSafeContextObj()
    tmpl_context.paginators = Bunch()
    pylons.tmpl_context._push_object(tmpl_context)
    # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
    # use the '.c' alias instead.
    pylons.c = pylons.tmpl_context

    paste_registry = Registry()
    paste_registry.prepare()
    engines = create_tw_engine_manager(app_globals)
    host_framework = PylonsHostFramework(engines=engines)
    paste_registry.register(tw.framework, host_framework)
    setup_translator(language=language, registry=paste_registry)

    wsgi_environ.update({
        'pylons.pylons': pylons,
        'paste.registry': paste_registry,
    })
    return request
예제 #25
0
    def __init__(self, *args, **kwargs):
        '''
        initialize the test class
        '''

        wsgiapp = pylons.test.pylonsapp
        self.app = webtest.TestApp(wsgiapp)
        self.session = 'justatest'
        self.resolvers = {}  # Set up in create_common_resolvers

        url._push_object(URLGenerator(config['routes.map'], environ))
        unittest2.TestCase.__init__(self, *args, **kwargs)

        self.appconf = config
예제 #26
0
def fake_request(pylons_config, server_name='mediadrop.example', language='en',
                 method='GET', request_uri='/', post_vars=None):
    app_globals = pylons_config['pylons.app_globals']
    pylons.app_globals._push_object(app_globals)
    
    if post_vars and method.upper() != 'POST':
        raise ValueError('You must not specify post_vars for request method %r' % method)
    wsgi_environ = create_wsgi_environ('http://%s%s' % (server_name, request_uri),
        method.upper(), request_body=post_vars)
    request = Request(wsgi_environ, charset='utf-8')
    request.language = language
    request.settings = app_globals.settings
    pylons.request._push_object(request)
    response = Response(content_type='application/xml', charset='utf-8')
    pylons.response._push_object(response)
    
    session = SessionObject(wsgi_environ)
    pylons.session._push_object(session)

    routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
    pylons.url._push_object(routes_url)

    # TODO: Use ContextObj() for Pylons 0.10
    tmpl_context = AttribSafeContextObj()
    tmpl_context.paginators = Bunch()
    pylons.tmpl_context._push_object(tmpl_context)
    # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
    # use the '.c' alias instead.
    pylons.c = pylons.tmpl_context
    
    paste_registry = Registry()
    paste_registry.prepare()
    engines = create_tw_engine_manager(app_globals)
    host_framework = PylonsHostFramework(engines=engines)
    paste_registry.register(tw.framework, host_framework)
    
    mediacore_i18n_path = os.path.join(os.path.dirname(mediacore.__file__), 'i18n')
    translator = Translator(language, dict(mediacore=mediacore_i18n_path))
    # not sure why but sometimes pylons.translator is not a StackedObjectProxy
    # but just a regular Translator.
    if not hasattr(pylons.translator, '_push_object'):
        pylons.translator = StackedObjectProxy()
    paste_registry.replace(pylons.translator, translator)
    
    wsgi_environ.update({
        'pylons.pylons': pylons,
        'paste.registry': paste_registry,
    })
    return request
예제 #27
0
 def _inject_url_generator_for_request(self, request):
     url_mapper = add_routes(create_mapper(self.pylons_config))
     url_generator = URLGenerator(url_mapper, request.environ)
     
     match = re.search('^.*?/([^/]+)(?:/([^/]+))?$', request.environ['PATH_INFO'])
     controller = match.group(1)
     action = match.group(2) or 'index'
     
     request.environ.update({
         'routes.url': url_generator,
         'wsgiorg.routing_args': (
             url_generator,
             dict(controller=controller, action=action),
         )
     })
     return url_generator
예제 #28
0
파일: wsgi.py 프로젝트: faramirs/wot
    def __call__(self, req):
        match = self._match(req)

        if not match:
            return webob.exc.HTTPNotFound()

        req.urlvars = match
        link = URLGenerator(self.mapper, req.environ)

        data = None
        name = match['controller'].__name__
        if name in self.registory:
            data = self.registory[name]

        controller = match['controller'](req, link, data, **self.config)
        return controller(req)
예제 #29
0
        def __init__(self, *args, **kwargs):
            super(TestController2, self).__init__(*args, **kwargs)

            # In case we detach controller from previous standard version,
            # we need to implement (at least for short amount of time)
            # support for Pylons and WebTest.
            import webtest
            import pylons.test
            from routes.util import URLGenerator

            environ = {}
            wsgiapp = pylons.test.pylonsapp
            config = pylons.test.pylonsapp.config

            self.app = webtest.TestApp(wsgiapp, environ)
            self.session = 'justatest'
            #self.appconf = config

            # Configure url ...
            url._push_object(URLGenerator(config['routes.map'], environ))

            # -------------------------------------------------------------- --

            current_webtest = LooseVersion(
                pkg_resources.get_distribution('webtest').version)
            if current_webtest <= LooseVersion('2.0.14'):
                # Fix application cookies for localhost for webtest versions
                # 2.0.0 to 2.0.14 (https://github.com/Pylons/webtest/issues/84)
                # The CookiePolicy code is taken from webtest

                class CookiePolicy(cookielib.DefaultCookiePolicy):
                    """A subclass of DefaultCookiePolicy to allow cookie set
                    for Domain=localhost."""
                    def return_ok_domain(self, cookie, request):
                        if cookie.domain == '.localhost':
                            return True
                        return cookielib.DefaultCookiePolicy.return_ok_domain(
                            self, cookie, request)

                    def set_ok_domain(self, cookie, request):
                        if cookie.domain == '.localhost':
                            return True
                        return cookielib.DefaultCookiePolicy.set_ok_domain(
                            self, cookie, request)

                self.app.cookiejar = cookielib.CookieJar(policy=CookiePolicy())
예제 #30
0
    def __call__(self, req, start_response):
        match = self._match(req)
        print "Here 4"
        if not match:
            return webob.exc.HTTPNotFound()

        req.start_response = start_response
        req.urlvars = match
        link = URLGenerator(self.mapper, req.environ)

        data = None
        name = match['controller'].__name__
        if name in self.registory:
            data = self.registory[name]

        controller = match['controller'](req, link, data, **self.config)
        controller.parent = self
        return controller(req)