Esempio n. 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)
Esempio n. 2
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")
Esempio n. 3
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"))
Esempio n. 4
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"
Esempio n. 5
0
    def serialize(self, full=True):
        result = []
        add = result.append
        add(self.name + b"=" + _value_quote(self.value))

        if full:
            for k in _c_valkeys:
                v = self[k]

                if v:
                    info = _c_renames[k]
                    name = info["name"]
                    quoter = info["quoter"]
                    add(name + b"=" + quoter(v))
            expires = self[b"expires"]

            if expires:
                add(b"expires=" + expires)

            if self.secure:
                add(b"secure")

            if self.httponly:
                add(b"HttpOnly")

            if self.samesite:
                if not self.secure and self.samesite.lower() == b"none":
                    raise ValueError(
                        "Incompatible cookie attributes: "
                        "when the samesite equals 'none', then the secure must be True"
                    )
                add(b"SameSite=" + self.samesite)

        return text_(b"; ".join(result), "ascii")
Esempio n. 6
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
Esempio n. 7
0
def test_header_getter_fset_text():
    from webob import Response
    from webob.descriptors import header_getter

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    desc.fset(resp, text_("avalue"))
    assert desc.fget(resp) == "avalue"
Esempio n. 8
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") == []
Esempio n. 9
0
def test_header_getter_fset_text_control_chars():
    from webob import Response
    from webob.descriptors import header_getter

    resp = Response("aresp")
    desc = header_getter("AHEADER", "14.3")
    with pytest.raises(ValueError):
        desc.fset(resp, text_("\n"))
Esempio n. 10
0
def no_escape(value):
    if value is None:
        return ""

    if not isinstance(value, str):
        if isinstance(value, bytes):
            value = text_(value, "utf-8")
        else:
            value = str(value)

    return value
Esempio n. 11
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""
Esempio n. 12
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)
Esempio n. 13
0
def test_serialize_cookie_date():
    """
    Testing webob.cookies.serialize_cookie_date.
    Missing scenarios:
        * input value is an str, should be returned verbatim
        * input value is an int, should be converted to timedelta and we
          should continue the rest of the process
    """
    date_one = cookies.serialize_cookie_date(b"Tue, 04-Jan-2011 13:43:50 GMT")
    assert date_one == b"Tue, 04-Jan-2011 13:43:50 GMT"
    date_two = cookies.serialize_cookie_date(text_("Tue, 04-Jan-2011 13:43:50 GMT"))
    assert date_two == b"Tue, 04-Jan-2011 13:43:50 GMT"
    assert cookies.serialize_cookie_date(None) is None
    cdate_delta = cookies.serialize_cookie_date(timedelta(seconds=10))
    cdate_int = cookies.serialize_cookie_date(10)
    assert cdate_delta == cdate_int
Esempio n. 14
0
def test_unicode_cookies_warning_issued():
    import warnings

    cookies._should_raise = False

    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        # Trigger a warning.

        res = Response()
        res.set_cookie("x", text_(b"\\N{BLACK SQUARE}", "unicode_escape"))

        assert len(w) == 1
        assert issubclass(w[-1].category, RuntimeWarning) is True
        assert "ValueError" in str(w[-1].message)

    cookies._should_raise = True
Esempio n. 15
0
    def _mutate_header(self, name, value):
        header = self._environ.get("HTTP_COOKIE")
        had_header = header is not None
        header = header or ""

        header = header.encode("latin-1")
        bytes_name = bytes_(name, "ascii")

        if value is None:
            replacement = None
        else:
            bytes_val = _value_quote(bytes_(value, "utf-8"))
            replacement = bytes_name + b"=" + bytes_val
        matches = _rx_cookie.finditer(header)
        found = False

        for match in matches:
            start, end = match.span()
            match_name = match.group(1)

            if match_name == bytes_name:
                found = True

                if replacement is None:  # remove value
                    header = header[:start].rstrip(b" ;") + header[end:]
                else:  # replace value
                    header = header[:start] + replacement + header[end:]

                break
        else:
            if replacement is not None:
                if header:
                    header += b"; " + replacement
                else:
                    header = replacement

        if header:
            self._environ["HTTP_COOKIE"] = text_(header, "latin-1")
        elif had_header:
            self._environ["HTTP_COOKIE"] = ""

        return found
