def testIfModSince(self):
        now = time.time()
        e = {
            'SERVER_NAME': 'foo',
            'SERVER_PORT': '80',
            'REQUEST_METHOD': 'GET'
        }

        # not modified since
        t_notmod = rfc1123_date(now)
        e['HTTP_IF_MODIFIED_SINCE'] = t_notmod
        out = StringIO()
        resp = HTTPResponse(stdout=out)
        req = HTTPRequest(sys.stdin, e, resp)
        data = self.file.index_html(req, resp)
        self.assertEqual(resp.getStatus(), 304)
        self.assertEqual(data, '')

        # modified since
        t_mod = rfc1123_date(now - 100)
        e['HTTP_IF_MODIFIED_SINCE'] = t_mod
        out = StringIO()
        resp = HTTPResponse(stdout=out)
        req = HTTPRequest(sys.stdin, e, resp)
        data = self.file.index_html(req, resp)
        self.assertEqual(resp.getStatus(), 200)
        self.assertEqual(data, str(self.file.data))
    def testIfModSince(self):
        now = time.time()
        e = {'SERVER_NAME': 'foo',
             'SERVER_PORT': '80',
             'REQUEST_METHOD': 'GET'}

        # not modified since
        t_notmod = rfc1123_date(now)
        e['HTTP_IF_MODIFIED_SINCE'] = t_notmod
        out = BytesIO()
        resp = HTTPResponse(stdout=out)
        req = HTTPRequest(sys.stdin, e, resp)
        data = self.file.index_html(req, resp)
        self.assertEqual(resp.getStatus(), 304)
        self.assertEqual(data, b'')

        # modified since
        t_mod = rfc1123_date(now - 100)
        e['HTTP_IF_MODIFIED_SINCE'] = t_mod
        out = BytesIO()
        resp = HTTPResponse(stdout=out)
        req = HTTPRequest(sys.stdin, e, resp)
        data = self.file.index_html(req, resp)
        self.assertEqual(resp.getStatus(), 200)
        self.assertEqual(data, bytes(self.file.data))
Beispiel #3
0
def publish_module_standard(module_name,
                            stdin=sys.stdin,
                            stdout=sys.stdout,
                            stderr=sys.stderr,
                            environ=os.environ,
                            debug=0,
                            request=None,
                            response=None):
    must_die = 0
    status = 200
    after_list = [None]
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            setRequest(request)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()
            clearRequest()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            reraise(must_die[0], must_die[1], must_die[2])
        finally:
            must_die = None

    return status
def http(request_string, handle_errors=True):
    """Execute an HTTP request string via the publisher

    This is used for HTTP doc tests.
    """
    import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error
    import rfc822
    from cStringIO import StringIO
    from ZPublisher.HTTPResponse import HTTPResponse as Response
    from ZServer.ZPublisher.Publish import publish_module

    # Commit work done by previous python code.
    transaction.commit()

    # Discard leading white space to make call layout simpler
    request_string = request_string.lstrip()

    # Split off and parse the command line
    l = request_string.find('\n')
    command_line = request_string[:l].rstrip()
    request_string = request_string[l + 1:]
    method, path, protocol = command_line.split()
    path = six.moves.urllib.parse.unquote(path)

    instream = StringIO(request_string)

    env = {
        "HTTP_HOST": 'localhost',
        "HTTP_REFERER": 'localhost',
        "REQUEST_METHOD": method,
        "SERVER_PROTOCOL": protocol,
    }

    p = path.split('?', 1)
    if len(p) == 1:
        env['PATH_INFO'] = p[0]
    elif len(p) == 2:
        [env['PATH_INFO'], env['QUERY_STRING']] = p
    else:
        raise TypeError('')

    header_output = HTTPHeaderOutput(
        protocol,
        ('x-content-type-warning', 'x-powered-by', 'bobo-exception-type',
         'bobo-exception-file', 'bobo-exception-value', 'bobo-exception-line'))

    headers = [
        split_header(header) for header in rfc822.Message(instream).headers
    ]

    # Store request body without headers
    instream = StringIO(instream.read())

    for name, value in headers:
        name = ('_'.join(name.upper().split('-')))
        if name not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            name = 'HTTP_' + name
        env[name] = value.rstrip()

    if 'HTTP_AUTHORIZATION' in env:
        env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])

    outstream = StringIO()
    response = Response(stdout=outstream, stderr=sys.stderr)

    publish_module('Zope2',
                   response=response,
                   stdin=instream,
                   environ=env,
                   debug=not handle_errors)

    header_output.setResponseStatus(response.getStatus(), response.errmsg)
    header_output.setResponseHeaders(response.headers)
    header_output.headersl.extend(response._cookie_list())
    header_output.appendResponseHeaders(response.accumulated_headers)

    sync()

    return DocResponseWrapper(response, outstream, path, header_output)
