flask/tests/test_regression.py

87 lines
2 KiB
Python
Raw Normal View History

import gc
2020-04-04 09:25:54 -07:00
import platform
import threading
import pytest
from werkzeug.exceptions import NotFound
2014-09-03 21:02:03 +02:00
import flask
_gc_lock = threading.Lock()
2020-04-04 09:43:06 -07:00
class assert_no_leak:
def __enter__(self):
gc.disable()
_gc_lock.acquire()
loc = flask._request_ctx_stack._local
# Force Python to track this dictionary at all times.
# This is necessary since Python only starts tracking
# dicts if they contain mutable objects. It's a horrible,
# horrible hack but makes this kinda testable.
loc.__storage__["FOOO"] = [1, 2, 3]
gc.collect()
self.old_objects = len(gc.get_objects())
def __exit__(self, exc_type, exc_value, tb):
2016-05-22 10:34:48 +02:00
gc.collect()
new_objects = len(gc.get_objects())
if new_objects > self.old_objects:
pytest.fail("Example code leaked")
_gc_lock.release()
gc.enable()
2020-04-04 09:25:54 -07:00
@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="CPython only")
2014-09-04 15:32:50 +02:00
def test_memory_consumption():
app = flask.Flask(__name__)
2014-08-31 21:56:15 +02:00
@app.route("/")
2014-09-04 15:32:50 +02:00
def index():
return flask.render_template("simple_template.html", whiskey=42)
2014-09-04 15:32:50 +02:00
def fire():
with app.test_client() as c:
rv = c.get("/")
2014-09-04 15:32:50 +02:00
assert rv.status_code == 200
assert rv.data == b"<h1>42</h1>"
2014-09-04 15:32:50 +02:00
# Trigger caches
fire()
2020-04-04 09:25:54 -07:00
with assert_no_leak():
for _x in range(10):
fire()
2014-09-04 15:32:50 +02:00
def test_safe_join_toplevel_pardir():
from flask.helpers import safe_join
2014-09-04 15:32:50 +02:00
with pytest.raises(NotFound):
safe_join("/foo", "..")
2013-01-21 17:55:07 +00:00
2017-05-24 17:27:36 -07:00
def test_aborting(app):
2014-09-04 15:32:50 +02:00
class Foo(Exception):
whatever = 42
2014-08-31 21:56:15 +02:00
2014-09-04 15:32:50 +02:00
@app.errorhandler(Foo)
def handle_foo(e):
return str(e.whatever)
2014-08-31 21:56:15 +02:00
@app.route("/")
2014-09-04 15:32:50 +02:00
def index():
raise flask.abort(flask.redirect(flask.url_for("test")))
2014-08-31 21:56:15 +02:00
@app.route("/test")
2014-09-04 15:32:50 +02:00
def test():
raise Foo()
2013-01-21 17:55:07 +00:00
2014-09-04 15:32:50 +02:00
with app.test_client() as c:
rv = c.get("/")
assert rv.headers["Location"] == "http://localhost/test"
rv = c.get("/test")
assert rv.data == b"42"