Example #1
0
def test_from_text_file():
    res = Response("test")
    inp = io.StringIO(text_(str(res), "utf-8"))
    equal_resp(res, inp)
    res = Response(app_iter=iter([b"test ", b"body"]), content_type="text/plain")
    inp = io.StringIO(text_(str(res), "utf-8"))
    equal_resp(res, inp)
Example #2
0
def test_from_text_file():
    res = Response("test")
    inp = io.StringIO(text_(str(res), "utf-8"))
    equal_resp(res, inp)
    res = Response(app_iter=iter([b"test ", b"body"]),
                   content_type="text/plain")
    inp = io.StringIO(text_(str(res), "utf-8"))
    equal_resp(res, inp)
Example #3
0
def test_from_text_file():
    res = Response('test')
    inp = io.StringIO(text_(str(res), 'utf-8'))
    equal_resp(res, inp)
    res = Response(app_iter=iter([b'test ', b'body']),
                   content_type='text/plain')
    inp = io.StringIO(text_(str(res), 'utf-8'))
    equal_resp(res, inp)
Example #4
0
def test_header_getter_fset_text_control_chars():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response
    resp = Response('aresp')
    desc = header_getter('AHEADER', '14.3')
    desc.fset(resp, text_('pylons\n'))
    with pytest.raises(ValueError):
        desc.fset(resp, text_('pylons\npyramid'))
Example #5
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 #6
0
def test_header_getter_fset_text_control_chars():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response
    resp = Response('aresp')
    desc = header_getter('AHEADER', '14.3')
    assert_raises(ValueError, desc.fset, resp, text_('\n'))
Example #7
0
def test_content_type_has_charset():
    res = Response(content_type='application/foo; charset=UTF-8',
                   body=text_(b'test'))
    assert res.body == b'test'
    assert res.content_type == 'application/foo'
    assert res.charset == 'UTF-8'
    assert res.headers['Content-Type'] == 'application/foo; charset=UTF-8'
Example #8
0
def test_doesnt_raise_with_charset_content_type_has_no_charset():
    res = Response(content_type='image/jpeg',
                   body=text_(b'test'),
                   charset='utf-8')
    assert res.body == b'test'
    assert res.content_type == 'image/jpeg'
    assert res.charset is None
Example #9
0
def html_escape(s):
    """HTML-escape a string or object

    This converts any non-string objects passed into it to strings
    (actually, using ``unicode()``).  All values returned are
    non-unicode strings (using ``&#num;`` entities for all non-ASCII
    characters).

    None is treated specially, and returns the empty string.
    """
    if s is None:
        return ''
    __html__ = getattr(s, '__html__', None)
    if __html__ is not None and callable(__html__):
        return s.__html__()
    if not isinstance(s, string_types):
        __unicode__ = getattr(s, '__unicode__', None)
        if __unicode__ is not None and callable(__unicode__):
            s = s.__unicode__()
        else:
            s = str(s)
    s = escape(s, True)
    if isinstance(s, text_type):
        s = s.encode('ascii', 'xmlcharrefreplace')
    return text_(s)
Example #10
0
 def test_itervalues_py3(self):
     val = text_(b"La Pe\xc3\xb1a", "utf-8")
     environ = {
         "HTTP_COOKIE": b'a=1; b="La Pe\\303\\261a"; c=3'.decode("utf-8")
     }
     inst = self._makeOne(environ)
     sorted(list(inst.values())) == ["1", "3", val]
 def test_itervalues_py3(self):
     val = text_(b'La Pe\xc3\xb1a', 'utf-8')
     environ = {
         'HTTP_COOKIE': b'a=1; b="La Pe\\303\\261a"; c=3'.decode('utf-8')
     }
     inst = self._makeOne(environ)
     sorted(list(inst.values())) == ['1', '3', val]
Example #12
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 #13
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 #14
0
def html_escape(s):
    """HTML-escape a string or object

    This converts any non-string objects passed into it to strings
    (actually, using ``unicode()``).  All values returned are
    non-unicode strings (using ``&#num;`` entities for all non-ASCII
    characters).

    None is treated specially, and returns the empty string.
    """
    if s is None:
        return ''
    __html__ = getattr(s, '__html__', None)
    if __html__ is not None and callable(__html__):
        return s.__html__()
    if not isinstance(s, string_types):
        __unicode__ = getattr(s, '__unicode__', None)
        if __unicode__ is not None and callable(__unicode__):
            s = s.__unicode__()
        else:
            s = str(s)
    s = escape(s, True)
    if isinstance(s, text_type):
        s = s.encode('ascii', 'xmlcharrefreplace')
    return text_(s)