def process_wrapper(pid, request_body, request_environ):
    # Sets up everything we need to run a view method in a new Zope-ish
    # context, then runs it and stores the result for later retrieval.
    
    _process = None

    def my_mapply(object, positional=(), keyword={},
                   debug=None, maybe=None,
                   missing_name=None,
                   handle_class=None,
                   context=None, bind=0):
        
        if not isinstance(keyword, Mapping):
            keyword = {}
        keyword['process_id'] = pid
        
        args = (getattr(object, '__run__', object),)
        kwargs = dict(positional=positional,
                      keyword=keyword,
                      debug=debug,
                      maybe=maybe,
                      context=context,
                      bind=bind
                      )
        if missing_name is not None:
            kwargs['missing_name'] = missing_name
        if handle_class is not None:
            kwargs['handle_class'] = handle_class
        return mapply(*args, **kwargs)
        
    response = HTTPResponse(stdout=StringIO(), stderr=StringIO())
    request = HTTPRequest(StringIO(request_body), request_environ, response)
    
    request.set('process_id', pid)
    
    import Zope2
    app = Zope2.bobo_application.__bobo_traverse__(request)
    reg = getProcessRegistry(app)
    _process = reg.get(pid)
    
    
    # Run
    try:
        try:
            response = publish(request, 'Zope2', [None], mapply=my_mapply)
            
            # We can't just pass the response back, as the data streams will not
            # be set up right.
            attr = (hasattr(response, 'cookies') and 'cookies') or \
                   (hasattr(response, '_cookies') and '_cookies')
            cookies = deepcopy(getattr(response, attr))
            
            if IHTTPResponse.providedBy(response):
                _process['result'] = (response.getStatus(),
                                      dict(response.getHeaders()),
                                      cookies,
                                      response.consumeBody())
            else:
                # Currently, ZPublisher.HTTPResponse doesn't implement
                # IHTTPResponse, even though HTTPRequest implements
                # IHTTPRequest.
                _process['result'] = (response.getStatus(),
                                      dict(response.headers),
                                      cookies,
                                      response.body)
                
        except Exception, e:
            # Set result to the exception raised
            _process['result'] = e
            raise
        else:
Beispiel #6
0
def publish_module_standard(
        module_name,
        stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
        environ=os.environ, debug=0, request=None, response=None):
    must_die = 0
    status = 200
    after_list = [None]
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            setRequest(request)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()
            clearRequest()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            reraise(must_die[0], must_die[1], must_die[2])
        finally:
            must_die = None

    return status
