Exemplo n.º 1
0
    def _create_request(self, authname='anonymous', **kwargs):
        kw = {
            'path_info': '/',
            'perm': MockPerm(),
            'args': _RequestArgs(),
            'href': self.env.href,
            'abs_href': self.env.abs_href,
            'tz': utc,
            'locale': None,
            'lc_time': locale_en,
            'session': DetachedSession(self.env, authname),
            'authname': authname,
            'chrome': {
                'notices': [],
                'warnings': []
            },
            'method': None,
            'get_header': lambda v: None,
            'is_xhr': False,
            'form_token': None
        }
        if 'args' in kwargs:
            kw['args'].update(kwargs.pop('args'))
        kw.update(kwargs)

        def redirect(url, permanent=False):
            raise RequestDone

        return Mock(add_redirect_listener=lambda x: [].append(x),
                    redirect=redirect,
                    **kw)
Exemplo n.º 2
0
 def _create_request(self, authname='anonymous', **kwargs):
     kw = {'path_info': '/', 'perm': MockPerm(), 'args': _RequestArgs(),
           'href': self.env.href, 'abs_href': self.env.abs_href,
           'tz': utc, 'locale': None, 'lc_time': locale_en,
           'session': {}, 'authname': authname,
           'chrome': {'notices': [], 'warnings': []},
           'method': None, 'get_header': lambda v: None, 'is_xhr': False,
           'form_token': None}
     if 'args' in kwargs:
         kw['args'].update(kwargs.pop('args'))
     kw.update(kwargs)
     def redirect(url, permanent=False):
         raise RequestDone
     return Mock(add_redirect_listener=lambda x: [].append(x),
                 redirect=redirect, **kw)
Exemplo n.º 3
0
    def test_tag_query_save(self):
        """Save timeline tag query string in session."""
        self.assertEqual('tag_query', self.tef.key)

        from trac.timeline.web_ui import TimelineModule
        TimelineModule(self.env)
        perms = PermissionSystem(self.env)
        perms.grant_permission('anonymous', 'TAGS_VIEW')
        perms.grant_permission('anonymous', 'TIMELINE_VIEW')

        req = self._create_request(args=_RequestArgs(tag_query='query_str'),
                                   path_info='/timeline', method='GET')
        dispatcher = RequestDispatcher(self.env)
        self.assertRaises(RequestDone, dispatcher.dispatch, req)
        self.assertEqual('query_str', req.session['timeline.tag_query'])
Exemplo n.º 4
0
    def test_tag_query_save(self):
        """Save timeline tag query string in session."""
        self.assertEqual('tag_query', self.tef.key)

        from trac.timeline.web_ui import TimelineModule
        TimelineModule(self.env)
        perms = PermissionSystem(self.env)
        perms.grant_permission('anonymous', 'TAGS_VIEW')
        perms.grant_permission('anonymous', 'TIMELINE_VIEW')

        req = self._create_request(args=_RequestArgs(tag_query='query_str'),
                                   path_info='/timeline',
                                   method='GET')
        dispatcher = RequestDispatcher(self.env)
        self.assertRaises(RequestDone, dispatcher.dispatch, req)
        self.assertEqual('query_str', req.session['timeline.tag_query'])
Exemplo n.º 5
0
 def parse_query_string(self, query_string):
     """Parse a query string into a _RequestArgs."""
     args = _RequestArgs()
     for arg in query_string.split('&'):
         nv = arg.split('=', 1)
         if len(nv) == 2:
             (name, value) = nv
         else:
             (name, value) = (nv[0], '')
         name = urllib2.unquote(name.replace('+', ' '))
         if isinstance(name, unicode):
             name = name.encode('utf-8')
         value = urllib2.unquote(value.replace('+', ' '))
         if not isinstance(value, unicode):
             value = unicode(value, 'utf-8')
         if name in args:
             if isinstance(args[name], list):
                 args[name].append(value)
             else:
                 args[name] = [args[name], value]
         else:
             args[name] = value
     return args
