Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
env.update({
'REQUEST_METHOD': 'GET',
'HTTP_IF_NONE_MATCH': response.get_etag()[0]
})
response.make_conditional(env)
assert 'date' in response.headers
# after the thing is invoked by the server as wsgi application
# (we're emulating this here), there must not be any entity
# headers left and the status code would have to be 304
resp = wrappers.Response.from_app(response, env)
assert resp.status_code == 304
assert not 'content-length' in resp.headers
# make sure date is not overriden
response = wrappers.Response('Hello World')
response.date = 1337
d = response.date
response.make_conditional(env)
assert response.date == d
# make sure content length is only set if missing
response = wrappers.Response('Hello World')
response.content_length = 999
response.make_conditional(env)
self.assert_equal(response.content_length, 999)
def stats(request):
copy_stream(request)
f1 = request.files["file1"]
f2 = request.files["file2"]
text = request.form["text"]
f1.save(request.stat_folder + "/file1.bin")
f2.save(request.stat_folder + "/file2.bin")
with open(request.stat_folder + "/text.txt", "w") as f:
f.write(text.encode("utf-8"))
return Response("Done.")
def test_range_request_with_file():
env = create_environ()
resources = os.path.join(os.path.dirname(__file__), "res")
fname = os.path.join(resources, "test.txt")
with open(fname, "rb") as f:
fcontent = f.read()
with open(fname, "rb") as f:
response = wrappers.Response(wrap_file(env, f))
env["HTTP_RANGE"] = "bytes=0-0"
response.make_conditional(
env, accept_ranges=True, complete_length=len(fcontent)
)
assert response.status_code == 206
assert response.headers["Accept-Ranges"] == "bytes"
assert response.headers["Content-Range"] == "bytes 0-0/%d" % len(fcontent)
assert response.headers["Content-Length"] == "1"
assert response.data == fcontent[:1]
def test_exception_repr(self):
exc = exceptions.NotFound()
self.assert_equal(str(exc), '404: Not Found')
self.assert_equal(repr(exc), "")
exc = exceptions.NotFound('Not There')
self.assert_equal(str(exc), '404: Not There')
self.assert_equal(repr(exc), "")
def test_trapping_of_all_http_exceptions(self):
app = flask.Flask(__name__)
app.testing = True
app.config['TRAP_HTTP_EXCEPTIONS'] = True
@app.route('/fail')
def fail():
flask.abort(404)
c = app.test_client()
try:
c.get('/fail')
except NotFound, e:
pass
else:
self.fail('Expected exception')
try:
f('../__init__.py')
except NotFound:
pass
else:
self.assert_true(0, 'expected exception')
# testcase for a security issue that may exist on windows systems
import os
import ntpath
old_path = os.path
os.path = ntpath
try:
try:
f('..\\__init__.py')
except NotFound:
pass
else:
self.assert_true(0, 'expected exception')
finally:
os.path = old_path
def test_method_fallback(self):
map = r.Map([
r.Rule('/', endpoint='index', methods=['GET']),
r.Rule('/', endpoint='hello_name', methods=['GET']),
r.Rule('/select', endpoint='hello_select', methods=['POST']),
r.Rule('/search_get', endpoint='search', methods=['GET']),
r.Rule('/search_post', endpoint='search', methods=['POST'])
])
adapter = map.bind('example.com')
assert adapter.build('index') == '/'
assert adapter.build('index', method='GET') == '/'
assert adapter.build('hello_name', {'name': 'foo'}) == '/foo'
assert adapter.build('hello_select') == '/select'
assert adapter.build('hello_select', method='POST') == '/select'
assert adapter.build('search') == '/search_get'
assert adapter.build('search', method='GET') == '/search_get'
assert adapter.build('search', method='POST') == '/search_post'
def test_path():
map = r.Map(
[
r.Rule("/", defaults={"name": "FrontPage"}, endpoint="page"),
r.Rule("/Special", endpoint="special"),
r.Rule("/", endpoint="year"),
r.Rule("/:foo", endpoint="foopage"),
r.Rule("/:", endpoint="twopage"),
r.Rule("/", endpoint="page"),
r.Rule("//edit", endpoint="editpage"),
r.Rule("//silly/", endpoint="sillypage"),
r.Rule("//silly//edit", endpoint="editsillypage"),
r.Rule("/Talk:", endpoint="talk"),
r.Rule("/User:", endpoint="user"),
r.Rule("/User:/", endpoint="userpage"),
r.Rule(
"/User:/comment/-",
endpoint="usercomment",
),
r.Rule("/Files/", endpoint="files"),
r.Rule("///", endpoint="admin"),
]
def test_complex_routing_rules():
m = r.Map(
[
r.Rule("/", endpoint="index"),
r.Rule("/", endpoint="an_int"),
r.Rule("/", endpoint="a_string"),
r.Rule("/foo/", endpoint="nested"),
r.Rule("/foobar/", endpoint="nestedbar"),
r.Rule("/foo//", endpoint="nested_show"),
r.Rule("/foo//edit", endpoint="nested_edit"),
r.Rule("/users/", endpoint="users", defaults={"page": 1}),
r.Rule("/users/page/", endpoint="users"),
r.Rule("/foox", endpoint="foox"),
r.Rule("//", endpoint="barx_path_path"),
]
)
a = m.bind("example.com")
assert a.match("/") == ("index", {})
assert a.match("/42") == ("an_int", {"blub": 42})
fromstring = etree.HTML
if self.mimetype == 'text/html':
return fromstring(self.data)
return etree.XML(self.data)
lxml = cached_property(lxml)
def json(self):
"""Get the result of simplejson.loads if possible."""
if 'json' not in self.mimetype:
raise AttributeError('Not a JSON response')
try:
from simplejson import loads
except ImportError:
from json import loads
return loads(self.data)
json = cached_property(json)
class TestResponse(Response, ContentAccessors):
"""Pass this to `werkzeug.test.Client` for easier unittesting."""