def http(request_string, handle_errors=True):
    """Execute an HTTP request string via the publisher

    This is used for HTTP doc tests.
    """
    import urllib
    import rfc822
    from cStringIO import StringIO
    from ZPublisher.HTTPResponse import HTTPResponse as Response
    from ZServer.ZPublisher.Publish import publish_module

    # Commit work done by previous python code.
    transaction.commit()

    # Discard leading white space to make call layout simpler
    request_string = request_string.lstrip()

    # Split off and parse the command line
    l = request_string.find('\n')
    command_line = request_string[:l].rstrip()
    request_string = request_string[l + 1:]
    method, path, protocol = command_line.split()
    path = urllib.unquote(path)

    instream = StringIO(request_string)

    env = {"HTTP_HOST": 'localhost',
           "HTTP_REFERER": 'localhost',
           "REQUEST_METHOD": method,
           "SERVER_PROTOCOL": protocol,
           }

    p = path.split('?', 1)
    if len(p) == 1:
        env['PATH_INFO'] = p[0]
    elif len(p) == 2:
        [env['PATH_INFO'], env['QUERY_STRING']] = p
    else:
        raise TypeError('')

    header_output = HTTPHeaderOutput(
        protocol, ('x-content-type-warning', 'x-powered-by',
                   'bobo-exception-type', 'bobo-exception-file',
                   'bobo-exception-value', 'bobo-exception-line'))

    headers = [split_header(header)
               for header in rfc822.Message(instream).headers]

    # Store request body without headers
    instream = StringIO(instream.read())

    for name, value in headers:
        name = ('_'.join(name.upper().split('-')))
        if name not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            name = 'HTTP_' + name
        env[name] = value.rstrip()

    if 'HTTP_AUTHORIZATION' in env:
        env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])

    outstream = StringIO()
    response = Response(stdout=outstream, stderr=sys.stderr)

    publish_module('Zope2',
                   response=response,
                   stdin=instream,
                   environ=env,
                   debug=not handle_errors)

    header_output.setResponseStatus(response.getStatus(), response.errmsg)
    header_output.setResponseHeaders(response.headers)
    header_output.headersl.extend(response._cookie_list())
    header_output.appendResponseHeaders(response.accumulated_headers)

    sync()

    return DocResponseWrapper(response, outstream, path, header_output)
def process_wrapper(pid, request_body, request_environ):
    # Sets up everything we need to run a view method in a new Zope-ish
    # context, then runs it and stores the result for later retrieval.

    _process = None

    def my_mapply(object,
                  positional=(),
                  keyword={},
                  debug=None,
                  maybe=None,
                  missing_name=None,
                  handle_class=None,
                  context=None,
                  bind=0):

        if not isinstance(keyword, Mapping):
            keyword = {}
        keyword['process_id'] = pid

        args = (getattr(object, '__run__', object), )
        kwargs = dict(positional=positional,
                      keyword=keyword,
                      debug=debug,
                      maybe=maybe,
                      context=context,
                      bind=bind)
        if missing_name is not None:
            kwargs['missing_name'] = missing_name
        if handle_class is not None:
            kwargs['handle_class'] = handle_class
        return mapply(*args, **kwargs)

    response = HTTPResponse(stdout=StringIO(), stderr=StringIO())
    request = HTTPRequest(StringIO(request_body), request_environ, response)

    request.set('process_id', pid)

    import Zope2
    app = Zope2.bobo_application.__bobo_traverse__(request)
    reg = getProcessRegistry(app)
    _process = reg.get(pid)

    # Run
    try:
        try:
            response = publish(request, 'Zope2', [None], mapply=my_mapply)

            # We can't just pass the response back, as the data streams will not
            # be set up right.
            attr = (hasattr(response, 'cookies') and 'cookies') or \
                   (hasattr(response, '_cookies') and '_cookies')
            cookies = deepcopy(getattr(response, attr))

            if IHTTPResponse.providedBy(response):
                _process['result'] = (response.getStatus(),
                                      dict(response.getHeaders()), cookies,
                                      response.consumeBody())
            else:
                # Currently, ZPublisher.HTTPResponse doesn't implement
                # IHTTPResponse, even though HTTPRequest implements
                # IHTTPRequest.
                _process['result'] = (response.getStatus(),
                                      dict(response.headers), cookies,
                                      response.body)

        except Exception, e:
            # Set result to the exception raised
            _process['result'] = e
            raise
        else: