示例#1
0
    def test_multipart(self):
        """
        Test parsing data in multipart format: it should fill the C{files}
        attribute.
        """
        ctype = http_headers.MimeType('multipart', 'form-data',
                                      (('boundary', '---weeboundary'), ))
        content = """-----weeboundary\r
Content-Disposition: form-data; name="FileNameOne"; filename="myfilename"\r
Content-Type: text/html\r
\r
my great content wooo\r
-----weeboundary--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)

        def cb(ign):
            self.assertEquals(request.args, {})
            self.assertEquals(request.files.keys(), ['FileNameOne'])
            self.assertEquals(
                request.files.values()[0][0][:2],
                ('myfilename', http_headers.MimeType('text', 'html', {})))
            f = request.files.values()[0][0][2]
            self.assertEquals(f.read(), "my great content wooo")

        return server.parsePOSTData(request).addCallback(cb)
示例#2
0
    def test_multipartMaxSize(self):
        """
        Check that the C{maxSize} parameter makes the parsing raise an
        exception if the data is too big.
        """
        ctype = http_headers.MimeType('multipart', 'form-data',
                                      (('boundary', '---weeboundary'), ))
        content = """-----weeboundary\r
Content-Disposition: form-data; name="FileNameOne"; filename="myfilename"\r
Content-Type: text/html\r
\r
my great content wooo
and even more and more\r
-----weeboundary--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)

        def cb(res):
            self.assertEquals(res.response.description,
                              "Maximum length of 10 bytes exceeded.")

        return self.assertFailure(server.parsePOSTData(request, maxSize=10),
                                  http.HTTPError).addCallback(cb)
示例#3
0
文件: tap.py 项目: lzimm/360io
def makeService(config):
    if config['logfile']:
        logObserver = log.FileAccessLoggingObserver(config['logfile'])
    else:
        logObserver = log.DefaultCommonAccessLoggingObserver()

    if config['root']:
        if config['indexes']:
            config['root'].indexNames = config['indexes']

        root = log.LogWrapperResource(config['root'])

    s = Web2Service(logObserver)

    site = server.Site(root)
    chan = channel.HTTPFactory(site)

    if config['https']:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        i = internet.SSLServer(
            int(config['https']), chan,
            DefaultOpenSSLContextFactory(config['privkey'],
                                         config['certificate']))
        i.setServiceParent(s)

    strports.service(config['port'], chan).setServiceParent(s)

    return s
示例#4
0
    def test_unknownResource(self):
        """
        Test urlForResource() on unknown resource.
        """
        root = resource.Resource()
        child = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/")

        self.assertRaises(server.NoURLForResourceError, request.urlForResource,
                          child)
示例#5
0
 def test_wrongContentType(self):
     """
     Check that a content-type not handled raise a C{http.HTTPError}.
     """
     ctype = http_headers.MimeType('application', 'foobar')
     content = "key=value&multiple=two+words&multiple=more%20words"
     root = resource.Resource()
     request = SimpleRequest(server.Site(root), "GET", "/",
                             http_headers.Headers({'content-type': ctype}),
                             content)
     return self.assertFailure(server.parsePOSTData(request),
                               http.HTTPError)
示例#6
0
    def test_noContentType(self):
        """
        Parsing a request without content-type should succeed but should not
        fill the C{args} and C{files} attributes of the request.
        """
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/", content="foo")

        def cb(ign):
            self.assertEquals(request.args, {})
            self.assertEquals(request.files, {})

        return server.parsePOSTData(request).addCallback(cb)
示例#7
0
文件: test_cgi.py 项目: lzimm/360io
    def test_scriptsExecute(self):
        """
        Verify that CGI scripts within a CGIDirectory can actually be executed
        """

        cgiBinDir = os.path.abspath(self.mktemp())
        os.mkdir(cgiBinDir)

        root = twcgi.CGIDirectory(cgiBinDir)

        self.createScript(os.path.join(cgiBinDir, 'dummy'))

        cgiSubDir = os.path.join(cgiBinDir, 'sub')
        os.mkdir(cgiSubDir)

        self.createScript(os.path.join(cgiSubDir, 'dummy'))

        site = server.Site(root)

        request = SimpleRequest(site, "GET", "/dummy")

        d = request.locateResource('/dummy')

        def _firstResponse(res):
            self.failUnlessEqual(res, "cgi output%s" % os.linesep)

        def _firstRequest(resource):
            d1 = self.getPage(request, resource)
            d1.addCallback(_firstResponse)

            return d1

        d.addCallback(_firstRequest)

        def _secondResponse(res):
            self.failUnlessEqual(res, "cgi output%s" % os.linesep)

        def _secondRequest(ign):
            request = SimpleRequest(site, "GET", '/sub/dummy')

            d2 = request.locateResource('/sub/dummy')

            d2.addCallback(lambda resource: self.getPage(request, resource))
            d2.addCallback(_secondResponse)

            return d2

        d.addCallback(_secondRequest)

        return d
示例#8
0
    def test_locateResource(self):
        """
        Test urlForResource() on resource looked up via a locateResource() call.
        """
        root = resource.Resource()
        child = resource.Resource()
        root.putChild("foo", child)

        request = SimpleRequest(server.Site(root), "GET", "/")

        def gotResource(resource):
            self.assertEquals("/foo", request.urlForResource(resource))

        d = defer.maybeDeferred(request.locateResource, "/foo")
        d.addCallback(gotResource)
        return d
示例#9
0
    def test_otherErrors(self):
        """
        Test that errors durign parsing other than C{MimeFormatError} are
        propagated.
        """
        ctype = http_headers.MimeType('multipart', 'form-data',
                                      (('boundary', '---weeboundary'), ))
        # XXX: maybe this is not a good example
        # parseContentDispositionFormData could handle this problem
        content = """-----weeboundary\r
Content-Disposition: form-data; name="FileNameOne"; filename="myfilename and invalid data \r
-----weeboundary--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)
        return self.assertFailure(server.parsePOSTData(request), ValueError)
示例#10
0
    def test_multipartWithNoBoundary(self):
        """
        If the boundary type is not specified, parsing should fail with a
        C{http.HTTPError}.
        """
        ctype = http_headers.MimeType('multipart', 'form-data')
        content = """-----weeboundary\r
Content-Disposition: form-data; name="FileNameOne"; filename="myfilename"\r
Content-Type: text/html\r
\r
my great content wooo\r
-----weeboundary--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)
        return self.assertFailure(server.parsePOSTData(request),
                                  http.HTTPError)
示例#11
0
    def test_urlencoded(self):
        """
        Test parsing data in urlencoded format: it should end in the C{args}
        attribute.
        """
        ctype = http_headers.MimeType('application', 'x-www-form-urlencoded')
        content = "key=value&multiple=two+words&multiple=more%20words"
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)

        def cb(ign):
            self.assertEquals(request.files, {})
            self.assertEquals(request.args, {
                'multiple': ['two words', 'more words'],
                'key': ['value']
            })

        return server.parsePOSTData(request).addCallback(cb)
示例#12
0
    def test_mimeParsingError(self):
        """
        A malformed content should result in a C{http.HTTPError}.
        
        The tested content has an invalid closing boundary.
        """
        ctype = http_headers.MimeType('multipart', 'form-data',
                                      (('boundary', '---weeboundary'), ))
        content = """-----weeboundary\r
Content-Disposition: form-data; name="FileNameOne"; filename="myfilename"\r
Content-Type: text/html\r
\r
my great content wooo\r
-----weeoundary--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)
        return self.assertFailure(server.parsePOSTData(request),
                                  http.HTTPError)
示例#13
0
    def test_locateChildResource(self):
        """
        Test urlForResource() on deeply nested resource looked up via
        locateChildResource().
        """
        root = EmptyResource(self)
        root.expectedURI = "/"

        foo = EmptyResource(self)
        foo.expectedURI = "/foo"
        root.putChild("foo", foo)

        bar = EmptyResource(self)
        bar.expectedURI = "/foo/bar"
        foo.putChild("bar", bar)

        baz = EmptyResource(self)
        baz.expectedURI = "/foo/bar/b%20a%20z"
        bar.putChild("b a z", baz)

        request = SimpleRequest(server.Site(root), "GET", "/")

        def gotResource(resource):
            # Make sure locateChildResource() gave us the right answer
            self.assertEquals(resource, bar)

            return request.locateChildResource(
                resource, "b a z").addCallback(gotChildResource)

        def gotChildResource(resource):
            # Make sure locateChildResource() gave us the right answer
            self.assertEquals(resource, baz)

            self.assertEquals(resource.expectedURI,
                              request.urlForResource(resource))

        d = request.locateResource(bar.expectedURI)
        d.addCallback(gotResource)
        return d
示例#14
0
    def test_deferredLocateChild(self):
        """
        Test deferred value from locateChild()
        """
        class DeferredLocateChild(resource.Resource):
            def locateChild(self, req, segments):
                return defer.maybeDeferred(
                    super(DeferredLocateChild, self).locateChild, req,
                    segments)

        root = DeferredLocateChild()
        child = resource.Resource()
        root.putChild("foo", child)

        request = SimpleRequest(server.Site(root), "GET", "/foo")

        def gotResource(resource):
            self.assertEquals("/foo", request.urlForResource(resource))

        d = request.locateResource("/foo")
        d.addCallback(gotResource)
        return d
示例#15
0
    def test_maxFields(self):
        """
        Check that the C{maxSize} parameter makes the parsing raise an
        exception if the data contains too many fields.
        """
        ctype = http_headers.MimeType('multipart', 'form-data',
                                      (('boundary', '---xyz'), ))
        content = """-----xyz\r
Content-Disposition: form-data; name="foo"\r
\r
Foo Bar\r
-----xyz\r
Content-Disposition: form-data; name="foo"\r
\r
Baz\r
-----xyz\r
Content-Disposition: form-data; name="file"; filename="filename"\r
Content-Type: text/html\r
\r
blah\r
-----xyz\r
Content-Disposition: form-data; name="file"; filename="filename"\r
Content-Type: text/plain\r
\r
bleh\r
-----xyz--\r
"""
        root = resource.Resource()
        request = SimpleRequest(server.Site(root), "GET", "/",
                                http_headers.Headers({'content-type': ctype}),
                                content)

        def cb(res):
            self.assertEquals(res.response.description,
                              "Maximum number of fields 3 exceeded")

        return self.assertFailure(server.parsePOSTData(request, maxFields=3),
                                  http.HTTPError).addCallback(cb)
示例#16
0
        if os.path.exists(location):
            contentTypes.update(mimetypes.read_mime_types(location))

    return contentTypes


def getTypeAndEncoding(filename, types, encodings, defaultType):
    p, ext = os.path.splitext(filename)
    ext = ext.lower()
    if encodings.has_key(ext):
        enc = encodings[ext]
        ext = os.path.splitext(p)[1].lower()
    else:
        enc = None
    type = types.get(ext, defaultType)
    return type, enc


##
# Test code
##

if __name__ == '__builtin__':
    # Running from twistd -y
    from twisted.application import service, strports
    from hack.web2 import server
    res = File('/')
    application = service.Application("demo")
    s = strports.service('8080', server.Site(res))
    s.setServiceParent(application)
示例#17
0
 def chanrequest(self, root, uri, length, headers, method, version, prepath,
                 content):
     site = server.Site(root)
     return TestChanRequest(site, method, prepath, uri, length, headers,
                            version, content)