Example #1
0
    def test_path_regex_variables(self):
        @Router.app
        def path_regex_var_handler(req, var):
            return Response(body=var,
                            content_type=CONTENT_TYPE_HTML,
                            charset='UTF-8')

        self.app.use('/{var:\w\w\w\w\w}', Router.METHOD_GET,
                     path_regex_var_handler)

        req = BaseRequest.blank('/value')
        res = req.get_response(self.app)

        self.assertIsInstance(res, Response)
        self.assertEqual(res.status, '200 OK')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.body, b'value')
        self.assertEqual(res.charset, 'UTF-8')
        self.assertEqual(res.content_type, 'text/html')

        req_invalid = BaseRequest.blank('/123456')
        res_invalid = req_invalid.get_response(self.app)
        self.assertIsInstance(res_invalid, Response)
        self.assertEqual(res_invalid.status, '404 Not Found')
        self.assertEqual(res_invalid.status_code, 404)
Example #2
0
    def test_from_fieldstorage_with_quoted_printable_encoding(self):
        from cgi import FieldStorage

        from webob.multidict import MultiDict
        from webob.request import BaseRequest

        multipart_type = "multipart/form-data; boundary=foobar"
        from io import BytesIO

        body = (b"--foobar\r\n"
                b'Content-Disposition: form-data; name="title"\r\n'
                b'Content-type: text/plain; charset="ISO-2022-JP"\r\n'
                b"Content-Transfer-Encoding: quoted-printable\r\n"
                b"\r\n"
                b"=1B$B$3$s$K$A$O=1B(B"
                b"\r\n"
                b"--foobar--")
        multipart_body = BytesIO(body)
        environ = BaseRequest.blank("/").environ
        environ.update(CONTENT_TYPE=multipart_type)
        environ.update(REQUEST_METHOD="POST")
        environ.update(CONTENT_LENGTH=len(body))
        fs = FieldStorage(multipart_body, environ=environ)
        vars = MultiDict.from_fieldstorage(fs)
        self.assertEqual(vars["title"].encode("utf8"),
                         text_("こんにちは", "utf8").encode("utf8"))
Example #3
0
    def test_from_fieldstorage_with_quoted_printable_encoding(self):
        from cgi import FieldStorage
        from webob.request import BaseRequest
        from webob.multidict import MultiDict

        multipart_type = "multipart/form-data; boundary=foobar"
        from io import BytesIO

        body = (
            b"--foobar\r\n"
            b'Content-Disposition: form-data; name="title"\r\n'
            b'Content-type: text/plain; charset="ISO-2022-JP"\r\n'
            b"Content-Transfer-Encoding: quoted-printable\r\n"
            b"\r\n"
            b"=1B$B$3$s$K$A$O=1B(B"
            b"\r\n"
            b"--foobar--"
        )
        multipart_body = BytesIO(body)
        environ = BaseRequest.blank("/").environ
        environ.update(CONTENT_TYPE=multipart_type)
        environ.update(REQUEST_METHOD="POST")
        environ.update(CONTENT_LENGTH=len(body))
        fs = FieldStorage(multipart_body, environ=environ)
        vars = MultiDict.from_fieldstorage(fs)
        self.assertEqual(vars["title"].encode("utf8"), text_("こんにちは", "utf8").encode("utf8"))
Example #4
0
    def conditional_response_app(self, environ, start_response):
        """
        Like the normal __call__ interface, but checks conditional headers:

        * If-Modified-Since   (304 Not Modified; only on GET, HEAD)
        * If-None-Match       (304 Not Modified; only on GET, HEAD)
        * Range               (406 Partial Content; only on GET, HEAD)
        """
        req = BaseRequest(environ)
        headerlist = self._abs_headerlist(environ)
        method = environ.get('REQUEST_METHOD', 'GET')
        if method in self._safe_methods:
            status304 = False
            if req.if_none_match and self.etag:
                status304 = self.etag in req.if_none_match
            elif req.if_modified_since and self.last_modified:
                status304 = self.last_modified <= req.if_modified_since
            if status304:
                start_response('304 Not Modified', filter_headers(headerlist))
                return EmptyResponse(self._app_iter)
        if (req.range and self in req.if_range and self.content_range is None
                and method in ('HEAD', 'GET') and self.status_code == 200
                and self.content_length is not None):
            content_range = req.range.content_range(self.content_length)
            if content_range is None:
                iter_close(self._app_iter)
                body = bytes_("Requested range not satisfiable: %s" %
                              req.range)
                headerlist = [
                    ('Content-Length', str(len(body))),
                    ('Content-Range',
                     str(ContentRange(None, None, self.content_length))),
                    ('Content-Type', 'text/plain'),
                ] + filter_headers(headerlist)
                start_response('416 Requested Range Not Satisfiable',
                               headerlist)
                if method == 'HEAD':
                    return ()
                return [body]
            else:
                app_iter = self.app_iter_range(content_range.start,
                                               content_range.stop)
                if app_iter is not None:
                    # the following should be guaranteed by
                    # Range.range_for_length(length)
                    assert content_range.start is not None
                    headerlist = [
                        ('Content-Length',
                         str(content_range.stop - content_range.start)),
                        ('Content-Range', str(content_range)),
                    ] + filter_headers(headerlist, ('content-length', ))
                    start_response('206 Partial Content', headerlist)
                    if method == 'HEAD':
                        return EmptyResponse(app_iter)
                    return app_iter

        start_response(self.status, headerlist)
        if method == 'HEAD':
            return EmptyResponse(self._app_iter)
        return self._app_iter