Esempio n. 16
0
def serialize_date(dt):
    if isinstance(dt, (bytes, str)):
        return text_(dt)

    if isinstance(dt, timedelta):
        dt = _now() + dt

    if isinstance(dt, (datetime, date)):
        dt = dt.timetuple()

    if isinstance(dt, (tuple, time.struct_time)):
        dt = calendar.timegm(dt)

    if not (isinstance(dt, float) or isinstance(dt, int)):
        raise ValueError(
            "You must pass in a datetime, date, time tuple, or integer object, "
            "not %r" % dt
        )

    return formatdate(dt, usegmt=True)
Esempio n. 17
0
def test_serialize_date():
    """Testing datetime_utils.serialize_date
    We need to verify the following scenarios:
        * on py3, passing an binary date, return the same date but str
        * on py2, passing an unicode date, return the same date but str
        * passing a timedelta, return now plus the delta
        * passing an invalid object, should raise ValueError
    """
    from webob.util import text_

    ret = datetime_utils.serialize_date("Mon, 20 Nov 1995 19:12:08 GMT")
    assert isinstance(ret, str)
    assert ret == "Mon, 20 Nov 1995 19:12:08 GMT"
    ret = datetime_utils.serialize_date(text_("Mon, 20 Nov 1995 19:12:08 GMT"))
    assert isinstance(ret, str)
    assert ret == "Mon, 20 Nov 1995 19:12:08 GMT"
    dt = formatdate(
        calendar.timegm(
            (datetime.datetime.now() + datetime.timedelta(1)).timetuple()),
        usegmt=True,
    )
    assert dt == datetime_utils.serialize_date(datetime.timedelta(1))
    with pytest.raises(ValueError):
        datetime_utils.serialize_date(None)
Esempio n. 18
0
def test_text_set_no_charset():
    res = Response()
    res.charset = None
    res.text = text_("abc")
    assert res.text == "abc"
Esempio n. 19
0
 def test_fget_nonascii(self):
     desc = self._callFUT("HTTP_X_AKEY", encattr="url_encoding")
     req = self._makeRequest()
     req.environ["HTTP_X_AKEY"] = str(b"\xc3\xab", "latin-1")
     result = desc.fget(req)
     assert result == text_(b"\xc3\xab", "utf-8")
Esempio n. 20
0
 def setUp(self):
     self._list = [("a", text_("\xe9")), ("a", "e"), ("a", "f"), ("b", "1")]
     self.data = multidict.MultiDict(self._list)
     self.d = self._get_instance()
Esempio n. 21
0
 def test_dict_of_lists(self):
     self.assertEqual(self.d.dict_of_lists(), {
         "a": [text_("\xe9"), "e", "f"],
         "b": ["1"]
     })
Esempio n. 22
0
 def items(self):
     return [("a", text_("\xe9")), ("a", "e"), ("a", "f"), ("b", 1)]
Esempio n. 23
0
def test_body_set_unicode():
    res = Response()
    with pytest.raises(TypeError):
        res.__setattr__("body", text_(b"abc"))
Esempio n. 24
0
def test_write_text():
    res = Response()
    res.body = b"abc"
    assert res.write(text_(b"a")) == 1
    assert res.text == "abca"
Esempio n. 25
0
def test_write_unicode_no_charset():
    res = Response(charset=None)
    with pytest.raises(TypeError):
        res.write(text_(b"a"))
Esempio n. 26
0
def test_write_unicode():
    res = Response()
    res.text = text_(b"La Pe\xc3\xb1a", "utf-8")
    assert res.write(text_(b"a")) == 1
    assert res.text, text_(b"La Pe\xc3\xb1aa" == "utf-8")
Esempio n. 27
0
def test_transcode_non_multipart():
    req = Request.blank("/?a", POST="%EF%F0%E8=%E2%E5%F2")
    req._content_type_raw = "application/x-www-form-urlencoded"
    req2 = req.decode("cp1251")
    assert text_(req2.body) == "%D0%BF%D1%80%D0%B8=%D0%B2%D0%B5%D1%82"
Esempio n. 28
0
def test_text_get_decode():
    res = Response()
    res.charset = "utf-8"
    res.body = b"La Pe\xc3\xb1a"
    assert res.text, text_(b"La Pe\xc3\xb1a")
Esempio n. 29
0
def test_transcode_non_form():
    req = Request.blank("/?a", POST="%EF%F0%E8=%E2%E5%F2")
    req._content_type_raw = "application/x-foo"
    req2 = req.decode("cp1251")
    assert text_(req2.body) == "%EF%F0%E8=%E2%E5%F2"
Esempio n. 30
0
def test_text_set_no_default_body_encoding():
    res = Response()
    res.charset = None
    res.default_body_encoding = None
    with pytest.raises(AttributeError):
        res.text = text_("abc")