Example #15
0
def test_unicode_cookies_error_raised():
    res = Response()
    with pytest.raises(ValueError):
        Response.set_cookie(
            res,
            'x',
            text_(b'\N{BLACK SQUARE}', 'unicode_escape'))
Example #16
0
 def test_iteritems(self):
     val = text_(b'La Pe\xc3\xb1a', 'utf-8')
     environ = {'HTTP_COOKIE': 'a=1; b="La Pe\\303\\261a"; c=3'}
     inst = self._makeOne(environ)
     self.assertEqual(sorted(list(inst.iteritems())), [('a', '1'),
                                                       ('b', val),
                                                       ('c', '3')])
Example #17
0
def test_content_type_has_charset():
    res = Response(content_type="application/foo; charset=UTF-8",
                   body=text_(b"test"))
    assert res.body == b"test"
    assert res.content_type == "application/foo"
    assert res.charset == "UTF-8"
    assert res.headers["Content-Type"] == "application/foo; charset=UTF-8"
Example #18
0
def test_doesnt_raise_with_charset_content_type_has_no_charset():
    res = Response(content_type="image/jpeg",
                   body=text_(b"test"),
                   charset="utf-8")
    assert res.body == b"test"
    assert res.content_type == "image/jpeg"
    assert res.charset is None
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_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 #21
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 #22
0
 def test_fset_nonascii(self):
     desc = self._callFUT("HTTP_X_AKEY", encattr="url_encoding")
     req = self._makeRequest()
     desc.fset(req, text_(b"\xc3\xab", "utf-8"))
     if PY3:
         self.assertEqual(req.environ["HTTP_X_AKEY"], b"\xc3\xab".decode("latin-1"))
     else:
         self.assertEqual(req.environ["HTTP_X_AKEY"], b"\xc3\xab")
Example #23
0
def test_header_getter_fset_text_control_chars():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    assert_raises(ValueError, desc.fset, resp, text_("\n"))
Example #24
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add('Set-Cookie', 'a=2; Path=/')
    res.headers.add('Set-Cookie', 'b=3; Path=/')
    res.unset_cookie('a')
    eq_(res.headers.getall('Set-Cookie'), ['b=3; Path=/'])
    res.unset_cookie(text_('b'))
    eq_(res.headers.getall('Set-Cookie'), [])
Example #25
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add("Set-Cookie", "a=2; Path=/")
    res.headers.add("Set-Cookie", "b=3; Path=/")
    res.unset_cookie("a")
    assert res.headers.getall("Set-Cookie") == ["b=3; Path=/"]
    res.unset_cookie(text_("b"))
    assert res.headers.getall("Set-Cookie") == []
Example #26
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add("Set-Cookie", "a=2; Path=/")
    res.headers.add("Set-Cookie", "b=3; Path=/")
    res.unset_cookie("a")
    eq_(res.headers.getall("Set-Cookie"), ["b=3; Path=/"])
    res.unset_cookie(text_("b"))
    eq_(res.headers.getall("Set-Cookie"), [])
Example #27
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add('Set-Cookie', 'a=2; Path=/')
    res.headers.add('Set-Cookie', 'b=3; Path=/')
    res.unset_cookie('a')
    assert res.headers.getall('Set-Cookie') == ['b=3; Path=/']
    res.unset_cookie(text_('b'))
    assert res.headers.getall('Set-Cookie') == []
Example #28
0
 def test_fset_nonascii(self):
     desc = self._callFUT('HTTP_X_AKEY', encattr='url_encoding')
     req = self._makeRequest()
     desc.fset(req, text_(b'\xc3\xab', 'utf-8'))
     if PY3:
         assert req.environ['HTTP_X_AKEY'] == b'\xc3\xab'.decode('latin-1')
     else:
         assert req.environ['HTTP_X_AKEY'] == b'\xc3\xab'
Example #29
0
def test_header_getter_fset_text():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response
    resp = Response('aresp')
    desc = header_getter('AHEADER', '14.3')
    desc.fset(resp, text_('avalue'))
    assert desc.fget(resp) == 'avalue'
 def test_iteritems_py3(self):
     val = text_(b'La Pe\xc3\xb1a', 'utf-8')
     environ = {
         'HTTP_COOKIE': b'a=1; b="La Pe\\303\\261a"; c=3'.decode('utf-8')
     }
     inst = self._makeOne(environ)
     assert sorted(list(inst.items())) == [('a', '1'), ('b', val),
                                           ('c', '3')]