Exemplo n.º 6
0
 def parse_query_string(self, query_string):
     """Parse a query string into a _RequestArgs."""
     args = _RequestArgs()
     for arg in query_string.split('&'):
         nv = arg.split('=', 1)
         if len(nv) == 2:
             (name, value) = nv
         else:
             (name, value) = (nv[0], '')
         name = urllib2.unquote(name.replace('+', ' '))
         if isinstance(name, unicode):
             name = name.encode('utf-8')
         value = urllib2.unquote(value.replace('+', ' '))
         if not isinstance(value, unicode):
             value = unicode(value, 'utf-8')
         if name in args:
             if isinstance(args[name], list):
                 args[name].append(value)
             else:
                 args[name] = [args[name], value]
         else:
             args[name] = value
     return args
Exemplo n.º 7
0
def MockRequest(env, **kwargs):
    """Request object for testing. Keyword arguments populate an
    `environ` dictionary and the callbacks.

    If `authname` is specified in a keyword arguments a `PermissionCache`
    object is created, otherwise if `authname` is not specified or is
    `None` a `MockPerm` object is used and the `authname` is set to
    'anonymous'.

    The following keyword arguments are commonly used:
    :keyword args: dictionary of request arguments
    :keyword authname: the name of the authenticated user, or 'anonymous'
    :keyword method: the HTTP request method
    :keyword path_info: the request path inside the application

    Additionally `cookie`, `format`, `language`, `lc_time`, `locale`,
    `remote_addr`, `remote_user`, `script_name`, `server_name`, `server_port`
    and `tz` can be specified as keyword arguments.

    :since: 1.0.11
    """

    authname = kwargs.get('authname')
    if authname is None:
        authname = 'anonymous'
        perm = MockPerm()
    else:
        perm = PermissionCache(env, authname)

    def convert(val):
        if isinstance(val, bool):
            return unicode(int(val))
        elif isinstance(val, numbers.Real):
            return unicode(val)
        elif isinstance(val, (list, tuple)):
            return [convert(v) for v in val]
        else:
            return val

    if 'arg_list' in kwargs:
        arg_list = [(k, convert(v)) for k, v in kwargs['arg_list']]
        args = arg_list_to_args(arg_list)
    else:
        args = _RequestArgs()
        args.update(
            (k, convert(v)) for k, v in kwargs.get('args', {}).iteritems())
        arg_list = [(name, value) for name in args
                    for value in args.getlist(name)]

    environ = {
        'trac.base_url': env.abs_href(),
        'wsgi.url_scheme': 'http',
        'HTTP_ACCEPT_LANGUAGE': kwargs.get('language', ''),
        'HTTP_COOKIE': kwargs.get('cookie', ''),
        'PATH_INFO': kwargs.get('path_info', '/'),
        'REQUEST_METHOD': kwargs.get('method', 'GET'),
        'REMOTE_ADDR': kwargs.get('remote_addr', '127.0.0.1'),
        'REMOTE_USER': kwargs.get('remote_user', authname),
        'SCRIPT_NAME': kwargs.get('script_name', '/trac.cgi'),
        'SERVER_NAME': kwargs.get('server_name', 'localhost'),
        'SERVER_PORT': kwargs.get('server_port', '80'),
    }
    for key in environ:
        if isinstance(environ[key], unicode):
            environ[key] = environ[key].encode('utf-8')

    status_sent = []
    headers_sent = {}
    response_sent = io.BytesIO()

    def start_response(status, headers, exc_info=None):
        status_sent.append(status)
        headers_sent.update(dict(headers))
        return response_sent.write

    req = Mock(Request, environ, start_response)
    req.status_sent = status_sent
    req.headers_sent = headers_sent
    req.response_sent = response_sent

    req.callbacks.update({
        'arg_list':
        lambda req: arg_list,
        'args':
        lambda req: args,
        'authname':
        lambda req: authname,
        'chrome':
        Chrome(env).prepare_request,
        'form_token':
        lambda req: kwargs.get('form_token', 0),
        'lc_time':
        lambda req: kwargs.get('lc_time', locale_en),
        'locale':
        lambda req: kwargs.get('locale'),
        'perm':
        lambda req: perm,
        'session':
        lambda req: Session(env, req),
        'tz':
        lambda req: kwargs.get('tz', utc),
        'use_xsendfile':
        lambda req: False,
        'xsendfile_header':
        lambda req: None,
        'configurable_headers':
        lambda req: [],
    })

    return req