Example #5
0
def test_set_response_status_bad():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    def status_test():
        res.status = 'ThisShouldFail'

    assert_raises(ValueError, status_test)
Example #6
0
def test_set_response_status_bad():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    def status_test():
        res.status = 'ThisShouldFail'

    assert_raises(ValueError, status_test)
Example #7
0
def test_set_response_status_bad():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)

    def status_test():
        res.status = "ThisShouldFail"

    with pytest.raises(ValueError):
        status_test()
Example #8
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie("x", "test")
    # utf8 encoded
    eq_(res.headers.getall("set-cookie"), ["x=test; Path=/"])
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank("/").get_response(r2)
    eq_(r2.headerlist, [("Content-Type", "text/html; charset=utf8"), ("Set-Cookie", "x=test; Path=/")])
Example #9
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie("x", text_(b"\N{BLACK SQUARE}", "unicode_escape"))
    # utf8 encoded
    eq_(res.headers.getall("set-cookie"), ['x="\\342\\226\\240"; Path=/'])
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank("/").get_response(r2)
    eq_(r2.headerlist, [("Content-Type", "text/html; charset=utf8"), ("Set-Cookie", 'x="\\342\\226\\240"; Path=/')])
Example #10
0
def test_set_response_status_bad():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)

    def status_test():
        res.status = "ThisShouldFail"

    with pytest.raises(ValueError):
        status_test()
Example #11
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie("x", "test")
    # utf8 encoded
    assert res.headers.getall("set-cookie") == ["x=test; Path=/"]
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank("/").get_response(r2)
    assert r2.headerlist == [
        ("Content-Type", "text/html; charset=UTF-8"),
        ("Set-Cookie", "x=test; Path=/"),
    ]
Example #12
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie('x', "test")
    # utf8 encoded
    assert res.headers.getall('set-cookie') == ['x=test; Path=/']
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank('/').get_response(r2)
    assert r2.headerlist == [
        ('Content-Type', 'text/html; charset=utf8'),
        ('Set-Cookie', 'x=test; Path=/'),
        ]
Example #13
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie('x', text_(b'\N{BLACK SQUARE}', 'unicode_escape'))
    # utf8 encoded
    eq_(res.headers.getall('set-cookie'), ['x="\\342\\226\\240"; Path=/'])
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank('/').get_response(r2)
    eq_(r2.headerlist, [
        ('Content-Type', 'text/html; charset=utf8'),
        ('Set-Cookie', 'x="\\342\\226\\240"; Path=/'),
    ])
Example #14
0
def test_user_agent_middleware__restrict(user_agent, expected_status,
                                         current_time):
    app = create_app()

    req = BaseRequest.blank("/")
    if user_agent is not None:
        req.user_agent = user_agent

    with freeze_time(current_time, tick=True):
        app = uut.user_agent_middleware(app)
        res = req.get_response(app)

    assert res.status_code == expected_status
Example #15
0
def test_cookies():
    res = Response()
    # test unicode value
    res.set_cookie('x', text_(b'\N{BLACK SQUARE}', 'unicode_escape'))
    # utf8 encoded
    eq_(res.headers.getall('set-cookie'), ['x="\\342\\226\\240"; Path=/'])
    r2 = res.merge_cookies(simple_app)
    r2 = BaseRequest.blank('/').get_response(r2)
    eq_(r2.headerlist,
        [('Content-Type', 'text/html; charset=utf8'),
        ('Set-Cookie', 'x="\\342\\226\\240"; Path=/'),
        ]
    )
Example #16
0
def test_response():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    assert res.status == "200 OK"
    assert res.status_code == 200
    assert res.body == "OK"
    assert res.charset == "UTF-8"
    assert res.content_type == "text/html"
    res.status = 404
    assert res.status == "404 Not Found"
    assert res.status_code == 404
    res.body = b"Not OK"
    assert b"".join(res.app_iter) == b"Not OK"
    res.charset = "iso8859-1"
    assert "text/html; charset=iso8859-1" == res.headers["content-type"]
    res.content_type = "text/xml"
    assert "text/xml; charset=UTF-8" == res.headers["content-type"]
    res.content_type = "text/xml; charset=UTF-8"
    assert "text/xml; charset=UTF-8" == res.headers["content-type"]
    res.headers = {"content-type": "text/html"}
    assert res.headers["content-type"] == "text/html"
    assert res.headerlist == [("content-type", "text/html")]
    res.set_cookie("x", "y")
    assert res.headers["set-cookie"].strip(";") == "x=y; Path=/"
    res.set_cookie(text_("x"), text_("y"))
    assert res.headers["set-cookie"].strip(";") == "x=y; Path=/"
    res = Response("a body", "200 OK", content_type="text/html")
    res.encode_content()
    assert res.content_encoding == "gzip"
    assert (
        res.body ==
        b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xffKTH\xcaO\xa9\x04\x00\xf6\x86GI\x06\x00\x00\x00"
    )
    res.decode_content()
    assert res.content_encoding is None
    assert res.body == b"a body"
    res.set_cookie("x", text_(b"foo"))  # test unicode value
    with pytest.raises(TypeError):
        Response(app_iter=iter(["a"]), body="somebody")
    del req.environ
    with pytest.raises(TypeError):
        Response(charset=None,
                 content_type="image/jpeg",
                 body=text_(b"unicode body"))
    with pytest.raises(TypeError):
        Response(wrong_key="dummy")
    with pytest.raises(TypeError):
        resp = Response()
        resp.body = text_(b"unicode body")
Example #17
0
def test_response():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    assert res.status == '200 OK'
    assert res.status_code == 200
    assert res.body == "OK"
    assert res.charset == "UTF-8"
    assert res.content_type == 'text/html'
    res.status = 404
    assert res.status == '404 Not Found'
    assert res.status_code == 404
    res.body = b'Not OK'
    assert b''.join(res.app_iter) == b'Not OK'
    res.charset = 'iso8859-1'
    assert 'text/html; charset=iso8859-1' == res.headers['content-type']
    res.content_type = 'text/xml'
    assert 'text/xml; charset=UTF-8' == res.headers['content-type']
    res.content_type = 'text/xml; charset=UTF-8'
    assert 'text/xml; charset=UTF-8' == res.headers['content-type']
    res.headers = {'content-type': 'text/html'}
    assert res.headers['content-type'] == 'text/html'
    assert res.headerlist == [('content-type', 'text/html')]
    res.set_cookie('x', 'y')
    assert res.headers['set-cookie'].strip(';') == 'x=y; Path=/'
    res.set_cookie(text_('x'), text_('y'))
    assert res.headers['set-cookie'].strip(';') == 'x=y; Path=/'
    res = Response('a body', '200 OK', content_type='text/html')
    res.encode_content()
    assert res.content_encoding == 'gzip'
    assert res.body == b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xffKTH\xcaO\xa9\x04\x00\xf6\x86GI\x06\x00\x00\x00'
    res.decode_content()
    assert res.content_encoding is None
    assert res.body == b'a body'
    res.set_cookie('x', text_(b'foo')) # test unicode value
    with pytest.raises(TypeError):
        Response(app_iter=iter(['a']),
                 body="somebody")
    del req.environ
    with pytest.raises(TypeError):
        Response(charset=None,
                 content_type='image/jpeg',
                 body=text_(b"unicode body"))
    with pytest.raises(TypeError):
        Response(wrong_key='dummy')
    with pytest.raises(TypeError):
        resp = Response()
        resp.body = text_(b"unicode body")