Example #31
0
 def test_iteritems_py3(self):
     val = text_(b"La Pe\xc3\xb1a", "utf-8")
     environ = {
         "HTTP_COOKIE": b'a=1; b="La Pe\\303\\261a"; c=3'.decode("utf-8")
     }
     inst = self._makeOne(environ)
     assert sorted(list(inst.items())) == [("a", "1"), ("b", val),
                                           ("c", "3")]
Example #32
0
 def test_fset_nonascii(self):
     desc = self._callFUT('HTTP_X_AKEY', encattr='url_encoding')
     req = self._makeRequest()
     desc.fset(req, text_(b'\xc3\xab', 'utf-8'))
     if PY3:
         assert req.environ['HTTP_X_AKEY'] == b'\xc3\xab'.decode('latin-1')
     else:
         assert req.environ['HTTP_X_AKEY'] == b'\xc3\xab'
Example #33
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add('Set-Cookie', 'a=2; Path=/')
    res.headers.add('Set-Cookie', 'b=3; Path=/')
    res.unset_cookie('a')
    eq_(res.headers.getall('Set-Cookie'), ['b=3; Path=/'])
    res.unset_cookie(text_('b'))
    eq_(res.headers.getall('Set-Cookie'), [])
Example #34
0
def test_header_getter_fset_text():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response
    resp = Response('aresp')
    desc = header_getter('AHEADER', '14.3')
    desc.fset(resp, text_('avalue'))
    eq_(desc.fget(resp), 'avalue')
Example #35
0
def test_unset_cookie_key_in_cookies():
    res = Response()
    res.headers.add("Set-Cookie", "a=2; Path=/")
    res.headers.add("Set-Cookie", "b=3; Path=/")
    res.unset_cookie("a")
    assert res.headers.getall("Set-Cookie") == ["b=3; Path=/"]
    res.unset_cookie(text_("b"))
    assert res.headers.getall("Set-Cookie") == []
Example #36
0
def test_header_getter_fset_text():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    desc.fset(resp, text_("avalue"))
    assert desc.fget(resp) == "avalue"
Example #37
0
 def test_fget_nonascii(self):
     desc = self._callFUT('HTTP_X_AKEY', encattr='url_encoding')
     req = self._makeRequest()
     if PY3:
         req.environ['HTTP_X_AKEY'] = b'\xc3\xab'.decode('latin-1')
     else:
         req.environ['HTTP_X_AKEY'] = b'\xc3\xab'
     result = desc.fget(req)
     self.assertEqual(result, text_(b'\xc3\xab', 'utf-8'))
 def test_fget_nonascii(self):
     desc = self._callFUT('HTTP_X_AKEY', encattr='url_encoding')
     req = self._makeRequest()
     if PY3:
         req.environ['HTTP_X_AKEY'] = b'\xc3\xab'.decode('latin-1')
     else:
         req.environ['HTTP_X_AKEY'] = b'\xc3\xab'
     result = desc.fget(req)
     self.assertEqual(result, text_(b'\xc3\xab', 'utf-8'))
Example #39
0
def test_header_getter_fset_text_control_chars():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    with pytest.raises(ValueError):
        desc.fset(resp, text_("\n"))
Example #40
0
def test_header_getter_fset_text():
    from webob.compat import text_
    from webob.descriptors import header_getter
    from webob import Response

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    desc.fset(resp, text_("avalue"))
    eq_(desc.fget(resp), "avalue")
Example #41
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 #42
0
 def __setitem__(self, name, value):
     name = self._valid_cookie_name(name)
     if not isinstance(value, string_types):
         raise ValueError(value, "cookie value must be a string")
     if not isinstance(value, text_type):
         try:
             value = text_(value, "utf-8")
         except UnicodeDecodeError:
             raise ValueError(value, "cookie value must be utf-8 binary or unicode")
     self._mutate_header(name, value)
Example #43
0
def test_unicode_body():
    res = Response()
    res.charset = 'utf-8'
    bbody = b'La Pe\xc3\xb1a' # binary string
    ubody = text_(bbody, 'utf-8') # unicode string
    res.body = bbody
    assert res.unicode_body == ubody
    res.ubody = ubody
    assert res.body == bbody
    del res.ubody
    assert res.body == b''
Example #44
0
def test_unicode_body():
    res = Response()
    res.charset = "utf-8"
    bbody = b"La Pe\xc3\xb1a"  # binary string
    ubody = text_(bbody, "utf-8")  # unicode string
    res.body = bbody
    eq_(res.unicode_body, ubody)
    res.ubody = ubody
    eq_(res.body, bbody)
    del res.ubody
    eq_(res.body, b"")