Exemplo n.º 8
0
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

import re
from functools import partial

from trac.test import Mock, MockPerm
from trac.web.api import _RequestArgs

_TAG_SPLIT = re.compile('[,\s]+')

# DEVEL: This needs monitoring for possibly varying endpoint requirements.
MockReq = partial(Mock,
                  args=_RequestArgs(),
                  authname='anonymous',
                  perm=MockPerm(),
                  session=dict(),
                  is_authenticated=lambda a: a != 'anonymous')


def query_realms(query, all_realms):
    realms = []
    for realm in all_realms:
        if re.search('(^|\W)realm:%s(\W|$)' % realm, query):
            realms.append(realm)
    return realms


def split_into_tags(text):
Exemplo n.º 9
0
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

import re
from functools import partial

from trac.test import Mock, MockPerm
from trac.web.api import _RequestArgs

_TAG_SPLIT = re.compile('[,\s]+')


# DEVEL: This needs monitoring for possibly varying endpoint requirements.
MockReq = partial(Mock, args=_RequestArgs(), authname='anonymous',
                  perm=MockPerm(), session=dict())


def query_realms(query, all_realms):
    realms = []
    for realm in all_realms:
        if re.search('(^|\W)realm:%s(\W|$)' % realm, query):
            realms.append(realm)
    return realms


def split_into_tags(text):
    """Split plain text into tags."""
    return set(filter(None, [tag.strip() for tag in _TAG_SPLIT.split(text)]))
Exemplo n.º 10
0
def MockRequest(env, **kwargs):
    """Request object for testing. Keyword arguments populate an
    `environ` dictionary and the callbacks.

    If `authname` is specified in a keyword arguments a `PermissionCache`
    object is created, otherwise if `authname` is not specified or is
    `None` a `MockPerm` object is used and the `authname` is set to
    'anonymous'.

    The following keyword arguments are commonly used:
    :keyword args: dictionary of request arguments
    :keyword authname: the name of the authenticated user, or 'anonymous'
    :keyword method: the HTTP request method
    :keyword path_info: the request path inside the application

    Additionally `format`, `locale`, `lc_time` and `tz` can be
    specified as keyword arguments.

    :since: 1.0.11
    """

    authname = kwargs.get('authname')
    if authname is None:
        authname = 'anonymous'
        perm = MockPerm()
    else:
        perm = PermissionCache(env, authname)

    args = _RequestArgs()
    args.update(kwargs.get('args', {}))

    environ = {
        'trac.base_url': env.abs_href(),
        'wsgi.url_scheme': 'http',
        'HTTP_ACCEPT_LANGUAGE': 'en-US',
        'PATH_INFO': kwargs.get('path_info', '/'),
        'REQUEST_METHOD': kwargs.get('method', 'GET'),
        'REMOTE_ADDR': '127.0.0.1',
        'REMOTE_USER': authname,
        'SCRIPT_NAME': '/trac.cgi',
        'SERVER_NAME': 'localhost',
        'SERVER_PORT': '80',
    }

    status_sent = []
    headers_sent = {}
    response_sent = StringIO.StringIO()

    def start_response(status, headers, exc_info=None):
        status_sent.append(status)
        headers_sent.update(dict(headers))
        return response_sent.write

    req = Mock(Request, environ, start_response)
    req.status_sent = status_sent
    req.headers_sent = headers_sent
    req.response_sent = response_sent

    from trac.web.chrome import Chrome
    req.callbacks.update({
        'arg_list':
        None,
        'args':
        lambda req: args,
        'authname':
        lambda req: authname,
        'chrome':
        Chrome(env).prepare_request,
        'form_token':
        lambda req: kwargs.get('form_token'),
        'languages':
        Request._parse_languages,
        'lc_time':
        lambda req: kwargs.get('lc_time', locale_en),
        'locale':
        lambda req: kwargs.get('locale'),
        'incookie':
        Request._parse_cookies,
        'perm':
        lambda req: perm,
        'session':
        lambda req: Session(env, req),
        'tz':
        lambda req: kwargs.get('tz', utc),
        'use_xsendfile':
        False,
        'xsendfile_header':
        None,
        '_inheaders':
        Request._parse_headers
    })

    return req