def test_set_cookie_expires_is_datetime_tz_and_max_age_is_None(): import datetime res = Response() class FixedOffset(datetime.tzinfo): def __init__(self, offset, name): self.__offset = datetime.timedelta(minutes=offset) self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return datetime.timedelta(0) then = datetime.datetime.now(FixedOffset(60, 'UTC+1')) + datetime.timedelta(days=1) res.set_cookie('a', '1', expires=then) assert res.headerlist[-1][0] == 'Set-Cookie' val = [x.strip() for x in res.headerlist[-1][1].split(';')] assert len(val) == 4 val.sort() assert val[0] in ('Max-Age=86399', 'Max-Age=86400') assert val[1] == 'Path=/' assert val[2] == 'a=1' assert val[3].startswith('expires')
def test_content_length(): r0 = Response('x'*10, content_length=10) req_head = Request.blank('/', method='HEAD') r1 = req_head.get_response(r0) eq_(r1.status_code, 200) eq_(r1.body, b'') eq_(r1.content_length, 10) req_get = Request.blank('/') r2 = req_get.get_response(r0) eq_(r2.status_code, 200) eq_(r2.body, b'x'*10) eq_(r2.content_length, 10) r3 = Response(app_iter=[b'x']*10) eq_(r3.content_length, None) eq_(r3.body, b'x'*10) eq_(r3.content_length, 10) r4 = Response(app_iter=[b'x']*10, content_length=20) # wrong content_length eq_(r4.content_length, 20) assert_raises(AssertionError, lambda: r4.body) req_range = Request.blank('/', range=(0,5)) r0.conditional_response = True r5 = req_range.get_response(r0) eq_(r5.status_code, 206) eq_(r5.body, b'xxxxx') eq_(r5.content_length, 5)
def test_cache_expires_set(): res = Response() res.cache_expires = True assert ( repr(res.cache_control) == "<CacheControl 'max-age=0, must-revalidate, no-cache, no-store'>" )
def test_exec_controller_ok(self): '''This test case ensures that requested route is executed - success scenario.''' global_headers = {"X-Custom-Header1": "header1", "X-Custom-Header2": "header2"} def get(key): if key == "installed_middleware": return ["fantastico.middleware.tests.test_fantastico_app.MockedMiddleware"] if key == "global_response_headers": return global_headers self._settings_facade.get = get app_middleware = FantasticoApp(self._settings_facade_cls) response = Response() response.content_type = "text/html" response.text = "Hello world" self._controller.exec_logic = lambda request: response self.assertEqual([b"Hello world"], app_middleware(self._environ, Mock())) self.assertTrue(self._environ["test_wrapped_ok"]) self.assertEqual(global_headers["X-Custom-Header1"], response.headers["X-Custom-Header1"]) self.assertEqual(global_headers["X-Custom-Header2"], response.headers["X-Custom-Header2"])
def __init__( self, detail=None, headers=None, comment=None, body_template=None, json_formatter=None, **kw ): Response.__init__(self, status="%s %s" % (self.code, self.title), **kw) Exception.__init__(self, detail) if headers: self.headers.extend(headers) self.detail = detail self.comment = comment if body_template is not None: self.body_template = body_template self.body_template_obj = Template(body_template) if self.empty_body: del self.content_type del self.content_length if json_formatter is not None: self.json_formatter = json_formatter
def test_cache_expires_set_timedelta(): res = Response() from datetime import timedelta delta = timedelta(seconds=60) res.cache_expires(seconds=delta) assert res.cache_control.max_age == 60
def test__abs_headerlist_location_no_scheme(): res = Response() res.content_encoding = 'gzip' res.headerlist = [('Location', '/abc')] result = res._abs_headerlist({'wsgi.url_scheme': 'http', 'HTTP_HOST': 'example.com:80'}) assert result == [('Location', 'http://example.com/abc')]
def test_encode_content_gzip_notyet_gzipped(): res = Response() res.app_iter = io.BytesIO(b"foo") result = res.encode_content("gzip") eq_(result, None) eq_(res.content_length, 23) eq_(res.app_iter, [b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff", b"K\xcb\xcf\x07\x00", b"!es\x8c\x03\x00\x00\x00"])
def test_md5_etag(): res = Response() res.body = b"""\ In A.D. 2101 War was beginning. Captain: What happen ? Mechanic: Somebody set up us the bomb. Operator: We get signal. Captain: What ! Operator: Main screen turn on. Captain: It's You !! Cats: How are you gentlemen !! Cats: All your base are belong to us. Cats: You are on the way to destruction. Captain: What you say !! Cats: You have no chance to survive make your time. Cats: HA HA HA HA .... Captain: Take off every 'zig' !! Captain: You know what you doing. Captain: Move 'zig'. Captain: For great justice.""" res.md5_etag() assert res.etag assert '\n' not in res.etag assert res.etag == 'pN8sSTUrEaPRzmurGptqmw' assert res.content_md5 is None
def test_unicode_cookies_error_raised(): res = Response() with pytest.raises(ValueError): Response.set_cookie( res, 'x', text_(b'\N{BLACK SQUARE}', 'unicode_escape'))
def test_content_length(): r0 = Response('x' * 10, content_length=10) req_head = Request.blank('/', method='HEAD') r1 = req_head.get_response(r0) assert r1.status_code == 200 assert r1.body == b'' assert r1.content_length == 10 req_get = Request.blank('/') r2 = req_get.get_response(r0) assert r2.status_code == 200 assert r2.body == b'x' * 10 assert r2.content_length == 10 r3 = Response(app_iter=[b'x'] * 10) assert r3.content_length is None assert r3.body == b'x' * 10 assert r3.content_length == 10 r4 = Response(app_iter=[b'x'] * 10, content_length=20) # wrong content_length assert r4.content_length == 20 with pytest.raises(AssertionError): r4.body req_range = Request.blank('/', range=(0, 5)) r0.conditional_response = True r5 = req_range.get_response(r0) assert r5.status_code == 206 assert r5.body == b'xxxxx' assert r5.content_length == 5
def test_has_body(): empty = Response() assert not empty.has_body with_list = Response(app_iter=['1']) assert with_list.has_body with_empty_list = Response(app_iter=[b'']) assert not with_empty_list.has_body with_body = Response(body='Seomthing') assert with_body.has_body with_none_app_iter = Response(app_iter=None) assert not with_none_app_iter.has_body with_none_body = Response(body=None) assert not with_none_body.has_body # key feature: has_body should not read app_iter app_iter = iter(['1', '2']) not_iterating = Response(app_iter=app_iter) assert not_iterating.has_body assert next(app_iter) == '1' # messed with private attribute but method should nonetheless not # return True messing_with_privates = Response() messing_with_privates._app_iter = None assert not messing_with_privates.has_body
def test_body_get_is_none(): res = Response() res._app_iter = None with pytest.raises(TypeError): Response(app_iter=iter(['a']), body="somebody") with pytest.raises(AttributeError): res.__getattribute__('body')
def generate_response(self, environ, start_response): if self.content_length is not None: del self.content_length headerlist = list(self.headerlist) accept_value = environ.get('HTTP_ACCEPT', '') accept = MIMEAccept(accept_value) match = accept.best_match(['text/html', 'application/json']) if match == 'text/html': content_type = 'text/html' body = self.html_body(environ) elif match == 'application/json': content_type = 'application/json' body = self.json_body(environ) else: content_type = 'text/plain' body = self.plain_body(environ) extra_kw = {} if isinstance(body, text_type): extra_kw.update(charset='utf-8') resp = Response(body, status=self.status, headerlist=headerlist, content_type=content_type, **extra_kw ) resp.content_type = content_type return resp(environ, start_response)
def test_set_cookie_expires_is_datetime_tz_and_max_age_is_None(): import datetime res = Response() class FixedOffset(datetime.tzinfo): def __init__(self, offset, name): self.__offset = datetime.timedelta(minutes=offset) self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return datetime.timedelta(0) then = datetime.datetime.now(FixedOffset(60, "UTC+1")) + datetime.timedelta(days=1) res.set_cookie("a", "1", expires=then) assert res.headerlist[-1][0] == "Set-Cookie" val = [x.strip() for x in res.headerlist[-1][1].split(";")] assert len(val) == 4 val.sort() assert val[0] in ("Max-Age=86399", "Max-Age=86400") assert val[1] == "Path=/" assert val[2] == "a=1" assert val[3].startswith("expires")
def say_hello(self, request): tpl = self.load_template("/say_hello.html") response = Response(tpl) response.content_type = "text/html" return response
def test_app_iter_range_inner_method(): class FakeAppIter: def app_iter_range(self, start, stop): return "you win", start, stop res = Response(app_iter=FakeAppIter()) assert res.app_iter_range(30, 40), ("you win", 30 == 40)
def generate_response(self, environ, start_response): if self.content_length is not None: del self.content_length headerlist = list(self.headerlist) accept_value = environ.get("HTTP_ACCEPT", "") accept_header = create_accept_header(header_value=accept_value) acceptable_offers = accept_header.acceptable_offers( offers=["text/html", "application/json"] ) match = acceptable_offers[0][0] if acceptable_offers else None if match == "text/html": content_type = "text/html" body = self.html_body(environ) elif match == "application/json": content_type = "application/json" body = self.json_body(environ) else: content_type = "text/plain" body = self.plain_body(environ) resp = Response( body, status=self.status, headerlist=headerlist, content_type=content_type ) resp.content_type = content_type return resp(environ, start_response)
def __call__(self, req): results = self.map.routematch(environ=req.environ) if not results: return exc.HTTPNotFound() match, route = results link = URLGenerator(self.map, req.environ) if route.redirect: # Taken from the routes middleware module route_name = '_redirect_%s' % id(route) location = link(route_name, **match) # Build the response manually so we don't have to try to map the # route status to a specific webob exception redirect_response = Response(status=route.redirect_status) redirect_response.location = location return redirect_response match_controller = match.get('controller', None) if not callable(match_controller): log.error('Unsupported route match: %s', match) return exc.HTTPNotFound() req.urlvars = ((), match) req.link = link controller = match_controller(req, **self.config) return controller()
def test_location(): res = Response() res.location = '/test.html' assert res.location == '/test.html' req = Request.blank('/') assert req.get_response(res).location == 'http://localhost/test.html' res.location = '/test2.html' assert req.get_response(res).location == 'http://localhost/test2.html'
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'), [])
def test_body_file_del(): res = Response() res.body = b'123' assert res.content_length == 3 assert res.app_iter == [b'123'] del res.body_file assert res.body == b'' assert res.content_length == 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') == []
def test_location(): res = Response() res.location = '/test.html' eq_(res.location, '/test.html') req = Request.blank('/') eq_(req.get_response(res).location, 'http://localhost/test.html') res.location = '/test2.html' eq_(req.get_response(res).location, 'http://localhost/test2.html')
def test_cache_expires_set_zero(): res = Response() res.cache_expires(seconds=0) assert res.cache_control.no_store is True assert res.cache_control.no_cache == '*' assert res.cache_control.must_revalidate is True assert res.cache_control.max_age == 0 assert res.cache_control.post_check == 0
def test_body_file_del(): res = Response() res.body = b'123' eq_(res.content_length, 3) eq_(res.app_iter, [b'123']) del res.body_file eq_(res.body, b'') eq_(res.content_length, 0)
def test_cache_expires_set_zero(): res = Response() res.cache_expires(seconds=0) eq_(res.cache_control.no_store, True) eq_(res.cache_control.no_cache, '*') eq_(res.cache_control.must_revalidate, True) eq_(res.cache_control.max_age, 0) eq_(res.cache_control.post_check, 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") == []
def test_response_copy_content_md5(): res = Response() res.md5_etag(set_content_md5=True) assert res.content_md5 res2 = res.copy() assert res.content_md5 assert res2.content_md5 assert res.content_md5 == res2.content_md5
def test_location(): res = Response() res.location = "/test.html" eq_(res.location, "/test.html") req = Request.blank("/") eq_(req.get_response(res).location, "http://localhost/test.html") res.location = "/test2.html" eq_(req.get_response(res).location, "http://localhost/test2.html")
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')
def equal_resp(res, inp): res2 = Response.from_file(inp) assert res.body == res2.body assert res.headers == res2.headers
def test_text_del(): res = Response('123') del res.text assert res.body == b'' assert res.content_length == 0
def test_file_with_http_version_more_status(): inp = io.BytesIO(b'HTTP/1.1 404 Not Found\r\n\r\nSome data...') res = Response.from_file(inp) assert res.status_code == 404 assert res.status == '404 Not Found'
def test_resp_write_app_iter_non_list(): res = Response(app_iter=(b'a', b'b')) assert res.content_length is None res.write(b'c') assert res.body == b'abc' assert res.content_length == 3
def test_body_get_is_unicode(): res = Response(app_iter=(['x'] * 51 + [text_(b'x')])) with pytest.raises(TypeError): res.__getattribute__('body')
def test_body_set_not_unicode_or_str(): res = Response() with pytest.raises(TypeError): res.__setattr__('body', object())
def test_body_set_unicode(): res = Response() with pytest.raises(TypeError): res.__setattr__('body', text_(b'abc'))
def test_str_crlf(): res = Response('test') assert '\r\n' in str(res)
def test_write_unicode_no_charset(): res = Response(charset=None) with pytest.raises(TypeError): res.write(text_(b'a'))
def test_write_unicode(): res = Response() res.text = text_(b'La Pe\xc3\xb1a', 'utf-8') res.write(text_(b'a')) assert res.text, text_(b'La Pe\xc3\xb1aa' == 'utf-8')
def test_response_file_body_write_empty_body(): res = Response('') res.write('baz') assert res.app_iter == [b'', b'baz']
def test_response_write_non_str(): res = Response() with pytest.raises(TypeError): res.write(object())
def test_body_get_is_unicode_notverylong(): res = Response(app_iter=(text_(b'foo'), )) with pytest.raises(TypeError): res.__getattribute__('body')
def test_response_file_body_tell_text(): from webob.response import ResponseBodyFile rbo = ResponseBodyFile(Response()) assert rbo.tell() == 0 rbo.write('123456789') assert rbo.tell() == 9
def test_response_file_body_repr(): rbo = Response().body_file rbo.response = 'yo' assert repr(rbo) == "<body_file for 'yo'>"
def test_set_status(): res = Response() res.status = "200" assert res.status == "200 OK" with pytest.raises(TypeError): setattr(res, 'status', (200, ))
def test_file_with_http_version(): inp = io.BytesIO(b'HTTP/1.1 200 OK\r\n\r\nSome data...') res = Response.from_file(inp) assert res.status_code == 200 assert res.status == '200 OK'
def test_response_file_body_close_not_implemented(): rbo = Response().body_file with pytest.raises(NotImplementedError): rbo.close()
def test_text_set_not_unicode(): res = Response() res.charset = 'utf-8' with pytest.raises(TypeError): res.__setattr__('text', b'La Pe\xc3\xb1a')
def test_from_file_not_unicode_headers(): inp = io.BytesIO(b'200 OK\n\tContent-Type: text/html; charset=UTF-8') res = Response.from_file(inp) assert res.headerlist[0][0].__class__ == str
def test_from_file(): res = Response('test') inp = io.BytesIO(bytes_(str(res))) equal_resp(res, inp)
def test_file_bad_header(): file_w_bh = io.BytesIO(b'200 OK\nBad Header') with pytest.raises(ValueError): Response.from_file(file_w_bh)
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')
def test_from_file2(): res = Response(app_iter=iter([b'test ', b'body']), content_type='text/plain') inp = io.BytesIO(bytes_(str(res))) equal_resp(res, inp)
def test_text_set_no_charset(): res = Response() res.charset = None res.text = text_('abc') assert res.text == 'abc'
def test_text_get_no_charset(): res = Response(charset=None) assert '' == res.text
def test_text_get_no_default_body_encoding(): res = Response(charset=None) res.default_body_encoding = None with pytest.raises(AttributeError): assert '' == res.text
def test_decode_content_defaults_to_identity(): res = Response() res.body = b'There be dragons' res.decode_content() assert res.body == b'There be dragons'
def test_body_set_under_body_doesnt_exist(): res = Response('abc') assert res.body == b'abc' assert res.content_length == 3