Example #45
0
def test_unicode_body():
    res = Response()
    res.charset = "utf-8"
    bbody = b"La Pe\xc3\xb1a"  # binary string
    ubody = text_(bbody, "utf-8")  # unicode string
    res.body = bbody
    assert res.unicode_body == ubody
    res.ubody = ubody
    assert res.body == bbody
    del res.ubody
    assert res.body == b""
Example #46
0
def test_unicode_body():
    res = Response()
    res.charset = "utf-8"
    bbody = b"La Pe\xc3\xb1a"  # binary string
    ubody = text_(bbody, "utf-8")  # unicode string
    res.body = bbody
    assert res.unicode_body == ubody
    res.ubody = ubody
    assert res.body == bbody
    del res.ubody
    assert res.body == b""
Example #47
0
def test_unicode_body():
    res = Response()
    res.charset = 'utf-8'
    bbody = b'La Pe\xc3\xb1a' # binary string
    ubody = text_(bbody, 'utf-8') # unicode string
    res.body = bbody
    eq_(res.unicode_body, ubody)
    res.ubody = ubody
    eq_(res.body, bbody)
    del res.ubody
    eq_(res.body, b'')
Example #48
0
def no_escape(value):
    if value is None:
        return ''
    if not isinstance(value, text_type):
        if hasattr(value, '__unicode__'):
            value = value.__unicode__()
        if isinstance(value, bytes):
            value = text_(value, 'utf-8')
        else:
            value = text_type(value)
    return value
Example #49
0
def test_unicode_body():
    res = Response()
    res.charset = 'utf-8'
    bbody = b'La Pe\xc3\xb1a'  # binary string
    ubody = text_(bbody, 'utf-8')  # unicode string
    res.body = bbody
    eq_(res.unicode_body, ubody)
    res.ubody = ubody
    eq_(res.body, bbody)
    del res.ubody
    eq_(res.body, b'')
Example #50
0
def no_escape(value):
    if value is None:
        return ''
    if not isinstance(value, text_type):
        if hasattr(value, '__unicode__'):
            value = value.__unicode__()
        if isinstance(value, bytes):
            value = text_(value, 'utf-8')
        else:
            value = text_type(value)
    return value
Example #51
0
    def tapp(env, sr):
        req = Request(env)
        req = req.decode()

        v = req.POST[req.query_string]

        if hasattr(v, 'filename'):
            r = Response(text_('%s\n%r' % (v.filename, v.value)))
        else:
            r = Response(v)
        return r(env, sr)
Example #52
0
def no_escape(value):
    if value is None:
        return ""
    if not isinstance(value, text_type):
        if hasattr(value, "__unicode__"):
            value = value.__unicode__()
        if isinstance(value, bytes):
            value = text_(value, "utf-8")
        else:
            value = text_type(value)
    return value
Example #53
0
 def __setitem__(self, name, value):
     name = self._valid_cookie_name(name)
     if not isinstance(value, string_types):
         raise ValueError(value, 'cookie value must be a string')
     if not isinstance(value, text_type):
         try:
             value = text_(value, 'utf-8')
         except UnicodeDecodeError:
             raise ValueError(
                 value, 'cookie value must be utf-8 binary or unicode')
     self._mutate_header(name, value)
Example #54
0
 def _valid_cookie_name(self, name):
     if not isinstance(name, string_types):
         raise TypeError(name, 'cookie name must be a string')
     if not isinstance(name, text_type):
         name = text_(name, 'utf-8')
     try:
         bytes_cookie_name = bytes_(name, 'ascii')
     except UnicodeEncodeError:
         raise TypeError('cookie name must be encodable to ascii')
     if not _valid_cookie_name(bytes_cookie_name):
         raise TypeError('cookie name must be valid according to RFC 6265')
     return name
Example #55
0
    def test_listextend(self):
        class Other:
            def items(self):
                return [text_("\xe9"), "e", "f", 1]

        other = Other()
        d = self._get_instance()
        d.extend(other)

        _list = [text_("\xe9"), "e", r"f", 1]
        for v in _list:
            self.assertTrue(v in d._items)
Example #56
0
    def test_listextend(self):
        class Other:
            def items(self):
                return [text_('\xe9'), 'e', 'f', 1]

        other = Other()
        d = self._get_instance()
        d.extend(other)

        _list = [text_('\xe9'), 'e', r'f', 1]
        for v in _list:
            self.assertTrue(v in d._items)