Example #18
0
def test_response():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    assert res.status == '200 OK'
    assert res.status_code == 200
    assert res.body == "OK"
    assert res.charset == "UTF-8"
    assert res.content_type == 'text/html'
    res.status = 404
    assert res.status == '404 Not Found'
    assert res.status_code == 404
    res.body = b'Not OK'
    assert b''.join(res.app_iter) == b'Not OK'
    res.charset = 'iso8859-1'
    assert 'text/html; charset=iso8859-1' == res.headers['content-type']
    res.content_type = 'text/xml'
    assert 'text/xml; charset=UTF-8' == res.headers['content-type']
    res.content_type = 'text/xml; charset=UTF-8'
    assert 'text/xml; charset=UTF-8' == res.headers['content-type']
    res.headers = {'content-type': 'text/html'}
    assert res.headers['content-type'] == 'text/html'
    assert res.headerlist == [('content-type', 'text/html')]
    res.set_cookie('x', 'y')
    assert res.headers['set-cookie'].strip(';') == 'x=y; Path=/'
    res.set_cookie(text_('x'), text_('y'))
    assert res.headers['set-cookie'].strip(';') == 'x=y; Path=/'
    res = Response('a body', '200 OK', content_type='text/html')
    res.encode_content()
    assert res.content_encoding == 'gzip'
    assert res.body == b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xffKTH\xcaO\xa9\x04\x00\xf6\x86GI\x06\x00\x00\x00'
    res.decode_content()
    assert res.content_encoding is None
    assert res.body == b'a body'
    res.set_cookie('x', text_(b'foo')) # test unicode value
    with pytest.raises(TypeError):
        Response(app_iter=iter(['a']),
                 body="somebody")
    del req.environ
    with pytest.raises(TypeError):
        Response(charset=None,
                 content_type='image/jpeg',
                 body=text_(b"unicode body"))
    with pytest.raises(TypeError):
        Response(wrong_key='dummy')
    with pytest.raises(TypeError):
        resp = Response()
        resp.body = text_(b"unicode body")
Example #19
0
def test_response():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    assert res.status == "200 OK"
    assert res.status_code == 200
    assert res.body == "OK"
    assert res.charset == "UTF-8"
    assert res.content_type == "text/html"
    res.status = 404
    assert res.status == "404 Not Found"
    assert res.status_code == 404
    res.body = b"Not OK"
    assert b"".join(res.app_iter) == b"Not OK"
    res.charset = "iso8859-1"
    assert "text/html; charset=iso8859-1" == res.headers["content-type"]
    res.content_type = "text/xml"
    assert "text/xml; charset=UTF-8" == res.headers["content-type"]
    res.content_type = "text/xml; charset=UTF-8"
    assert "text/xml; charset=UTF-8" == res.headers["content-type"]
    res.headers = {"content-type": "text/html"}
    assert res.headers["content-type"] == "text/html"
    assert res.headerlist == [("content-type", "text/html")]
    res.set_cookie("x", "y")
    assert res.headers["set-cookie"].strip(";") == "x=y; Path=/"
    res.set_cookie(text_("x"), text_("y"))
    assert res.headers["set-cookie"].strip(";") == "x=y; Path=/"
    res = Response("a body", "200 OK", content_type="text/html")
    res.encode_content()
    assert res.content_encoding == "gzip"
    assert (
        res.body
        == b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xffKTH\xcaO\xa9\x04\x00\xf6\x86GI\x06\x00\x00\x00"
    )
    res.decode_content()
    assert res.content_encoding is None
    assert res.body == b"a body"
    res.set_cookie("x", text_(b"foo"))  # test unicode value
    with pytest.raises(TypeError):
        Response(app_iter=iter(["a"]), body="somebody")
    del req.environ
    with pytest.raises(TypeError):
        Response(charset=None, content_type="image/jpeg", body=text_(b"unicode body"))
    with pytest.raises(TypeError):
        Response(wrong_key="dummy")
    with pytest.raises(TypeError):
        resp = Response()
        resp.body = text_(b"unicode body")
Example #20
0
def test_user_agent_middleware__slowdown(user_agent, sleep_seconds,
                                         expected_time, current_time):
    app = create_app(sleep_seconds=sleep_seconds)

    req = BaseRequest.blank("/")
    if user_agent is not None:
        req.user_agent = user_agent

    with freeze_time(current_time, tick=True):
        app = uut.user_agent_middleware(app)

        before_time = time.time()
        res = req.get_response(app)
        request_time = time.time() - before_time

    assert res.status_code == 200
    assert request_time >= expected_time
Example #21
0
    def test_simple_request(self):
        @Router.app
        def simple_request_handler(req):
            return Response(body='OK',
                            content_type=CONTENT_TYPE_HTML,
                            charset='UTF-8')

        self.app.use('/', Router.METHOD_GET, simple_request_handler)

        req = BaseRequest.blank('/')
        res = req.get_response(self.app)

        self.assertIsInstance(res, Response)
        self.assertEqual(res.status, '200 OK')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.body, b'OK')
        self.assertEqual(res.charset, 'UTF-8')
        self.assertEqual(res.content_type, 'text/html')
Example #22
0
 def test_from_fieldstorage_with_charset(self):
     from cgi import FieldStorage
     from webob.request import BaseRequest
     from webob.multidict import MultiDict
     multipart_type = 'multipart/form-data; boundary=foobar'
     from io import BytesIO
     body = (b'--foobar\r\n'
             b'Content-Disposition: form-data; name="title"\r\n'
             b'Content-type: text/plain; charset="ISO-2022-JP"\r\n'
             b'\r\n'
             b'\x1b$B$3$s$K$A$O\x1b(B'
             b'\r\n'
             b'--foobar--')
     multipart_body = BytesIO(body)
     environ = BaseRequest.blank('/').environ
     environ.update(CONTENT_TYPE=multipart_type)
     environ.update(REQUEST_METHOD='POST')
     environ.update(CONTENT_LENGTH=len(body))
     fs = FieldStorage(multipart_body, environ=environ)
     vars = MultiDict.from_fieldstorage(fs)
     self.assertEqual(vars['title'].encode('utf8'),
                      text_('こんにちは', 'utf8').encode('utf8'))
Example #23
0
 def test_from_fieldstorage_with_charset(self):
     from cgi import FieldStorage
     from webob.request import BaseRequest
     from webob.multidict import MultiDict
     multipart_type = 'multipart/form-data; boundary=foobar'
     from io import BytesIO
     body = (
         b'--foobar\r\n'
         b'Content-Disposition: form-data; name="title"\r\n'
         b'Content-type: text/plain; charset="ISO-2022-JP"\r\n'
         b'\r\n'
         b'\x1b$B$3$s$K$A$O\x1b(B'
         b'\r\n'
         b'--foobar--')
     multipart_body = BytesIO(body)
     environ = BaseRequest.blank('/').environ
     environ.update(CONTENT_TYPE=multipart_type)
     environ.update(REQUEST_METHOD='POST')
     environ.update(CONTENT_LENGTH=len(body))
     fs = FieldStorage(multipart_body, environ=environ)
     vars = MultiDict.from_fieldstorage(fs)
     self.assertEqual(vars['title'].encode('utf8'),
                      text_('こんにちは', 'utf8').encode('utf8'))
Example #24
0
def test_set_response_status_str_no_reason():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    res.status = '200'
    assert res.status_int == 200
    assert res.status == '200 OK'
Example #25
0
def test_set_response_status_binary():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    res.status == b'200 OK'
    assert res.status_int == 200
    assert res.status == '200 OK'
Example #26
0
def test_set_response_status_str_no_reason():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status = "200"
    assert res.status_code == 200
    assert res.status == "200 OK"
Example #27
0
def request_for_cell(app):
    environ = BaseRequest.blank('test').environ
    return Mock(spec=EkklesiaPortalRequest(environ, app))
Example #28
0
 def _makeRequest(self):
     from webob.request import BaseRequest
     req = BaseRequest.blank('/')
     return req
Example #29
0
def test_set_response_status_code_generic_reason():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status_code = 299
    assert res.status_code == 299
    assert res.status == "299 Success"
Example #30
0
def test_set_response_status_binary():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    res.status == b'200 OK'
    assert res.status_int == 200
    assert res.status == '200 OK'
Example #31
0
def test_set_response_status_code_generic_reason():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status_code = 299
    assert res.status_code == 299
    assert res.status == "299 Success"
Example #32
0
def test_set_response_status_binary():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status == b"200 OK"
    assert res.status_code == 200
    assert res.status == "200 OK"
Example #33
0
def test_set_response_status_str_generic_reason():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    res.status = '299'
    assert res.status_code == 299
    assert res.status == '299 Success'
Example #34
0
def test_set_response_status_code():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    res.status_code = 200
    assert res.status_code == 200
    assert res.status == '200 OK'
Example #35
0
def test_set_response_status_binary():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status == b"200 OK"
    assert res.status_code == 200
    assert res.status == "200 OK"
Example #36
0
    def _makeRequest(self):
        from webob.request import BaseRequest

        req = BaseRequest.blank("/")

        return req
Example #37
0
def test_set_response_status_str_no_reason():
    req = BaseRequest.blank("/")
    res = req.get_response(simple_app)
    res.status = "200"
    assert res.status_code == 200
    assert res.status == "200 OK"