Merge pull request #3183 from singingwolfboy/pre-commit
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Baumgold · committed by GitHub · parents 819368a, 025589e · Browse files · 65 files·+3791 added−3456 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Pre-commit: Black
Diff stats
65 files+3791 added−3456 removed
- tests:+2485 added−2403 removed
- other:+1306 added−1053 removed
Provenance
- Commit
1dda032- Tree
95e3a5b- Author
David Baumgold <david@davidbaumgold.com>- Committer
GitHub <noreply@github.com>- Parent 1
819368a- Parent 2
025589e
65 files changed+3791 added−3456 removed
modified:examples/javascript/js_example/views.py+6 added-6 removed
1 unmodified line2 3 from js_example import app4 5 6-@app.route('/', defaults={'js': 'plain'})7-@app.route('/<any(plain, jquery, fetch):js>')6+@app.route("/", defaults={"js": "plain"})7+@app.route("/<any(plain, jquery, fetch):js>")8 def index(js):9- return render_template('{0}.html'.format(js), js=js)9+ return render_template("{0}.html".format(js), js=js)10 11 12-@app.route('/add', methods=['POST'])12+@app.route("/add", methods=["POST"])13 def add():14- a = request.form.get('a', 0, type=float)15- b = request.form.get('b', 0, type=float)14+ a = request.form.get("a", 0, type=float)15+ b = request.form.get("b", 0, type=float)16 return jsonify(result=a + b)modified:examples/javascript/tests/conftest.py+1 added-1 removed
1 unmodified line2 3 from js_example import app4 5 6-@pytest.fixture(name='app')6+@pytest.fixture(name="app")7 def fixture_app():8 app.testing = True9 yield app10 app.testing = False5 unmodified linesmodified:examples/javascript/tests/test_js_example.py+14 added-14 removed
1 unmodified line2 3 from flask import template_rendered4 5 6-@pytest.mark.parametrize(('path', 'template_name'), (7- ('/', 'plain.html'),8- ('/plain', 'plain.html'),9- ('/fetch', 'fetch.html'),10- ('/jquery', 'jquery.html'),11-))6+@pytest.mark.parametrize(7+ ("path", "template_name"),8+ (9+ ("/", "plain.html"),10+ ("/plain", "plain.html"),11+ ("/fetch", "fetch.html"),12+ ("/jquery", "jquery.html"),13+ ),14+)15 def test_index(app, client, path, template_name):16 def check(sender, template, context):17 assert template.name == template_name18 19 with template_rendered.connected_to(check, app):20 client.get(path)21 22 20-@pytest.mark.parametrize(('a', 'b', 'result'), (21- (2, 3, 5),22- (2.5, 3, 5.5),23- (2, None, 2),24- (2, 'b', 2),25-))23+@pytest.mark.parametrize(24+ ("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2))25+)26 def test_add(client, a, b, result):27- response = client.post('/add', data={'a': a, 'b': b})28- assert response.get_json()['result'] == result27+ response = client.post("/add", data={"a": a, "b": b})28+ assert response.get_json()["result"] == resultmodified:examples/javascript/setup.py+10 added-18 removed
1 import io2 3 from setuptools import find_packages, setup4 5-with io.open('README.rst', 'rt', encoding='utf8') as f:5+with io.open("README.rst", "rt", encoding="utf8") as f:6 readme = f.read()7 8 setup(9- name='js_example',10- version='1.0.0',11- url='http://flask.pocoo.org/docs/patterns/jquery/',12- license='BSD',13- maintainer='Pallets team',14- maintainer_email='contact@palletsprojects.com',15- description='Demonstrates making Ajax requests to Flask.',9+ name="js_example",10+ version="1.0.0",11+ url="http://flask.pocoo.org/docs/patterns/jquery/",12+ license="BSD",13+ maintainer="Pallets team",14+ maintainer_email="contact@palletsprojects.com",15+ description="Demonstrates making Ajax requests to Flask.",16 long_description=readme,17 packages=find_packages(),18 include_package_data=True,19 zip_safe=False,20- install_requires=[21- 'flask',22- ],23- extras_require={24- 'test': [25- 'pytest',26- 'coverage',27- 'blinker',28- ],29- },20+ install_requires=["flask"],21+ extras_require={"test": ["pytest", "coverage", "blinker"]},22 )modified:examples/tutorial/flaskr/__init__.py+8 added-6 removed
6 unmodified lines7 """Create and configure an instance of the Flask application."""8 app = Flask(__name__, instance_relative_config=True)9 app.config.from_mapping(10 # a default secret that should be overridden by instance config11- SECRET_KEY='dev',11+ SECRET_KEY="dev",12 # store the database in the instance folder13- DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),13+ DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"),14 )15 16 if test_config is None:17 # load the instance config, if it exists, when not testing18- app.config.from_pyfile('config.py', silent=True)18+ app.config.from_pyfile("config.py", silent=True)19 else:20 # load the test config if passed in21 app.config.update(test_config)22 2 unmodified lines25 os.makedirs(app.instance_path)26 except OSError:27 pass28 29- @app.route('/hello')29+ @app.route("/hello")30 def hello():31- return 'Hello, World!'31+ return "Hello, World!"32 33 # register the database commands34 from flaskr import db35+36 db.init_app(app)37 38 # apply the blueprints to the app39 from flaskr import auth, blog40+41 app.register_blueprint(auth.bp)42 app.register_blueprint(blog.bp)43 44 # make url_for('index') == url_for('blog.index')45 # in another app, you might define a separate main index here with46 # app.route, while giving the blog blueprint a url_prefix, but for47 # the tutorial the blog will be the main index46- app.add_url_rule('/', endpoint='index')48+ app.add_url_rule("/", endpoint="index")49 50 return appmodified:examples/tutorial/flaskr/auth.py+43 added-34 removed
1 import functools2 3 from flask import (4- Blueprint, flash, g, redirect, render_template, request, session, url_for4+ Blueprint,5+ flash,6+ g,7+ redirect,8+ render_template,9+ request,10+ session,11+ url_for,12 )13 from werkzeug.security import check_password_hash, generate_password_hash14 15 from flaskr.db import get_db16 10-bp = Blueprint('auth', __name__, url_prefix='/auth')17+bp = Blueprint("auth", __name__, url_prefix="/auth")18 19 20 def login_required(view):21 """View decorator that redirects anonymous users to the login page."""22+23 @functools.wraps(view)24 def wrapped_view(**kwargs):25 if g.user is None:18- return redirect(url_for('auth.login'))26+ return redirect(url_for("auth.login"))27 28 return view(**kwargs)29 30 return wrapped_view2 unmodified lines33 @bp.before_app_request34 def load_logged_in_user():35 """If a user id is stored in the session, load the user object from36 the database into ``g.user``."""29- user_id = session.get('user_id')37+ user_id = session.get("user_id")38 39 if user_id is None:40 g.user = None41 else:34- g.user = get_db().execute(35- 'SELECT * FROM user WHERE id = ?', (user_id,)36- ).fetchone()42+ g.user = (43+ get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone()44+ )45 46 39-@bp.route('/register', methods=('GET', 'POST'))47+@bp.route("/register", methods=("GET", "POST"))48 def register():49 """Register a new user.50 51 Validates that the username is not already taken. Hashes the52 password for security.53 """46- if request.method == 'POST':47- username = request.form['username']48- password = request.form['password']54+ if request.method == "POST":55+ username = request.form["username"]56+ password = request.form["password"]57 db = get_db()58 error = None59 60 if not username:53- error = 'Username is required.'61+ error = "Username is required."62 elif not password:55- error = 'Password is required.'56- elif db.execute(57- 'SELECT id FROM user WHERE username = ?', (username,)58- ).fetchone() is not None:59- error = 'User {0} is already registered.'.format(username)63+ error = "Password is required."64+ elif (65+ db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()66+ is not None67+ ):68+ error = "User {0} is already registered.".format(username)69 70 if error is None:71 # the name is available, store it in the database and go to72 # the login page73 db.execute(65- 'INSERT INTO user (username, password) VALUES (?, ?)',66- (username, generate_password_hash(password))74+ "INSERT INTO user (username, password) VALUES (?, ?)",75+ (username, generate_password_hash(password)),76 )77 db.commit()69- return redirect(url_for('auth.login'))78+ return redirect(url_for("auth.login"))79 80 flash(error)81 73- return render_template('auth/register.html')82+ return render_template("auth/register.html")83 84 76-@bp.route('/login', methods=('GET', 'POST'))85+@bp.route("/login", methods=("GET", "POST"))86 def login():87 """Log in a registered user by adding the user id to the session."""79- if request.method == 'POST':80- username = request.form['username']81- password = request.form['password']88+ if request.method == "POST":89+ username = request.form["username"]90+ password = request.form["password"]91 db = get_db()92 error = None93 user = db.execute(85- 'SELECT * FROM user WHERE username = ?', (username,)94+ "SELECT * FROM user WHERE username = ?", (username,)95 ).fetchone()96 97 if user is None:89- error = 'Incorrect username.'90- elif not check_password_hash(user['password'], password):91- error = 'Incorrect password.'98+ error = "Incorrect username."99+ elif not check_password_hash(user["password"], password):100+ error = "Incorrect password."101 102 if error is None:103 # store the user id in a new session and return to the index104 session.clear()96- session['user_id'] = user['id']97- return redirect(url_for('index'))105+ session["user_id"] = user["id"]106+ return redirect(url_for("index"))107 108 flash(error)109 101- return render_template('auth/login.html')110+ return render_template("auth/login.html")111 112 104-@bp.route('/logout')113+@bp.route("/logout")114 def logout():115 """Clear the current session, including the stored user id."""116 session.clear()108- return redirect(url_for('index'))117+ return redirect(url_for("index"))modified:examples/tutorial/flaskr/blog.py+38 added-38 removed
1-from flask import (2- Blueprint, flash, g, redirect, render_template, request, url_for1+from flask import Blueprint, flash, g, redirect, render_template, request, url_for3-)2 from werkzeug.exceptions import abort3 4 from flaskr.auth import login_required5 from flaskr.db import get_db6 9-bp = Blueprint('blog', __name__)7+bp = Blueprint("blog", __name__)8 9 12-@bp.route('/')10+@bp.route("/")11 def index():12 """Show all the posts, most recent first."""13 db = get_db()14 posts = db.execute(17- 'SELECT p.id, title, body, created, author_id, username'18- ' FROM post p JOIN user u ON p.author_id = u.id'19- ' ORDER BY created DESC'15+ "SELECT p.id, title, body, created, author_id, username"16+ " FROM post p JOIN user u ON p.author_id = u.id"17+ " ORDER BY created DESC"18 ).fetchall()21- return render_template('blog/index.html', posts=posts)19+ return render_template("blog/index.html", posts=posts)20 21 22 def get_post(id, check_author=True):23 """Get a post and its author by id.6 unmodified lines30 :return: the post with author information31 :raise 404: if a post with the given id doesn't exist32 :raise 403: if the current user isn't the author33 """36- post = get_db().execute(37- 'SELECT p.id, title, body, created, author_id, username'38- ' FROM post p JOIN user u ON p.author_id = u.id'39- ' WHERE p.id = ?',40- (id,)41- ).fetchone()34+ post = (35+ get_db()36+ .execute(37+ "SELECT p.id, title, body, created, author_id, username"38+ " FROM post p JOIN user u ON p.author_id = u.id"39+ " WHERE p.id = ?",40+ (id,),41+ )42+ .fetchone()43+ )44 45 if post is None:46 abort(404, "Post id {0} doesn't exist.".format(id))47 46- if check_author and post['author_id'] != g.user['id']:48+ if check_author and post["author_id"] != g.user["id"]:49 abort(403)50 51 return post52 53 52-@bp.route('/create', methods=('GET', 'POST'))54+@bp.route("/create", methods=("GET", "POST"))55 @login_required56 def create():57 """Create a new post for the current user."""56- if request.method == 'POST':57- title = request.form['title']58- body = request.form['body']58+ if request.method == "POST":59+ title = request.form["title"]60+ body = request.form["body"]61 error = None62 63 if not title:62- error = 'Title is required.'64+ error = "Title is required."65 66 if error is not None:67 flash(error)68 else:69 db = get_db()70 db.execute(69- 'INSERT INTO post (title, body, author_id)'70- ' VALUES (?, ?, ?)',71- (title, body, g.user['id'])71+ "INSERT INTO post (title, body, author_id)" " VALUES (?, ?, ?)",72+ (title, body, g.user["id"]),73 )74 db.commit()74- return redirect(url_for('blog.index'))75+ return redirect(url_for("blog.index"))76 76- return render_template('blog/create.html')77+ return render_template("blog/create.html")78 79 79-@bp.route('/<int:id>/update', methods=('GET', 'POST'))80+@bp.route("/<int:id>/update", methods=("GET", "POST"))81 @login_required82 def update(id):83 """Update a post if the current user is the author."""84 post = get_post(id)85 85- if request.method == 'POST':86- title = request.form['title']87- body = request.form['body']86+ if request.method == "POST":87+ title = request.form["title"]88+ body = request.form["body"]89 error = None90 91 if not title:91- error = 'Title is required.'92+ error = "Title is required."93 94 if error is not None:95 flash(error)96 else:97 db = get_db()98 db.execute(98- 'UPDATE post SET title = ?, body = ? WHERE id = ?',99- (title, body, id)99+ "UPDATE post SET title = ?, body = ? WHERE id = ?", (title, body, id)100 )101 db.commit()102- return redirect(url_for('blog.index'))102+ return redirect(url_for("blog.index"))103 104- return render_template('blog/update.html', post=post)104+ return render_template("blog/update.html", post=post)105 106 107-@bp.route('/<int:id>/delete', methods=('POST',))107+@bp.route("/<int:id>/delete", methods=("POST",))108 @login_required109 def delete(id):110 """Delete a post.111 1 unmodified line113 author of the post.114 """115 get_post(id)116 db = get_db()117- db.execute('DELETE FROM post WHERE id = ?', (id,))117+ db.execute("DELETE FROM post WHERE id = ?", (id,))118 db.commit()119- return redirect(url_for('blog.index'))119+ return redirect(url_for("blog.index"))modified:examples/tutorial/flaskr/db.py+7 added-8 removed
8 unmodified lines9 """Connect to the application's configured database. The connection10 is unique for each request and will be reused if this is called11 again.12 """13- if 'db' not in g:13+ if "db" not in g:14 g.db = sqlite3.connect(15- current_app.config['DATABASE'],16- detect_types=sqlite3.PARSE_DECLTYPES15+ current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES16 )17 g.db.row_factory = sqlite3.Row18 19 return g.db2 unmodified lines22 def close_db(e=None):23 """If this request connected to the database, close the24 connection.25 """27- db = g.pop('db', None)26+ db = g.pop("db", None)27 28 if db is not None:29 db.close()30 1 unmodified line32 def init_db():33 """Clear existing data and create new tables."""34 db = get_db()35 37- with current_app.open_resource('schema.sql') as f:38- db.executescript(f.read().decode('utf8'))36+ with current_app.open_resource("schema.sql") as f:37+ db.executescript(f.read().decode("utf8"))38 39 41-@click.command('init-db')40+@click.command("init-db")41 @with_appcontext42 def init_db_command():43 """Clear existing data and create new tables."""44 init_db()46- click.echo('Initialized the database.')45+ click.echo("Initialized the database.")46 47 48 def init_app(app):49 """Register database functions with the Flask app. This is called by4 unmodified linesmodified:examples/tutorial/tests/conftest.py+6 added-10 removed
4 unmodified lines5 from flaskr import create_app6 from flaskr.db import get_db, init_db7 8 # read in SQL for populating test data9-with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:10- _data_sql = f.read().decode('utf8')9+with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:10+ _data_sql = f.read().decode("utf8")11 12 13 @pytest.fixture14 def app():15 """Create and configure a new app instance for each test."""16 # create a temporary file to isolate the database for each test17 db_fd, db_path = tempfile.mkstemp()18 # create the app with common test config19- app = create_app({20- 'TESTING': True,21- 'DATABASE': db_path,22- })19+ app = create_app({"TESTING": True, "DATABASE": db_path})20 21 # create the database and load test data22 with app.app_context():23 init_db()21 unmodified lines45 class AuthActions(object):46 def __init__(self, client):47 self._client = client48 52- def login(self, username='test', password='test'):49+ def login(self, username="test", password="test"):50 return self._client.post(54- '/auth/login',55- data={'username': username, 'password': password}51+ "/auth/login", data={"username": username, "password": password}52 )53 54 def logout(self):59- return self._client.get('/auth/logout')55+ return self._client.get("/auth/logout")56 57 58 @pytest.fixture59 def auth(client):1 unmodified linemodified:examples/tutorial/tests/test_auth.py+26 added-25 removed
3 unmodified lines4 5 6 def test_register(client, app):7 # test that viewing the page renders without template errors8- assert client.get('/auth/register').status_code == 2008+ assert client.get("/auth/register").status_code == 2009 10 # test that successful registration redirects to the login page11- response = client.post(12- '/auth/register', data={'username': 'a', 'password': 'a'}13- )14- assert 'http://localhost/auth/login' == response.headers['Location']11+ response = client.post("/auth/register", data={"username": "a", "password": "a"})12+ assert "http://localhost/auth/login" == response.headers["Location"]13 14 # test that the user was inserted into the database15 with app.app_context():18- assert get_db().execute(19- "select * from user where username = 'a'",20- ).fetchone() is not None16+ assert (17+ get_db().execute("select * from user where username = 'a'").fetchone()18+ is not None19+ )20 21 23-@pytest.mark.parametrize(('username', 'password', 'message'), (24- ('', '', b'Username is required.'),25- ('a', '', b'Password is required.'),26- ('test', 'test', b'already registered'),27-))22+@pytest.mark.parametrize(23+ ("username", "password", "message"),24+ (25+ ("", "", b"Username is required."),26+ ("a", "", b"Password is required."),27+ ("test", "test", b"already registered"),28+ ),29+)30 def test_register_validate_input(client, username, password, message):31 response = client.post(30- '/auth/register',31- data={'username': username, 'password': password}32+ "/auth/register", data={"username": username, "password": password}33 )34 assert message in response.data35 36 37 def test_login(client, auth):38 # test that viewing the page renders without template errors38- assert client.get('/auth/login').status_code == 20039+ assert client.get("/auth/login").status_code == 20040 41 # test that successful login redirects to the index page42 response = auth.login()42- assert response.headers['Location'] == 'http://localhost/'43+ assert response.headers["Location"] == "http://localhost/"44 45 # login request set the user_id in the session46 # check that the user is loaded from the session47 with client:47- client.get('/')48- assert session['user_id'] == 149- assert g.user['username'] == 'test'48+ client.get("/")49+ assert session["user_id"] == 150+ assert g.user["username"] == "test"51 52 52-@pytest.mark.parametrize(('username', 'password', 'message'), (53- ('a', 'test', b'Incorrect username.'),54- ('test', 'a', b'Incorrect password.'),55-))53+@pytest.mark.parametrize(54+ ("username", "password", "message"),55+ (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")),56+)57 def test_login_validate_input(auth, username, password, message):58 response = auth.login(username, password)59 assert message in response.data60 2 unmodified lines63 auth.login()64 65 with client:66 auth.logout()66- assert 'user_id' not in session67+ assert "user_id" not in sessionmodified:examples/tutorial/tests/test_blog.py+25 added-35 removed
1 unmodified line2 from flaskr.db import get_db3 4 5 def test_index(client, auth):6- response = client.get('/')6+ response = client.get("/")7 assert b"Log In" in response.data8 assert b"Register" in response.data9 10 auth.login()11- response = client.get('/')12- assert b'test title' in response.data13- assert b'by test on 2018-01-01' in response.data14- assert b'test\nbody' in response.data11+ response = client.get("/")12+ assert b"test title" in response.data13+ assert b"by test on 2018-01-01" in response.data14+ assert b"test\nbody" in response.data15 assert b'href="/1/update"' in response.data16 17 18-@pytest.mark.parametrize('path', (19- '/create',20- '/1/update',21- '/1/delete',22-))18+@pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete"))19 def test_login_required(client, path):20 response = client.post(path)25- assert response.headers['Location'] == 'http://localhost/auth/login'21+ assert response.headers["Location"] == "http://localhost/auth/login"22 23 24 def test_author_required(app, client, auth):25 # change the post author to another user26 with app.app_context():27 db = get_db()32- db.execute('UPDATE post SET author_id = 2 WHERE id = 1')28+ db.execute("UPDATE post SET author_id = 2 WHERE id = 1")29 db.commit()30 31 auth.login()32 # current user can't modify other user's post37- assert client.post('/1/update').status_code == 40338- assert client.post('/1/delete').status_code == 40333+ assert client.post("/1/update").status_code == 40334+ assert client.post("/1/delete").status_code == 40335 # current user doesn't see edit link40- assert b'href="/1/update"' not in client.get('/').data36+ assert b'href="/1/update"' not in client.get("/").data37 38 43-@pytest.mark.parametrize('path', (44- '/2/update',45- '/2/delete',46-))39+@pytest.mark.parametrize("path", ("/2/update", "/2/delete"))40 def test_exists_required(client, auth, path):41 auth.login()42 assert client.post(path).status_code == 40443 44 45 def test_create(client, auth, app):46 auth.login()54- assert client.get('/create').status_code == 20055- client.post('/create', data={'title': 'created', 'body': ''})47+ assert client.get("/create").status_code == 20048+ client.post("/create", data={"title": "created", "body": ""})49 50 with app.app_context():51 db = get_db()59- count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]52+ count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0]53 assert count == 254 55 56 def test_update(client, auth, app):57 auth.login()65- assert client.get('/1/update').status_code == 20066- client.post('/1/update', data={'title': 'updated', 'body': ''})58+ assert client.get("/1/update").status_code == 20059+ client.post("/1/update", data={"title": "updated", "body": ""})60 61 with app.app_context():62 db = get_db()70- post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()71- assert post['title'] == 'updated'63+ post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()64+ assert post["title"] == "updated"65 66 74-@pytest.mark.parametrize('path', (75- '/create',76- '/1/update',77-))67+@pytest.mark.parametrize("path", ("/create", "/1/update"))68 def test_create_update_validate(client, auth, path):69 auth.login()80- response = client.post(path, data={'title': '', 'body': ''})81- assert b'Title is required.' in response.data70+ response = client.post(path, data={"title": "", "body": ""})71+ assert b"Title is required." in response.data72 73 74 def test_delete(client, auth, app):75 auth.login()86- response = client.post('/1/delete')87- assert response.headers['Location'] == 'http://localhost/'76+ response = client.post("/1/delete")77+ assert response.headers["Location"] == "http://localhost/"78 79 with app.app_context():80 db = get_db()91- post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()81+ post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()82 assert post is Nonemodified:examples/tutorial/tests/test_db.py+5 added-5 removed
8 unmodified lines9 db = get_db()10 assert db is get_db()11 12 with pytest.raises(sqlite3.ProgrammingError) as e:13- db.execute('SELECT 1')13+ db.execute("SELECT 1")14 15- assert 'closed' in str(e)15+ assert "closed" in str(e)16 17 18 def test_init_db_command(runner, monkeypatch):19 class Recorder(object):1 unmodified line21 22 def fake_init_db():23 Recorder.called = True24 25- monkeypatch.setattr('flaskr.db.init_db', fake_init_db)26- result = runner.invoke(args=['init-db'])27- assert 'Initialized' in result.output25+ monkeypatch.setattr("flaskr.db.init_db", fake_init_db)26+ result = runner.invoke(args=["init-db"])27+ assert "Initialized" in result.output28 assert Recorder.calledmodified:examples/tutorial/tests/test_factory.py+3 added-3 removed
2 unmodified lines3 4 def test_config():5 """Test create_app without passing test config."""6 assert not create_app().testing7- assert create_app({'TESTING': True}).testing7+ assert create_app({"TESTING": True}).testing8 9 10 def test_hello(client):11- response = client.get('/hello')12- assert response.data == b'Hello, World!'11+ response = client.get("/hello")12+ assert response.data == b"Hello, World!"modified:examples/tutorial/setup.py+10 added-17 removed
1 import io2 3 from setuptools import find_packages, setup4 5-with io.open('README.rst', 'rt', encoding='utf8') as f:5+with io.open("README.rst", "rt", encoding="utf8") as f:6 readme = f.read()7 8 setup(9- name='flaskr',10- version='1.0.0',11- url='http://flask.pocoo.org/docs/tutorial/',12- license='BSD',13- maintainer='Pallets team',14- maintainer_email='contact@palletsprojects.com',15- description='The basic blog app built in the Flask tutorial.',9+ name="flaskr",10+ version="1.0.0",11+ url="http://flask.pocoo.org/docs/tutorial/",12+ license="BSD",13+ maintainer="Pallets team",14+ maintainer_email="contact@palletsprojects.com",15+ description="The basic blog app built in the Flask tutorial.",16 long_description=readme,17 packages=find_packages(),18 include_package_data=True,19 zip_safe=False,20- install_requires=[21- 'flask',22- ],23- extras_require={24- 'test': [25- 'pytest',26- 'coverage',27- ],28- },20+ install_requires=["flask"],21+ extras_require={"test": ["pytest", "coverage"]},22 )modified:flask/json/__init__.py+57 added-49 removed
21 unmodified lines22 23 24 # Figure out if simplejson escapes slashes. This behavior was changed25 # from one version to another without reason.26-_slash_escape = '\\/' not in _json.dumps('/')26+_slash_escape = "\\/" not in _json.dumps("/")27 28 29-__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',30- 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',31- 'jsonify']29+__all__ = [30+ "dump",31+ "dumps",32+ "load",33+ "loads",34+ "htmlsafe_dump",35+ "htmlsafe_dumps",36+ "JSONDecoder",37+ "JSONEncoder",38+ "jsonify",39+]40 41 42 def _wrap_reader_for_text(fp, encoding):43 if isinstance(fp.read(0), bytes):2 unmodified lines46 47 48 def _wrap_writer_for_text(fp, encoding):49 try:42- fp.write('')50+ fp.write("")51 except TypeError:52 fp = io.TextIOWrapper(fp, encoding)53 return fp54 28 unmodified lines83 if isinstance(o, date):84 return http_date(o.timetuple())85 if isinstance(o, uuid.UUID):86 return str(o)79- if hasattr(o, '__html__'):87+ if hasattr(o, "__html__"):88 return text_type(o.__html__())89 return _json.JSONEncoder.default(self, o)90 91 9 unmodified lines101 """Inject default arguments for dump functions."""102 if current_app:103 bp = current_app.blueprints.get(request.blueprint) if request else None104 kwargs.setdefault(97- 'cls',98- bp.json_encoder if bp and bp.json_encoder99- else current_app.json_encoder105+ "cls",106+ bp.json_encoder if bp and bp.json_encoder else current_app.json_encoder,107 )108 102- if not current_app.config['JSON_AS_ASCII']:103- kwargs.setdefault('ensure_ascii', False)109+ if not current_app.config["JSON_AS_ASCII"]:110+ kwargs.setdefault("ensure_ascii", False)111 105- kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])112+ kwargs.setdefault("sort_keys", current_app.config["JSON_SORT_KEYS"])113 else:107- kwargs.setdefault('sort_keys', True)108- kwargs.setdefault('cls', JSONEncoder)114+ kwargs.setdefault("sort_keys", True)115+ kwargs.setdefault("cls", JSONEncoder)116 117 118 def _load_arg_defaults(kwargs):119 """Inject default arguments for load functions."""120 if current_app:121 bp = current_app.blueprints.get(request.blueprint) if request else None122 kwargs.setdefault(116- 'cls',117- bp.json_decoder if bp and bp.json_decoder118- else current_app.json_decoder123+ "cls",124+ bp.json_decoder if bp and bp.json_decoder else current_app.json_decoder,125 )126 else:121- kwargs.setdefault('cls', JSONDecoder)127+ kwargs.setdefault("cls", JSONDecoder)128 129 130 def detect_encoding(data):131 """Detect which UTF codec was used to encode the given bytes.7 unmodified lines139 """140 head = data[:4]141 142 if head[:3] == codecs.BOM_UTF8:137- return 'utf-8-sig'143+ return "utf-8-sig"144 139- if b'\x00' not in head:140- return 'utf-8'145+ if b"\x00" not in head:146+ return "utf-8"147 148 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):143- return 'utf-32'149+ return "utf-32"150 151 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):146- return 'utf-16'152+ return "utf-16"153 154 if len(head) == 4:149- if head[:3] == b'\x00\x00\x00':150- return 'utf-32-be'155+ if head[:3] == b"\x00\x00\x00":156+ return "utf-32-be"157 152- if head[::2] == b'\x00\x00':153- return 'utf-16-be'158+ if head[::2] == b"\x00\x00":159+ return "utf-16-be"160 155- if head[1:] == b'\x00\x00\x00':156- return 'utf-32-le'161+ if head[1:] == b"\x00\x00\x00":162+ return "utf-32-le"163 158- if head[1::2] == b'\x00\x00':159- return 'utf-16-le'164+ if head[1::2] == b"\x00\x00":165+ return "utf-16-le"166 167 if len(head) == 2:162- return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'168+ return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"169 164- return 'utf-8'170+ return "utf-8"171 172 173 def dumps(obj, **kwargs):174 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's5 unmodified lines180 default is controlled by the ``JSON_AS_ASCII`` configuration variable181 and can be overridden by the simplejson ``ensure_ascii`` parameter.182 """183 _dump_arg_defaults(kwargs)178- encoding = kwargs.pop('encoding', None)184+ encoding = kwargs.pop("encoding", None)185 rv = _json.dumps(obj, **kwargs)186 if encoding is not None and isinstance(rv, text_type):187 rv = rv.encode(encoding)188 return rv1 unmodified line190 191 def dump(obj, fp, **kwargs):192 """Like :func:`dumps` but writes into a file object."""193 _dump_arg_defaults(kwargs)188- encoding = kwargs.pop('encoding', None)194+ encoding = kwargs.pop("encoding", None)195 if encoding is not None:196 fp = _wrap_writer_for_text(fp, encoding)197 _json.dump(obj, fp, **kwargs)198 4 unmodified lines203 application on the stack.204 """205 _load_arg_defaults(kwargs)206 if isinstance(s, bytes):201- encoding = kwargs.pop('encoding', None)207+ encoding = kwargs.pop("encoding", None)208 if encoding is None:209 encoding = detect_encoding(s)210 s = s.decode(encoding)211 return _json.loads(s, **kwargs)3 unmodified lines215 """Like :func:`loads` but reads from a file object.216 """217 _load_arg_defaults(kwargs)218 if not PY2:213- fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')219+ fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")220 return _json.load(fp, **kwargs)221 222 223 def htmlsafe_dumps(obj, **kwargs):20 unmodified lines244 hold true when using this function in HTML attributes that are double245 quoted. Always single quote attributes if you use the ``|tojson``246 filter. Alternatively use ``|tojson|forceescape``.247 """242- rv = dumps(obj, **kwargs) \243- .replace(u'<', u'\\u003c') \244- .replace(u'>', u'\\u003e') \245- .replace(u'&', u'\\u0026') \246- .replace(u"'", u'\\u0027')248+ rv = (249+ dumps(obj, **kwargs)250+ .replace(u"<", u"\\u003c")251+ .replace(u">", u"\\u003e")252+ .replace(u"&", u"\\u0026")253+ .replace(u"'", u"\\u0027")254+ )255 if not _slash_escape:248- rv = rv.replace('\\/', '/')256+ rv = rv.replace("\\/", "/")257 return rv258 259 260 def htmlsafe_dump(obj, fp, **kwargs):50 unmodified lines311 .. versionadded:: 0.2312 """313 314 indent = None307- separators = (',', ':')315+ separators = (",", ":")316 309- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:317+ if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:318 indent = 2311- separators = (', ', ': ')319+ separators = (", ", ": ")320 321 if args and kwargs:314- raise TypeError('jsonify() behavior undefined when passed both args and kwargs')322+ raise TypeError("jsonify() behavior undefined when passed both args and kwargs")323 elif len(args) == 1: # single args are passed directly to dumps()324 data = args[0]325 else:326 data = args or kwargs327 328 return current_app.response_class(321- dumps(data, indent=indent, separators=separators) + '\n',322- mimetype=current_app.config['JSONIFY_MIMETYPE']329+ dumps(data, indent=indent, separators=separators) + "\n",330+ mimetype=current_app.config["JSONIFY_MIMETYPE"],331 )332 333 334 def tojson_filter(obj, **kwargs):1 unmodified linemodified:flask/json/tag.py+19 added-13 removed
54 unmodified lines55 56 class JSONTag(object):57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""58 59- __slots__ = ('serializer',)59+ __slots__ = ("serializer",)60 61 #: The tag to mark the serialized object with. If ``None``, this tag is62 #: only used as an intermediate step during tagging.63 key = None29 unmodified lines93 when deserializing.94 """95 96 __slots__ = ()97- key = ' di'97+ key = " di"98 99 def check(self, value):100 return (101 isinstance(value, dict)2 unmodified lines104 )105 106 def to_json(self, value):107 key = next(iter(value))108- return {key + '__': self.serializer.tag(value[key])}108+ return {key + "__": self.serializer.tag(value[key])}109 110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}14 unmodified lines127 128 129 class TagTuple(JSONTag):130 __slots__ = ()131- key = ' t'131+ key = " t"132 133 def check(self, value):134 return isinstance(value, tuple)135 17 unmodified lines153 154 155 class TagBytes(JSONTag):156 __slots__ = ()157- key = ' b'157+ key = " b"158 159 def check(self, value):160 return isinstance(value, bytes)161 162 def to_json(self, value):163- return b64encode(value).decode('ascii')163+ return b64encode(value).decode("ascii")164 165 def to_python(self, value):166 return b64decode(value)167 3 unmodified lines171 having a ``__html__`` method to the result of that method. Always172 deserializes to an instance of :class:`~flask.Markup`."""173 174 __slots__ = ()175- key = ' m'175+ key = " m"176 177 def check(self, value):178- return callable(getattr(value, '__html__', None))178+ return callable(getattr(value, "__html__", None))179 180 def to_json(self, value):181 return text_type(value.__html__())182 2 unmodified lines185 186 187 class TagUUID(JSONTag):188 __slots__ = ()189- key = ' u'189+ key = " u"190 191 def check(self, value):192 return isinstance(value, UUID)193 5 unmodified lines199 200 201 class TagDateTime(JSONTag):202 __slots__ = ()203- key = ' d'203+ key = " d"204 205 def check(self, value):206 return isinstance(value, datetime)207 18 unmodified lines226 * :class:`~uuid.UUID`227 * :class:`~datetime.datetime`228 """229 230- __slots__ = ('tags', 'order')230+ __slots__ = ("tags", "order")231 232 #: Tag classes to bind when creating the serializer. Other tags can be233 #: added later using :meth:`~register`.234 default_tags = [235- TagDict, PassDict, TagTuple, PassList, TagBytes, TagMarkup, TagUUID,235+ TagDict,236+ PassDict,237+ TagTuple,238+ PassList,239+ TagBytes,240+ TagMarkup,241+ TagUUID,242 TagDateTime,243 ]244 245 def __init__(self):52 unmodified lines298 return self.tags[key].to_python(value[key])299 300 def dumps(self, value):301 """Tag the value and dump it to a compact JSON string."""296- return dumps(self.tag(value), separators=(',', ':'))302+ return dumps(self.tag(value), separators=(",", ":"))303 304 def loads(self, value):305 """Load data from a JSON string and deserialized any tagged objects."""306 return loads(value, object_hook=self.untag)modified:flask/__init__.py+39 added-12 removed
8 unmodified lines9 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11 """12 13-__version__ = '1.1.dev'13+__version__ = "1.1.dev"14 15 # utilities we import from Werkzeug and Jinja2 that are unused16 # in the module but are exported as public interface.17 from werkzeug.exceptions import abort1 unmodified line19 from jinja2 import Markup, escape20 21 from .app import Flask, Request, Response22 from .config import Config23-from .helpers import url_for, flash, send_file, send_from_directory, \24- get_flashed_messages, get_template_attribute, make_response, safe_join, \25- stream_with_context26-from .globals import current_app, g, request, session, _request_ctx_stack, \27- _app_ctx_stack28-from .ctx import has_request_context, has_app_context, \29- after_this_request, copy_current_request_context23+from .helpers import (24+ url_for,25+ flash,26+ send_file,27+ send_from_directory,28+ get_flashed_messages,29+ get_template_attribute,30+ make_response,31+ safe_join,32+ stream_with_context,33+)34+from .globals import (35+ current_app,36+ g,37+ request,38+ session,39+ _request_ctx_stack,40+ _app_ctx_stack,41+)42+from .ctx import (43+ has_request_context,44+ has_app_context,45+ after_this_request,46+ copy_current_request_context,47+)48 from .blueprints import Blueprint49 from .templating import render_template, render_template_string50 51 # the signals34-from .signals import signals_available, template_rendered, request_started, \35- request_finished, got_request_exception, request_tearing_down, \36- appcontext_tearing_down, appcontext_pushed, \37- appcontext_popped, message_flashed, before_render_template52+from .signals import (53+ signals_available,54+ template_rendered,55+ request_started,56+ request_finished,57+ got_request_exception,58+ request_tearing_down,59+ appcontext_tearing_down,60+ appcontext_pushed,61+ appcontext_popped,62+ message_flashed,63+ before_render_template,64+)65 66 # We're not exposing the actual json module but a convenient wrapper around67 # it.68 from . import json4 unmodified linesmodified:flask/__main__.py+2 added-1 removed
7 unmodified lines8 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10 """11 12-if __name__ == '__main__':12+if __name__ == "__main__":13 from .cli import main14+15 main(as_module=True)modified:flask/_compat.py+10 added-6 removed
48 unmodified lines49 from inspect import getargspec50 from cStringIO import StringIO51 import collections as collections_abc52 53- exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')53+ exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")54 55 def implements_to_string(cls):56 cls.__unicode__ = cls.__str__57- cls.__str__ = lambda x: x.__unicode__().encode('utf-8')57+ cls.__str__ = lambda x: x.__unicode__().encode("utf-8")58 return cls59 60 61 def with_metaclass(meta, *bases):3 unmodified lines65 # itself with the actual metaclass.66 class metaclass(type):67 def __new__(cls, name, this_bases, d):68 return meta(name, bases, d)69- return type.__new__(metaclass, 'temporary_class', (), {})69 70+ return type.__new__(metaclass, "temporary_class", (), {})71 72+73 # Certain versions of pypy have a bug where clearing the exception stack74 # breaks the __exit__ function in a very peculiar way. The second level of75 # exception blocks is necessary because pypy seems to forget to check if an76 # exception happened until the next bytecode instruction?4 unmodified lines81 # versions.82 #83 # Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.84 BROKEN_PYPY_CTXMGR_EXIT = False84-if hasattr(sys, 'pypy_version_info'):85+if hasattr(sys, "pypy_version_info"):86+87 class _Mgr(object):88 def __enter__(self):89 return self90+91 def __exit__(self, *args):89- if hasattr(sys, 'exc_clear'):92+ if hasattr(sys, "exc_clear"):93 # Python 3 (PyPy3) doesn't have exc_clear94 sys.exc_clear()95+96 try:97 try:98 with _Mgr():99 raise AssertionError()10 unmodified lines110 except ImportError:111 # Backwards compatibility as proposed in PEP 0519:112 # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility113 def fspath(path):110- return path.__fspath__() if hasattr(path, '__fspath__') else path114+ return path.__fspath__() if hasattr(path, "__fspath__") else pathmodified:flask/app.py+245 added-183 removed
16 unmodified lines17 from itertools import chain18 from threading import Lock19 20 from werkzeug.datastructures import Headers, ImmutableDict21-from werkzeug.exceptions import BadRequest, BadRequestKeyError, HTTPException, \22- InternalServerError, MethodNotAllowed, default_exceptions23-from werkzeug.routing import BuildError, Map, RequestRedirect, \24- RoutingException, Rule21+from werkzeug.exceptions import (22+ BadRequest,23+ BadRequestKeyError,24+ HTTPException,25+ InternalServerError,26+ MethodNotAllowed,27+ default_exceptions,28+)29+from werkzeug.routing import BuildError, Map, RequestRedirect, RoutingException, Rule30 31 from . import cli, json32 from ._compat import integer_types, reraise, string_types, text_type33 from .config import Config, ConfigAttribute34 from .ctx import AppContext, RequestContext, _AppCtxGlobals35 from .globals import _request_ctx_stack, g, request, session36 from .helpers import (37 _PackageBoundObject,33- _endpoint_from_view_func, find_package, get_env, get_debug_flag,34- get_flashed_messages, locked_cached_property, url_for, get_load_dotenv38+ _endpoint_from_view_func,39+ find_package,40+ get_env,41+ get_debug_flag,42+ get_flashed_messages,43+ locked_cached_property,44+ url_for,45+ get_load_dotenv,46 )47 from .logging import create_logger48 from .sessions import SecureCookieSessionInterface38-from .signals import appcontext_tearing_down, got_request_exception, \39- request_finished, request_started, request_tearing_down40-from .templating import DispatchingJinjaLoader, Environment, \41- _default_template_ctx_processor49+from .signals import (50+ appcontext_tearing_down,51+ got_request_exception,52+ request_finished,53+ request_started,54+ request_tearing_down,55+)56+from .templating import (57+ DispatchingJinjaLoader,58+ Environment,59+ _default_template_ctx_processor,60+)61 from .wrappers import Request, Response62 63 # a singleton sentinel value for parameter defaults64 _sentinel = object()8 unmodified lines73 def setupmethod(f):74 """Wraps a method so that it performs a check in debug mode if the75 first request was already handled.76 """77+78 def wrapper_func(self, *args, **kwargs):79 if self.debug and self._got_first_request:60- raise AssertionError('A setup function was called after the '61- 'first request was handled. This usually indicates a bug '62- 'in the application where a module was not imported '63- 'and decorators or other functionality was called too late.\n'64- 'To fix this make sure to import all your view modules, '65- 'database models and everything related at a central place '66- 'before the application starts serving requests.')80+ raise AssertionError(81+ "A setup function was called after the "82+ "first request was handled. This usually indicates a bug "83+ "in the application where a module was not imported "84+ "and decorators or other functionality was called too late.\n"85+ "To fix this make sure to import all your view modules, "86+ "database models and everything related at a central place "87+ "before the application starts serving requests."88+ )89 return f(self, *args, **kwargs)90+91 return update_wrapper(wrapper_func, f)92 93 94 class Flask(_PackageBoundObject):144 unmodified lines239 #: default it's implicitly enabled.240 #:241 #: This attribute can also be configured from the config with the242 #: ``TESTING`` configuration key. Defaults to ``False``.220- testing = ConfigAttribute('TESTING')243+ testing = ConfigAttribute("TESTING")244 245 #: If a secret key is set, cryptographic components can use this to246 #: sign cookies and other things. Set this to a complex random value247 #: when you want to use the secure cookie for instance.248 #:249 #: This attribute can also be configured from the config with the250 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.228- secret_key = ConfigAttribute('SECRET_KEY')251+ secret_key = ConfigAttribute("SECRET_KEY")252 253 #: The secure cookie uses this for the name of the session cookie.254 #:255 #: This attribute can also be configured from the config with the256 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``234- session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')257+ session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")258 259 #: A :class:`~datetime.timedelta` which is used to set the expiration260 #: date of a permanent session. The default is 31 days which makes a261 #: permanent session survive for roughly one month.262 #:263 #: This attribute can also be configured from the config with the264 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to265 #: ``timedelta(days=31)``243- permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',244- get_converter=_make_timedelta)266+ permanent_session_lifetime = ConfigAttribute(267+ "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta268+ )269 270 #: A :class:`~datetime.timedelta` which is used as default cache_timeout271 #: for the :func:`send_file` functions. The default is 12 hours.272 #:273 #: This attribute can also be configured from the config with the274 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration275 #: variable can also be set with an integer value used as seconds.276 #: Defaults to ``timedelta(hours=12)``253- send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',254- get_converter=_make_timedelta)277+ send_file_max_age_default = ConfigAttribute(278+ "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta279+ )280 281 #: Enable this if you want to use the X-Sendfile feature. Keep in282 #: mind that the server has to support this. This only affects files283 #: sent with the :func:`send_file` method.1 unmodified line285 #: .. versionadded:: 0.2286 #:287 #: This attribute can also be configured from the config with the288 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.264- use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')289+ use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")290 291 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.292 #:293 #: .. versionadded:: 0.105 unmodified lines299 json_decoder = json.JSONDecoder300 301 #: Options that are passed directly to the Jinja2 environment.302 jinja_options = ImmutableDict(278- extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']303+ extensions=["jinja2.ext.autoescape", "jinja2.ext.with_"]304 )305 306 #: Default configuration parameters.282- default_config = ImmutableDict({283- 'ENV': None,284- 'DEBUG': None,285- 'TESTING': False,286- 'PROPAGATE_EXCEPTIONS': None,287- 'PRESERVE_CONTEXT_ON_EXCEPTION': None,288- 'SECRET_KEY': None,289- 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),290- 'USE_X_SENDFILE': False,291- 'SERVER_NAME': None,292- 'APPLICATION_ROOT': '/',293- 'SESSION_COOKIE_NAME': 'session',294- 'SESSION_COOKIE_DOMAIN': None,295- 'SESSION_COOKIE_PATH': None,296- 'SESSION_COOKIE_HTTPONLY': True,297- 'SESSION_COOKIE_SECURE': False,298- 'SESSION_COOKIE_SAMESITE': None,299- 'SESSION_REFRESH_EACH_REQUEST': True,300- 'MAX_CONTENT_LENGTH': None,301- 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),302- 'TRAP_BAD_REQUEST_ERRORS': None,303- 'TRAP_HTTP_EXCEPTIONS': False,304- 'EXPLAIN_TEMPLATE_LOADING': False,305- 'PREFERRED_URL_SCHEME': 'http',306- 'JSON_AS_ASCII': True,307- 'JSON_SORT_KEYS': True,308- 'JSONIFY_PRETTYPRINT_REGULAR': False,309- 'JSONIFY_MIMETYPE': 'application/json',310- 'TEMPLATES_AUTO_RELOAD': None,311- 'MAX_COOKIE_SIZE': 4093,312- })307+ default_config = ImmutableDict(308+ {309+ "ENV": None,310+ "DEBUG": None,311+ "TESTING": False,312+ "PROPAGATE_EXCEPTIONS": None,313+ "PRESERVE_CONTEXT_ON_EXCEPTION": None,314+ "SECRET_KEY": None,315+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),316+ "USE_X_SENDFILE": False,317+ "SERVER_NAME": None,318+ "APPLICATION_ROOT": "/",319+ "SESSION_COOKIE_NAME": "session",320+ "SESSION_COOKIE_DOMAIN": None,321+ "SESSION_COOKIE_PATH": None,322+ "SESSION_COOKIE_HTTPONLY": True,323+ "SESSION_COOKIE_SECURE": False,324+ "SESSION_COOKIE_SAMESITE": None,325+ "SESSION_REFRESH_EACH_REQUEST": True,326+ "MAX_CONTENT_LENGTH": None,327+ "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),328+ "TRAP_BAD_REQUEST_ERRORS": None,329+ "TRAP_HTTP_EXCEPTIONS": False,330+ "EXPLAIN_TEMPLATE_LOADING": False,331+ "PREFERRED_URL_SCHEME": "http",332+ "JSON_AS_ASCII": True,333+ "JSON_SORT_KEYS": True,334+ "JSONIFY_PRETTYPRINT_REGULAR": False,335+ "JSONIFY_MIMETYPE": "application/json",336+ "TEMPLATES_AUTO_RELOAD": None,337+ "MAX_COOKIE_SIZE": 4093,338+ }339+ )340 341 #: The rule object to use for URL rules created. This is used by342 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.343 #:37 unmodified lines381 def __init__(382 self,383 import_name,384 static_url_path=None,358- static_folder='static',385+ static_folder="static",386 static_host=None,387 host_matching=False,388 subdomain_matching=False,362- template_folder='templates',389+ template_folder="templates",390 instance_path=None,391 instance_relative_config=False,365- root_path=None392+ root_path=None,393 ):394 _PackageBoundObject.__init__(368- self,369- import_name,370- template_folder=template_folder,371- root_path=root_path395+ self, import_name, template_folder=template_folder, root_path=root_path396 )397 398 if static_url_path is not None:399 self.static_url_path = static_url_path4 unmodified lines404 if instance_path is None:405 instance_path = self.auto_find_instance_path()406 elif not os.path.isabs(instance_path):407 raise ValueError(384- 'If an instance path is provided it must be absolute.'385- ' A relative path was given instead.'408+ "If an instance path is provided it must be absolute."409+ " A relative path was given instead."410 )411 412 #: Holds the path to the instance folder.413 #:99 unmodified lines513 #: name of the blueprint this function is active for, ``None`` for all514 #: requests. Each returns a dictionary that the template context is515 #: updated with. To register a function here, use the516 #: :meth:`context_processor` decorator.493- self.template_context_processors = {494- None: [_default_template_ctx_processor]495- }517+ self.template_context_processors = {None: [_default_template_ctx_processor]}518 519 #: A list of shell context processor functions that should be run520 #: when a shell context is created.521 #:54 unmodified lines576 # Note we do this without checking if static_folder exists.577 # For one, it might be created while the server is running (e.g. during578 # development). Also, Google App Engine stores static files somewhere579 if self.has_static_folder:558- assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'580+ assert (581+ bool(static_host) == host_matching582+ ), "Invalid static_host/host_matching combination"583 self.add_url_rule(560- self.static_url_path + '/<path:filename>',561- endpoint='static',584+ self.static_url_path + "/<path:filename>",585+ endpoint="static",586 host=static_host,563- view_func=self.send_static_file587+ view_func=self.send_static_file,588 )589 590 #: The click command line context for this application. Commands591 #: registered here show up in the :command:`flask` command once the12 unmodified lines604 to change the value.605 606 .. versionadded:: 0.8607 """584- if self.import_name == '__main__':585- fn = getattr(sys.modules['__main__'], '__file__', None)608+ if self.import_name == "__main__":609+ fn = getattr(sys.modules["__main__"], "__file__", None)610 if fn is None:587- return '__main__'611+ return "__main__"612 return os.path.splitext(os.path.basename(fn))[0]613 return self.import_name614 615 @property2 unmodified lines618 value in case it's set, otherwise a sensible default is returned.619 620 .. versionadded:: 0.7621 """598- rv = self.config['PROPAGATE_EXCEPTIONS']622+ rv = self.config["PROPAGATE_EXCEPTIONS"]623 if rv is not None:624 return rv625 return self.testing or self.debug626 4 unmodified lines631 is returned.632 633 .. versionadded:: 0.7634 """611- rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']635+ rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]636 if rv is not None:637 return rv638 return self.debug639 46 unmodified lines686 root_path = self.root_path687 if instance_relative:688 root_path = self.instance_path689 defaults = dict(self.default_config)666- defaults['ENV'] = get_env()667- defaults['DEBUG'] = get_debug_flag()690+ defaults["ENV"] = get_env()691+ defaults["DEBUG"] = get_debug_flag()692 return self.config_class(root_path, defaults)693 694 def auto_find_instance_path(self):695 """Tries to locate the instance path if it was not provided to the4 unmodified lines700 .. versionadded:: 0.8701 """702 prefix, package_path = find_package(self.import_name)703 if prefix is None:680- return os.path.join(package_path, 'instance')681- return os.path.join(prefix, 'var', self.name + '-instance')704+ return os.path.join(package_path, "instance")705+ return os.path.join(prefix, "var", self.name + "-instance")706 683- def open_instance_resource(self, resource, mode='rb'):707+ def open_instance_resource(self, resource, mode="rb"):708 """Opens a resource from the application's instance folder709 (:attr:`instance_path`). Otherwise works like710 :meth:`open_resource`. Instance resources can also be opened for711 writing.14 unmodified lines726 .. versionadded:: 1.0727 This property was added but the underlying config and behavior728 already existed.729 """706- rv = self.config['TEMPLATES_AUTO_RELOAD']730+ rv = self.config["TEMPLATES_AUTO_RELOAD"]731 return rv if rv is not None else self.debug732 733 def _set_templates_auto_reload(self, value):710- self.config['TEMPLATES_AUTO_RELOAD'] = value734+ self.config["TEMPLATES_AUTO_RELOAD"] = value735 736 templates_auto_reload = property(737 _get_templates_auto_reload, _set_templates_auto_reload738 )11 unmodified lines750 ``TEMPLATES_AUTO_RELOAD`` configuration option.751 """752 options = dict(self.jinja_options)753 730- if 'autoescape' not in options:731- options['autoescape'] = self.select_jinja_autoescape754+ if "autoescape" not in options:755+ options["autoescape"] = self.select_jinja_autoescape756 733- if 'auto_reload' not in options:734- options['auto_reload'] = self.templates_auto_reload757+ if "auto_reload" not in options:758+ options["auto_reload"] = self.templates_auto_reload759 760 rv = self.jinja_environment(self, **options)761 rv.globals.update(762 url_for=url_for,3 unmodified lines766 # context processor for efficiency reasons but for imported767 # templates we also want the proxies in there.768 request=request,769 session=session,746- g=g770+ g=g,771 )748- rv.filters['tojson'] = json.tojson_filter772+ rv.filters["tojson"] = json.tojson_filter773 return rv774 775 def create_global_jinja_loader(self):776 """Creates the loader for the Jinja2 environment. Can be used to15 unmodified lines792 .. versionadded:: 0.5793 """794 if filename is None:795 return True772- return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))796+ return filename.endswith((".html", ".htm", ".xml", ".xhtml"))797 798 def update_template_context(self, context):799 """Update the template context with some commonly used variables.800 This injects request, session, config and g into the template25 unmodified lines826 processors.827 828 .. versionadded:: 0.11829 """806- rv = {'app': self, 'g': g}830+ rv = {"app": self, "g": g}831 for processor in self.shell_context_processors:832 rv.update(processor())833 return rv834 5 unmodified lines840 #:841 #: **Do not enable development when deploying in production.**842 #:843 #: Default: ``'production'``820- env = ConfigAttribute('ENV')844+ env = ConfigAttribute("ENV")845 846 def _get_debug(self):823- return self.config['DEBUG']847+ return self.config["DEBUG"]848 849 def _set_debug(self, value):826- self.config['DEBUG'] = value850+ self.config["DEBUG"] = value851 self.jinja_env.auto_reload = self.templates_auto_reload852 853 #: Whether debug mode is enabled. When using ``flask run`` to start854 #: the development server, an interactive debugger will be shown for9 unmodified lines864 #: ``False`` otherwise.865 debug = property(_get_debug, _set_debug)866 del _get_debug, _set_debug867 844- def run(self, host=None, port=None, debug=None,845- load_dotenv=True, **options):868+ def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):869 """Runs the application on a local development server.870 871 Do not use ``run()`` in a production setting. It is not intended to872 meet security and performance requirements for a production server.51 unmodified lines924 variable.925 """926 # Change this into a no-op if the server is invoked from the927 # command line. Have a look at cli.py for more information.905- if os.environ.get('FLASK_RUN_FROM_CLI') == 'true':928+ if os.environ.get("FLASK_RUN_FROM_CLI") == "true":929 from .debughelpers import explain_ignored_app_run930+931 explain_ignored_app_run()932 return933 934 if get_load_dotenv(load_dotenv):935 cli.load_dotenv()936 937 # if set, let env vars override previous values914- if 'FLASK_ENV' in os.environ:938+ if "FLASK_ENV" in os.environ:939 self.env = get_env()940 self.debug = get_debug_flag()917- elif 'FLASK_DEBUG' in os.environ:941+ elif "FLASK_DEBUG" in os.environ:942 self.debug = get_debug_flag()943 944 # debug passed to method overrides all other sources945 if debug is not None:946 self.debug = bool(debug)947 924- _host = '127.0.0.1'948+ _host = "127.0.0.1"949 _port = 5000926- server_name = self.config.get('SERVER_NAME')950+ server_name = self.config.get("SERVER_NAME")951 sn_host, sn_port = None, None952 953 if server_name:930- sn_host, _, sn_port = server_name.partition(':')954+ sn_host, _, sn_port = server_name.partition(":")955 956 host = host or sn_host or _host957 port = int(port or sn_port or _port)958 935- options.setdefault('use_reloader', self.debug)936- options.setdefault('use_debugger', self.debug)937- options.setdefault('threaded', True)959+ options.setdefault("use_reloader", self.debug)960+ options.setdefault("use_debugger", self.debug)961+ options.setdefault("threaded", True)962 963 cli.show_server_banner(self.env, self.debug, self.name, False)964 965 from werkzeug.serving import run_simple91 unmodified lines1057 1058 :param request: an instance of :attr:`request_class`.1059 """1060 1061+ warnings.warn(1037- warnings.warn(DeprecationWarning(1038- '"open_session" is deprecated and will be removed in 1.1. Use'1039- ' "session_interface.open_session" instead.'1040- ))1062+ DeprecationWarning(1063+ '"open_session" is deprecated and will be removed in 1.1. Use'1064+ ' "session_interface.open_session" instead.'1065+ )1066+ )1067 return self.session_interface.open_session(self, request)1068 1069 def save_session(self, session, response):1070 """Saves the session if it needs updates. For the default9 unmodified lines1080 object)1081 :param response: an instance of :attr:`response_class`1082 """1083 1084+ warnings.warn(1058- warnings.warn(DeprecationWarning(1059- '"save_session" is deprecated and will be removed in 1.1. Use'1060- ' "session_interface.save_session" instead.'1061- ))1085+ DeprecationWarning(1086+ '"save_session" is deprecated and will be removed in 1.1. Use'1087+ ' "session_interface.save_session" instead.'1088+ )1089+ )1090 return self.session_interface.save_session(self, session, response)1091 1092 def make_null_session(self):1093 """Creates a new instance of a missing session. Instead of overriding5 unmodified lines1099 1100 .. versionadded:: 0.71101 """1102 1103+ warnings.warn(1075- warnings.warn(DeprecationWarning(1076- '"make_null_session" is deprecated and will be removed in 1.1. Use'1077- ' "session_interface.make_null_session" instead.'1078- ))1104+ DeprecationWarning(1105+ '"make_null_session" is deprecated and will be removed in 1.1. Use'1106+ ' "session_interface.make_null_session" instead.'1107+ )1108+ )1109 return self.session_interface.make_null_session(self)1110 1111 @setupmethod1112 def register_blueprint(self, blueprint, **options):18 unmodified lines1131 first_registration = False1132 1133 if blueprint.name in self.blueprints:1134 assert self.blueprints[blueprint.name] is blueprint, (1105- 'A name collision occurred between blueprints %r and %r. Both'1135+ "A name collision occurred between blueprints %r and %r. Both"1136 ' share the same name "%s". Blueprints that are created on the'1107- ' fly need unique names.' % (1108- blueprint, self.blueprints[blueprint.name], blueprint.name1109- )1137+ " fly need unique names."1138+ % (blueprint, self.blueprints[blueprint.name], blueprint.name)1139 )1140 else:1141 self.blueprints[blueprint.name] = blueprint1142 self._blueprint_order.append(blueprint)8 unmodified lines1151 """1152 return iter(self._blueprint_order)1153 1154 @setupmethod1126- def add_url_rule(self, rule, endpoint=None, view_func=None,1127- provide_automatic_options=None, **options):1155+ def add_url_rule(1156+ self,1157+ rule,1158+ endpoint=None,1159+ view_func=None,1160+ provide_automatic_options=None,1161+ **options1162+ ):1163 """Connects a URL rule. Works exactly like the :meth:`route`1164 decorator. If a view_func is provided it will be registered with the1165 endpoint.1166 46 unmodified lines1213 added and handled by the standard request handling.1214 """1215 if endpoint is None:1216 endpoint = _endpoint_from_view_func(view_func)1182- options['endpoint'] = endpoint1183- methods = options.pop('methods', None)1217+ options["endpoint"] = endpoint1218+ methods = options.pop("methods", None)1219 1220 # if the methods are not given and the view_func object knows its1221 # methods we can use that instead. If neither exists, we go with1222 # a tuple of only ``GET`` as default.1223 if methods is None:1189- methods = getattr(view_func, 'methods', None) or ('GET',)1224+ methods = getattr(view_func, "methods", None) or ("GET",)1225 if isinstance(methods, string_types):1191- raise TypeError('Allowed methods have to be iterables of strings, '1192- 'for example: @app.route(..., methods=["POST"])')1226+ raise TypeError(1227+ "Allowed methods have to be iterables of strings, "1228+ 'for example: @app.route(..., methods=["POST"])'1229+ )1230 methods = set(item.upper() for item in methods)1231 1232 # Methods that should always be added1196- required_methods = set(getattr(view_func, 'required_methods', ()))1233+ required_methods = set(getattr(view_func, "required_methods", ()))1234 1235 # starting with Flask 0.8 the view_func object can disable and1236 # force-enable the automatic options handling.1237 if provide_automatic_options is None:1201- provide_automatic_options = getattr(view_func,1202- 'provide_automatic_options', None)1238+ provide_automatic_options = getattr(1239+ view_func, "provide_automatic_options", None1240+ )1241 1242 if provide_automatic_options is None:1205- if 'OPTIONS' not in methods:1243+ if "OPTIONS" not in methods:1244 provide_automatic_options = True1207- required_methods.add('OPTIONS')1245+ required_methods.add("OPTIONS")1246 else:1247 provide_automatic_options = False1248 1249 # Add the required methods now.5 unmodified lines1255 self.url_map.add(rule)1256 if view_func is not None:1257 old_func = self.view_functions.get(endpoint)1258 if old_func is not None and old_func != view_func:1221- raise AssertionError('View function mapping is overwriting an '1222- 'existing endpoint function: %s' % endpoint)1259+ raise AssertionError(1260+ "View function mapping is overwriting an "1261+ "existing endpoint function: %s" % endpoint1262+ )1263 self.view_functions[endpoint] = view_func1264 1265 def route(self, rule, **options):1266 """A decorator that is used to register a view function for a18 unmodified lines1285 just listens for ``GET`` (and implicitly ``HEAD``).1286 Starting with Flask 0.6, ``OPTIONS`` is implicitly1287 added and handled by the standard request handling.1288 """1289+1290 def decorator(f):1250- endpoint = options.pop('endpoint', None)1291+ endpoint = options.pop("endpoint", None)1292 self.add_url_rule(rule, endpoint, f, **options)1293 return f1294+1295 return decorator1296 1297 @setupmethod1298 def endpoint(self, endpoint):5 unmodified lines1304 return "example"1305 1306 :param endpoint: the name of the endpoint1307 """1308+1309 def decorator(f):1310 self.view_functions[endpoint] = f1311 return f1312+1313 return decorator1314 1315 @staticmethod1316 def _get_exc_class_and_code(exc_class_or_code):39 unmodified lines1356 1357 :param code_or_exception: the code as integer for the handler, or1358 an arbitrary exception1359 """1360+1361 def decorator(f):1362 self._register_error_handler(None, code_or_exception, f)1363 return f1364+1365 return decorator1366 1367 @setupmethod1368 def register_error_handler(self, code_or_exception, f):13 unmodified lines1382 :type f: callable1383 """1384 if isinstance(code_or_exception, HTTPException): # old broken behavior1385 raise ValueError(1340- 'Tried to register a handler for an exception instance {0!r}.'1341- ' Handlers can only be registered for exception classes or'1342- ' HTTP error codes.'.format(code_or_exception)1386+ "Tried to register a handler for an exception instance {0!r}."1387+ " Handlers can only be registered for exception classes or"1388+ " HTTP error codes.".format(code_or_exception)1389 )1390 1391 try:1392 exc_class, code = self._get_exc_class_and_code(code_or_exception)18 unmodified lines1411 1412 :param name: the optional name of the filter, otherwise the1413 function name will be used.1414 """1415+1416 def decorator(f):1417 self.add_template_filter(f, name=name)1418 return f1419+1420 return decorator1421 1422 @setupmethod1423 def add_template_filter(self, f, name=None):24 unmodified lines1448 1449 :param name: the optional name of the test, otherwise the1450 function name will be used.1451 """1452+1453 def decorator(f):1454 self.add_template_test(f, name=name)1455 return f1456+1457 return decorator1458 1459 @setupmethod1460 def add_template_test(self, f, name=None):21 unmodified lines1482 1483 :param name: the optional name of the global function, otherwise the1484 function name will be used.1485 """1486+1487 def decorator(f):1488 self.add_template_global(f, name=name)1489 return f1490+1491 return decorator1492 1493 @setupmethod1494 def add_template_global(self, f, name=None):169 unmodified lines1664 """1665 exc_class, code = self._get_exc_class_and_code(type(e))1666 1667 for name, c in (1616- (request.blueprint, code), (None, code),1617- (request.blueprint, None), (None, None)1668+ (request.blueprint, code),1669+ (None, code),1670+ (request.blueprint, None),1671+ (None, None),1672 ):1673 handler_map = self.error_handler_spec.setdefault(name, {}).get(c)1674 1675 if not handler_map:54 unmodified lines1730 Bad request errors are not trapped by default in debug mode.1731 1732 .. versionadded:: 0.81733 """1680- if self.config['TRAP_HTTP_EXCEPTIONS']:1734+ if self.config["TRAP_HTTP_EXCEPTIONS"]:1735 return True1736 1683- trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']1737+ trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]1738 1739 # if unset, trap key errors in debug mode1740 if (1687- trap_bad_request is None and self.debug1741+ trap_bad_request is None1742+ and self.debug1743 and isinstance(e, BadRequestKeyError)1744 ):1745 return True1746 80 unmodified lines1827 :attr:`logger`.1828 1829 .. versionadded:: 0.81830 """1776- self.logger.error('Exception on %s [%s]' % (1777- request.path,1778- request.method1779- ), exc_info=exc_info)1831+ self.logger.error(1832+ "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1833+ )1834 1835 def raise_routing_exception(self, request):1836 """Exceptions that are recording during routing are reraised with1837 this method. During debug we are not reraising redirect requests1 unmodified line1839 a different error instead to help debug situations.1840 1841 :internal:1842 """1789- if not self.debug \1790- or not isinstance(request.routing_exception, RequestRedirect) \1791- or request.method in ('GET', 'HEAD', 'OPTIONS'):1843+ if (1844+ not self.debug1845+ or not isinstance(request.routing_exception, RequestRedirect)1846+ or request.method in ("GET", "HEAD", "OPTIONS")1847+ ):1848 raise request.routing_exception1849 1850 from .debughelpers import FormDataRoutingRedirect1851+1852 raise FormDataRoutingRedirect(request)1853 1854 def dispatch_request(self):1855 """Does the request dispatching. Matches the URL and returns the10 unmodified lines1866 self.raise_routing_exception(req)1867 rule = req.url_rule1868 # if we provide automatic options for this URL and the1869 # request came with the OPTIONS method, reply automatically1813- if getattr(rule, 'provide_automatic_options', False) \1814- and req.method == 'OPTIONS':1870+ if (1871+ getattr(rule, "provide_automatic_options", False)1872+ and req.method == "OPTIONS"1873+ ):1874 return self.make_default_options_response()1875 # otherwise dispatch to the handler for that endpoint1876 return self.view_functions[rule.endpoint](**req.view_args)1877 33 unmodified lines1911 request_finished.send(self, response=response)1912 except Exception:1913 if not from_error_handler:1914 raise1856- self.logger.exception('Request finalizing failed with an '1857- 'error while handling an error')1915+ self.logger.exception(1916+ "Request finalizing failed with an " "error while handling an error"1917+ )1918 return response1919 1920 def try_trigger_before_first_request_functions(self):1921 """Called before each request and will ensure that it triggers18 unmodified lines1940 1941 .. versionadded:: 0.71942 """1943 adapter = _request_ctx_stack.top.url_adapter1884- if hasattr(adapter, 'allowed_methods'):1944+ if hasattr(adapter, "allowed_methods"):1945 methods = adapter.allowed_methods()1946 else:1947 # fallback for Werkzeug < 0.71948 methods = []1949 try:1890- adapter.match(method='--')1950+ adapter.match(method="--")1951 except MethodNotAllowed as e:1952 methods = e.valid_methods1953 except HTTPException as e:1954 pass68 unmodified lines2023 rv, status = rv2024 # other sized tuples are not allowed2025 else:2026 raise TypeError(1967- 'The view function did not return a valid response tuple.'1968- ' The tuple must have the form (body, status, headers),'1969- ' (body, status), or (body, headers).'2027+ "The view function did not return a valid response tuple."2028+ " The tuple must have the form (body, status, headers),"2029+ " (body, status), or (body, headers)."2030 )2031 2032 # the body must not be None2033 if rv is None:2034 raise TypeError(1975- 'The view function did not return a valid response. The'1976- ' function either returned None or ended without a return'1977- ' statement.'2035+ "The view function did not return a valid response. The"2036+ " function either returned None or ended without a return"2037+ " statement."2038 )2039 2040 # make sure the body is an instance of the response class2041 if not isinstance(rv, self.response_class):9 unmodified lines2051 try:2052 rv = self.response_class.force_type(rv, request.environ)2053 except TypeError as e:2054 new_error = TypeError(1995- '{e}\nThe view function did not return a valid'1996- ' response. The return type must be a string, tuple,'1997- ' Response instance, or WSGI callable, but it was a'1998- ' {rv.__class__.__name__}.'.format(e=e, rv=rv)2055+ "{e}\nThe view function did not return a valid"2056+ " response. The return type must be a string, tuple,"2057+ " Response instance, or WSGI callable, but it was a"2058+ " {rv.__class__.__name__}.".format(e=e, rv=rv)2059 )2060 reraise(TypeError, new_error, sys.exc_info()[2])2061 2062 # prefer the status if it was provided27 unmodified lines2090 if request is not None:2091 # If subdomain matching is disabled (the default), use the2092 # default subdomain in all cases. This should be the default2093 # in Werkzeug but it currently does not have that feature.2094+ subdomain = (2034- subdomain = ((self.url_map.default_subdomain or None)2035- if not self.subdomain_matching else None)2095+ (self.url_map.default_subdomain or None)2096+ if not self.subdomain_matching2097+ else None2098+ )2099 return self.url_map.bind_to_environ(2100 request.environ,2038- server_name=self.config['SERVER_NAME'],2039- subdomain=subdomain)2101+ server_name=self.config["SERVER_NAME"],2102+ subdomain=subdomain,2103+ )2104 # We need at the very least the server name to be set for this2105 # to work.2042- if self.config['SERVER_NAME'] is not None:2106+ if self.config["SERVER_NAME"] is not None:2107 return self.url_map.bind(2044- self.config['SERVER_NAME'],2045- script_name=self.config['APPLICATION_ROOT'],2046- url_scheme=self.config['PREFERRED_URL_SCHEME'])2108+ self.config["SERVER_NAME"],2109+ script_name=self.config["APPLICATION_ROOT"],2110+ url_scheme=self.config["PREFERRED_URL_SCHEME"],2111+ )2112 2113 def inject_url_defaults(self, endpoint, values):2114 """Injects the URL defaults for the given endpoint directly into2115 the values dictionary passed. This is used internally and1 unmodified line2117 2118 .. versionadded:: 0.72119 """2120 funcs = self.url_default_functions.get(None, ())2056- if '.' in endpoint:2057- bp = endpoint.rsplit('.', 1)[0]2121+ if "." in endpoint:2122+ bp = endpoint.rsplit(".", 1)[0]2123 funcs = chain(funcs, self.url_default_functions.get(bp, ()))2124 for func in funcs:2125 func(endpoint, values)2126 264 unmodified lines2391 wrapped to applying middleware."""2392 return self.wsgi_app(environ, start_response)2393 2394 def __repr__(self):2330- return '<%s %r>' % (2331- self.__class__.__name__,2332- self.name,2333- )2395+ return "<%s %r>" % (self.__class__.__name__, self.name)modified:flask/blueprints.py+113 added-54 removed
37 unmodified lines38 #: multiple times on it, this attribute can be used to figure39 #: out if the blueprint was registered in the past already.40 self.first_registration = first_registration41 42- subdomain = self.options.get('subdomain')42+ subdomain = self.options.get("subdomain")43 if subdomain is None:44 subdomain = self.blueprint.subdomain45 46 #: The subdomain that the blueprint should be active for, ``None``47 #: otherwise.48 self.subdomain = subdomain49 50- url_prefix = self.options.get('url_prefix')50+ url_prefix = self.options.get("url_prefix")51 if url_prefix is None:52 url_prefix = self.blueprint.url_prefix53 #: The prefix that should be used for all URLs defined on the54 #: blueprint.1 unmodified line56 57 #: A dictionary with URL defaults that is added to each and every58 #: URL that was defined with the blueprint.59 self.url_defaults = dict(self.blueprint.url_values_defaults)60- self.url_defaults.update(self.options.get('url_defaults', ()))60+ self.url_defaults.update(self.options.get("url_defaults", ()))61 62 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):63 """A helper method to register a rule (and optionally a view function)64 to the application. The endpoint is automatically prefixed with the65 blueprint's name.66 """67 if self.url_prefix is not None:68 if rule:69- rule = '/'.join((70- self.url_prefix.rstrip('/'), rule.lstrip('/')))69+ rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))70 else:71 rule = self.url_prefix73- options.setdefault('subdomain', self.subdomain)72+ options.setdefault("subdomain", self.subdomain)73 if endpoint is None:74 endpoint = _endpoint_from_view_func(view_func)75 defaults = self.url_defaults77- if 'defaults' in options:78- defaults = dict(defaults, **options.pop('defaults'))79- self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint),80- view_func, defaults=defaults, **options)76+ if "defaults" in options:77+ defaults = dict(defaults, **options.pop("defaults"))78+ self.app.add_url_rule(79+ rule,80+ "%s.%s" % (self.blueprint.name, endpoint),81+ view_func,82+ defaults=defaults,83+ **options84+ )85 86 87 class Blueprint(_PackageBoundObject):88 """Represents a blueprint. A blueprint is an object that records29 unmodified lines118 #: Absolute path to the package on the filesystem. Used to look up119 #: resources contained in the package.120 root_path = None121 118- def __init__(self, name, import_name, static_folder=None,119- static_url_path=None, template_folder=None,120- url_prefix=None, subdomain=None, url_defaults=None,121- root_path=None):122- _PackageBoundObject.__init__(self, import_name, template_folder,123- root_path=root_path)122+ def __init__(123+ self,124+ name,125+ import_name,126+ static_folder=None,127+ static_url_path=None,128+ template_folder=None,129+ url_prefix=None,130+ subdomain=None,131+ url_defaults=None,132+ root_path=None,133+ ):134+ _PackageBoundObject.__init__(135+ self, import_name, template_folder, root_path=root_path136+ )137 self.name = name138 self.url_prefix = url_prefix139 self.subdomain = subdomain140 self.static_folder = static_folder10 unmodified lines151 method.152 """153 if self._got_registered_once and self.warn_on_modifications:154 from warnings import warn142- warn(Warning('The blueprint was already registered once '143- 'but is getting modified now. These changes '144- 'will not show up.'))155+156+ warn(157+ Warning(158+ "The blueprint was already registered once "159+ "but is getting modified now. These changes "160+ "will not show up."161+ )162+ )163 self.deferred_functions.append(func)164 165 def record_once(self, func):166 """Works like :meth:`record` but wraps the function in another167 function that will ensure the function is only called once. If the168 blueprint is registered a second time on the application, the169 function passed is not called.170 """171+172 def wrapper(state):173 if state.first_registration:174 func(state)175+176 return self.record(update_wrapper(wrapper, func))177 178 def make_setup_state(self, app, options, first_registration=False):179 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`18 unmodified lines198 state = self.make_setup_state(app, options, first_registration)199 200 if self.has_static_folder:201 state.add_url_rule(182- self.static_url_path + '/<path:filename>',183- view_func=self.send_static_file, endpoint='static'202+ self.static_url_path + "/<path:filename>",203+ view_func=self.send_static_file,204+ endpoint="static",205 )206 207 for deferred in self.deferred_functions:208 deferred(state)1 unmodified line210 def route(self, rule, **options):211 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the212 :func:`url_for` function is prefixed with the name of the blueprint.213 """214+215 def decorator(f):216 endpoint = options.pop("endpoint", f.__name__)217 self.add_url_rule(rule, endpoint, f, **options)218 return f219+220 return decorator221 222 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):223 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for224 the :func:`url_for` function is prefixed with the name of the blueprint.225 """226 if endpoint:204- assert '.' not in endpoint, "Blueprint endpoints should not contain dots"205- if view_func and hasattr(view_func, '__name__'):206- assert '.' not in view_func.__name__, "Blueprint view function name should not contain dots"207- self.record(lambda s:208- s.add_url_rule(rule, endpoint, view_func, **options))227+ assert "." not in endpoint, "Blueprint endpoints should not contain dots"228+ if view_func and hasattr(view_func, "__name__"):229+ assert (230+ "." not in view_func.__name__231+ ), "Blueprint view function name should not contain dots"232+ self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))233 234 def endpoint(self, endpoint):235 """Like :meth:`Flask.endpoint` but for a blueprint. This does not236 prefix the endpoint with the blueprint name, this has to be done237 explicitly by the user of this method. If the endpoint is prefixed238 with a `.` it will be registered to the current blueprint, otherwise239 it's an application independent endpoint.240 """241+242 def decorator(f):243 def register_endpoint(state):244 state.app.view_functions[endpoint] = f245+246 self.record_once(register_endpoint)247 return f248+249 return decorator250 251 def app_template_filter(self, name=None):252 """Register a custom template filter, available application wide. Like1 unmodified line254 255 :param name: the optional name of the filter, otherwise the256 function name will be used.257 """258+259 def decorator(f):260 self.add_app_template_filter(f, name=name)261 return f262+263 return decorator264 265 def add_app_template_filter(self, f, name=None):266 """Register a custom template filter, available application wide. Like2 unmodified lines269 270 :param name: the optional name of the filter, otherwise the271 function name will be used.272 """273+274 def register_template(state):275 state.app.jinja_env.filters[name or f.__name__] = f276+277 self.record_once(register_template)278 279 def app_template_test(self, name=None):280 """Register a custom template test, available application wide. Like3 unmodified lines284 285 :param name: the optional name of the test, otherwise the286 function name will be used.287 """288+289 def decorator(f):290 self.add_app_template_test(f, name=name)291 return f292+293 return decorator294 295 def add_app_template_test(self, f, name=None):296 """Register a custom template test, available application wide. Like4 unmodified lines301 302 :param name: the optional name of the test, otherwise the303 function name will be used.304 """305+306 def register_template(state):307 state.app.jinja_env.tests[name or f.__name__] = f308+309 self.record_once(register_template)310 311 def app_template_global(self, name=None):312 """Register a custom template global, available application wide. Like3 unmodified lines316 317 :param name: the optional name of the global, otherwise the318 function name will be used.319 """320+321 def decorator(f):322 self.add_app_template_global(f, name=name)323 return f324+325 return decorator326 327 def add_app_template_global(self, f, name=None):328 """Register a custom template global, available application wide. Like4 unmodified lines333 334 :param name: the optional name of the global, otherwise the335 function name will be used.336 """337+338 def register_template(state):339 state.app.jinja_env.globals[name or f.__name__] = f340+341 self.record_once(register_template)342 343 def before_request(self, f):344 """Like :meth:`Flask.before_request` but for a blueprint. This function345 is only executed before each request that is handled by a function of346 that blueprint.347 """309- self.record_once(lambda s: s.app.before_request_funcs310- .setdefault(self.name, []).append(f))348+ self.record_once(349+ lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f)350+ )351 return f352 353 def before_app_request(self, f):354 """Like :meth:`Flask.before_request`. Such a function is executed355 before each request, even if outside of a blueprint.356 """317- self.record_once(lambda s: s.app.before_request_funcs318- .setdefault(None, []).append(f))357+ self.record_once(358+ lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)359+ )360 return f361 362 def before_app_first_request(self, f):363 """Like :meth:`Flask.before_first_request`. Such a function is6 unmodified lines370 """Like :meth:`Flask.after_request` but for a blueprint. This function371 is only executed after each request that is handled by a function of372 that blueprint.373 """333- self.record_once(lambda s: s.app.after_request_funcs334- .setdefault(self.name, []).append(f))374+ self.record_once(375+ lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f)376+ )377 return f378 379 def after_app_request(self, f):380 """Like :meth:`Flask.after_request` but for a blueprint. Such a function381 is executed after each request, even if outside of the blueprint.382 """341- self.record_once(lambda s: s.app.after_request_funcs342- .setdefault(None, []).append(f))383+ self.record_once(384+ lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)385+ )386 return f387 388 def teardown_request(self, f):389 """Like :meth:`Flask.teardown_request` but for a blueprint. This1 unmodified line391 function of that blueprint. Teardown request functions are executed392 when the request context is popped, even when no actual request was393 performed.394 """352- self.record_once(lambda s: s.app.teardown_request_funcs353- .setdefault(self.name, []).append(f))395+ self.record_once(396+ lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f)397+ )398 return f399 400 def teardown_app_request(self, f):401 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a402 function is executed when tearing down each request, even if outside of403 the blueprint.404 """361- self.record_once(lambda s: s.app.teardown_request_funcs362- .setdefault(None, []).append(f))405+ self.record_once(406+ lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)407+ )408 return f409 410 def context_processor(self, f):411 """Like :meth:`Flask.context_processor` but for a blueprint. This412 function is only executed for requests handled by a blueprint.413 """369- self.record_once(lambda s: s.app.template_context_processors370- .setdefault(self.name, []).append(f))414+ self.record_once(415+ lambda s: s.app.template_context_processors.setdefault(416+ self.name, []417+ ).append(f)418+ )419 return f420 421 def app_context_processor(self, f):422 """Like :meth:`Flask.context_processor` but for a blueprint. Such a423 function is executed each request, even if outside of the blueprint.424 """377- self.record_once(lambda s: s.app.template_context_processors378- .setdefault(None, []).append(f))425+ self.record_once(426+ lambda s: s.app.template_context_processors.setdefault(None, []).append(f)427+ )428 return f429 430 def app_errorhandler(self, code):431 """Like :meth:`Flask.errorhandler` but for a blueprint. This432 handler is used for all requests, even if outside of the blueprint.433 """434+435 def decorator(f):436 self.record_once(lambda s: s.app.errorhandler(code)(f))437 return f438+439 return decorator440 441 def url_value_preprocessor(self, f):442 """Registers a function as URL value preprocessor for this443 blueprint. It's called before the view functions are called and444 can modify the url values provided.445 """395- self.record_once(lambda s: s.app.url_value_preprocessors396- .setdefault(self.name, []).append(f))446+ self.record_once(447+ lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f)448+ )449 return f450 451 def url_defaults(self, f):452 """Callback function for URL defaults for this blueprint. It's called453 with the endpoint and values and should update the values passed454 in place.455 """404- self.record_once(lambda s: s.app.url_default_functions405- .setdefault(self.name, []).append(f))456+ self.record_once(457+ lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f)458+ )459 return f460 461 def app_url_value_preprocessor(self, f):462 """Same as :meth:`url_value_preprocessor` but application wide.463 """411- self.record_once(lambda s: s.app.url_value_preprocessors412- .setdefault(None, []).append(f))464+ self.record_once(465+ lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)466+ )467 return f468 469 def app_url_defaults(self, f):470 """Same as :meth:`url_defaults` but application wide.471 """418- self.record_once(lambda s: s.app.url_default_functions419- .setdefault(None, []).append(f))472+ self.record_once(473+ lambda s: s.app.url_default_functions.setdefault(None, []).append(f)474+ )475 return f476 477 def errorhandler(self, code_or_exception):478 """Registers an error handler that becomes active for this blueprint5 unmodified lines484 485 Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator486 of the :class:`~flask.Flask` object.487 """488+489 def decorator(f):434- self.record_once(lambda s: s.app._register_error_handler(435- self.name, code_or_exception, f))490+ self.record_once(491+ lambda s: s.app._register_error_handler(self.name, code_or_exception, f)492+ )493 return f494+495 return decorator496 497 def register_error_handler(self, code_or_exception, f):498 """Non-decorator version of the :meth:`errorhandler` error attach2 unmodified lines501 for error handlers limited to this blueprint.502 503 .. versionadded:: 0.11504 """447- self.record_once(lambda s: s.app._register_error_handler(448- self.name, code_or_exception, f))505+ self.record_once(506+ lambda s: s.app._register_error_handler(self.name, code_or_exception, f)507+ )modified:flask/cli.py+180 added-159 removed
46 unmodified lines47 """48 from . import Flask49 50 # Search for the most common names first.51- for attr_name in ('app', 'application'):51+ for attr_name in ("app", "application"):52 app = getattr(module, attr_name, None)53 54 if isinstance(app, Flask):55 return app56 57 # Otherwise find the only object that is a Flask instance.58- matches = [59- v for v in itervalues(module.__dict__) if isinstance(v, Flask)60- ]58+ matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]59 60 if len(matches) == 1:61 return matches[0]62 elif len(matches) > 1:63 raise NoAppException(64 'Detected multiple Flask applications in module "{module}". Use '65 '"FLASK_APP={module}:name" to specify the correct '68- 'one.'.format(module=module.__name__)66+ "one.".format(module=module.__name__)67 )68 69 # Search for app factory functions.72- for attr_name in ('create_app', 'make_app'):70+ for attr_name in ("create_app", "make_app"):71 app_factory = getattr(module, attr_name, None)72 73 if inspect.isfunction(app_factory):74 try:5 unmodified lines80 if not _called_with_wrong_args(app_factory):81 raise82 raise NoAppException(83 'Detected factory "{factory}" in module "{module}", but '86- 'could not call it without arguments. Use '87- '"FLASK_APP=\'{module}:{factory}(args)\'" to specify '88- 'arguments.'.format(89- factory=attr_name, module=module.__name__90- )84+ "could not call it without arguments. Use "85+ "\"FLASK_APP='{module}:{factory}(args)'\" to specify "86+ "arguments.".format(factory=attr_name, module=module.__name__)87 )88 89 raise NoAppException(90 'Failed to find Flask application or factory in module "{module}". '95- 'Use "FLASK_APP={module}:name to specify one.'.format(96- module=module.__name__97- )91+ 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)92 )93 94 95 def call_factory(script_info, app_factory, arguments=()):4 unmodified lines100 args_spec = getargspec(app_factory)101 arg_names = args_spec.args102 arg_defaults = args_spec.defaults103 110- if 'script_info' in arg_names:104+ if "script_info" in arg_names:105 return app_factory(*arguments, script_info=script_info)106 elif arguments:107 return app_factory(*arguments)108 elif not arguments and len(arg_names) == 1 and arg_defaults is None:32 unmodified lines141 ``script_info`` argument and calls the function with the appropriate142 arguments.143 """144 from flask import Flask151- match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name)145 146+ match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)147+148 if not match:149 raise NoAppException(150 '"{name}" is not a valid variable name or function '156- 'expression.'.format(name=app_name)151+ "expression.".format(name=app_name)152 )153 154 name, args = match.groups()155 4 unmodified lines160 161 if inspect.isfunction(attr):162 if args:163 try:169- args = ast.literal_eval('({args},)'.format(args=args))170- except (ValueError, SyntaxError)as e:164+ args = ast.literal_eval("({args},)".format(args=args))165+ except (ValueError, SyntaxError) as e:166 raise NoAppException(172- 'Could not parse the arguments in '167+ "Could not parse the arguments in "168 '"{app_name}".'.format(e=e, app_name=app_name)169 )170 else:171 args = ()5 unmodified lines177 raise178 179 raise NoAppException(180 '{e}\nThe factory "{app_name}" in module "{module}" could not '186- 'be called with the specified arguments.'.format(181+ "be called with the specified arguments.".format(182 e=e, app_name=app_name, module=module.__name__183 )184 )185 else:2 unmodified lines188 if isinstance(app, Flask):189 return app190 191 raise NoAppException(197- 'A valid Flask application was not obtained from '198- '"{module}:{app_name}".'.format(199- module=module.__name__, app_name=app_name200- )192+ "A valid Flask application was not obtained from "193+ '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)194 )195 196 197 def prepare_import(path):2 unmodified lines200 """201 path = os.path.realpath(path)202 203 fname, ext = os.path.splitext(path)211- if ext == '.py':204+ if ext == ".py":205 path = fname206 214- if os.path.basename(path) == '__init__':207+ if os.path.basename(path) == "__init__":208 path = os.path.dirname(path)209 210 module_name = []211 1 unmodified line213 while True:214 path, name = os.path.split(path)215 module_name.append(name)216 224- if not os.path.exists(os.path.join(path, '__init__.py')):217+ if not os.path.exists(os.path.join(path, "__init__.py")):218 break219 220 if sys.path[0] != path:221 sys.path.insert(0, path)222 230- return '.'.join(module_name[::-1])223+ return ".".join(module_name[::-1])224 225 226 def locate_app(script_info, module_name, app_name, raise_if_not_found=True):227 __traceback_hide__ = True5 unmodified lines233 # Determine this by checking whether the trace has a depth > 1.234 if sys.exc_info()[-1].tb_next:235 raise NoAppException(236 'While importing "{name}", an ImportError was raised:'244- '\n\n{tb}'.format(name=module_name, tb=traceback.format_exc())237+ "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())238 )239 elif raise_if_not_found:247- raise NoAppException(248- 'Could not import "{name}".'.format(name=module_name)249- )240+ raise NoAppException('Could not import "{name}".'.format(name=module_name))241 else:242 return243 244 module = sys.modules[module_name]7 unmodified lines252 def get_version(ctx, param, value):253 if not value or ctx.resilient_parsing:254 return255 import werkzeug265- message = (266- 'Python %(python)s\n'267- 'Flask %(flask)s\n'268- 'Werkzeug %(werkzeug)s'256+257+ message = "Python %(python)s\n" "Flask %(flask)s\n" "Werkzeug %(werkzeug)s"258+ click.echo(259+ message260+ % {261+ "python": platform.python_version(),262+ "flask": __version__,263+ "werkzeug": werkzeug.__version__,264+ },265+ color=ctx.color,266 )270- click.echo(message % {271- 'python': platform.python_version(),272- 'flask': __version__,273- 'werkzeug': werkzeug.__version__,274- }, color=ctx.color)267 ctx.exit()268 269 270 version_option = click.Option(279- ['--version'],280- help='Show the flask version',271+ ["--version"],272+ help="Show the flask version",273 expose_value=False,274 callback=get_version,275 is_flag=True,284- is_eager=True276+ is_eager=True,277 )278 279 280 class DispatchingApp(object):20 unmodified lines301 try:302 self._load_unlocked()303 except Exception:304 self._bg_loading_exc_info = sys.exc_info()305+306 t = Thread(target=_load_app, args=())307 t.start()308 309 def _flush_bg_loading_exception(self):30 unmodified lines340 :class:`FlaskGroup` but you can also manually create it and pass it341 onwards as click object.342 """343 351- def __init__(self, app_import_path=None, create_app=None,352- set_debug_flag=True):344+ def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):345 #: Optionally the import path for the Flask application.354- self.app_import_path = app_import_path or os.environ.get('FLASK_APP')346+ self.app_import_path = app_import_path or os.environ.get("FLASK_APP")347 #: Optionally a function that is passed the script info to create348 #: the instance of the application.349 self.create_app = create_app350 #: A dictionary with arbitrary data that can be associated with17 unmodified lines368 if self.create_app is not None:369 app = call_factory(self, self.create_app)370 else:371 if self.app_import_path:380- path, name = (re.split(r':(?![\\/])', self.app_import_path, 1) + [None])[:2]372+ path, name = (373+ re.split(r":(?![\\/])", self.app_import_path, 1) + [None]374+ )[:2]375 import_name = prepare_import(path)376 app = locate_app(self, import_name, name)377 else:384- for path in ('wsgi.py', 'app.py'):378+ for path in ("wsgi.py", "app.py"):379 import_name = prepare_import(path)386- app = locate_app(self, import_name, None,387- raise_if_not_found=False)380+ app = locate_app(self, import_name, None, raise_if_not_found=False)381 382 if app:383 break384 385 if not app:386 raise NoAppException(394- 'Could not locate a Flask application. You did not provide '387+ "Could not locate a Flask application. You did not provide "388 'the "FLASK_APP" environment variable, and a "wsgi.py" or '389 '"app.py" module was not found in the current directory.'390 )391 14 unmodified lines406 script's application context. If callbacks are registered directly407 to the ``app.cli`` object then they are wrapped with this function408 by default unless it's disabled.409 """410+411 @click.pass_context412 def decorator(__ctx, *args, **kwargs):413 with __ctx.ensure_object(ScriptInfo).load_app().app_context():414 return __ctx.invoke(f, *args, **kwargs)415+416 return update_wrapper(decorator, f)417 418 419 class AppGroup(click.Group):8 unmodified lines428 """This works exactly like the method of the same name on a regular429 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`430 unless it's disabled by passing ``with_appcontext=False``.431 """437- wrap_for_ctx = kwargs.pop('with_appcontext', True)432+ wrap_for_ctx = kwargs.pop("with_appcontext", True)433+434 def decorator(f):435 if wrap_for_ctx:436 f = with_appcontext(f)437 return click.Group.command(self, *args, **kwargs)(f)438+439 return decorator440 441 def group(self, *args, **kwargs):442 """This works exactly like the method of the same name on a regular443 :class:`click.Group` but it defaults the group class to444 :class:`AppGroup`.445 """449- kwargs.setdefault('cls', AppGroup)446+ kwargs.setdefault("cls", AppGroup)447 return click.Group.group(self, *args, **kwargs)448 449 450 class FlaskGroup(AppGroup):20 unmodified lines471 If installed, python-dotenv will be used to load environment variables472 from :file:`.env` and :file:`.flaskenv` files.473 """474 478- def __init__(self, add_default_commands=True, create_app=None,479- add_version_option=True, load_dotenv=True,480- set_debug_flag=True, **extra):481- params = list(extra.pop('params', None) or ())475+ def __init__(476+ self,477+ add_default_commands=True,478+ create_app=None,479+ add_version_option=True,480+ load_dotenv=True,481+ set_debug_flag=True,482+ **extra483+ ):484+ params = list(extra.pop("params", None) or ())485 486 if add_version_option:487 params.append(version_option)488 17 unmodified lines506 except ImportError:507 self._loaded_plugin_commands = True508 return509 507- for ep in pkg_resources.iter_entry_points('flask.commands'):510+ for ep in pkg_resources.iter_entry_points("flask.commands"):511 self.add_command(ep.load(), ep.name)512 self._loaded_plugin_commands = True513 514 def get_command(self, ctx, name):41 unmodified lines556 # Set a global flag that indicates that we were invoked from the557 # command line interface. This is detected by Flask.run to make the558 # call into a no-op. This is necessary to avoid ugly errors when the559 # script that is loaded here also attempts to start a server.557- os.environ['FLASK_RUN_FROM_CLI'] = 'true'560+ os.environ["FLASK_RUN_FROM_CLI"] = "true"561 562 if get_load_dotenv(self.load_dotenv):563 load_dotenv()564 562- obj = kwargs.get('obj')565+ obj = kwargs.get("obj")566 567 if obj is None:565- obj = ScriptInfo(create_app=self.create_app,566- set_debug_flag=self.set_debug_flag)568+ obj = ScriptInfo(569+ create_app=self.create_app, set_debug_flag=self.set_debug_flag570+ )571 568- kwargs['obj'] = obj569- kwargs.setdefault('auto_envvar_prefix', 'FLASK')572+ kwargs["obj"] = obj573+ kwargs.setdefault("auto_envvar_prefix", "FLASK")574 return super(FlaskGroup, self).main(*args, **kwargs)575 576 577 def _path_is_ancestor(path, other):578 """Take ``other`` and remove the length of ``path`` from it. Then join it579 to ``path``. If it is the original value, ``path`` is an ancestor of580 ``other``."""577- return os.path.join(path, other[len(path):].lstrip(os.sep)) == other581+ return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other582 583 584 def load_dotenv(path=None):585 """Load "dotenv" files in order of precedence to set environment variables.14 unmodified lines600 601 .. versionadded:: 1.0602 """603 if dotenv is None:600- if path or os.path.isfile('.env') or os.path.isfile('.flaskenv'):604+ if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):605 click.secho(602- ' * Tip: There are .env or .flaskenv files present.'606+ " * Tip: There are .env or .flaskenv files present."607 ' Do "pip install python-dotenv" to use them.',604- fg='yellow')608+ fg="yellow",609+ )610 return611 612 if path is not None:613 return dotenv.load_dotenv(path)614 615 new_dir = None616 612- for name in ('.env', '.flaskenv'):617+ for name in (".env", ".flaskenv"):618 path = dotenv.find_dotenv(name, usecwd=True)619 620 if not path:621 continue12 unmodified lines634 def show_server_banner(env, debug, app_import_path, eager_loading):635 """Show extra startup messages the first time the server is run,636 ignoring the reloader.637 """633- if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':638+ if os.environ.get("WERKZEUG_RUN_MAIN") == "true":639 return640 641 if app_import_path is not None:642 message = ' * Serving Flask app "{0}"'.format(app_import_path)643 644 if not eager_loading:640- message += ' (lazy loading)'645+ message += " (lazy loading)"646 647 click.echo(message)648 644- click.echo(' * Environment: {0}'.format(env))649+ click.echo(" * Environment: {0}".format(env))650 646- if env == 'production':651+ if env == "production":652 click.secho(648- ' WARNING: Do not use the development server in a production'649- ' environment.', fg='red')650- click.secho(' Use a production WSGI server instead.', dim=True)653+ " WARNING: Do not use the development server in a production"654+ " environment.",655+ fg="red",656+ )657+ click.secho(" Use a production WSGI server instead.", dim=True)658 659 if debug is not None:653- click.echo(' * Debug mode: {0}'.format('on' if debug else 'off'))660+ click.echo(" * Debug mode: {0}".format("on" if debug else "off"))661 662 663 class CertParamType(click.ParamType):664 """Click option type for the ``--cert`` option. Allows either an665 existing file, the string ``'adhoc'``, or an import for a666 :class:`~ssl.SSLContext` object.667 """668 662- name = 'path'669+ name = "path"670 671 def __init__(self):665- self.path_type = click.Path(666- exists=True, dir_okay=False, resolve_path=True)672+ self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)673 674 def convert(self, value, param, ctx):675 try:676 return self.path_type(value, param, ctx)677 except click.BadParameter:678 value = click.STRING(value, param, ctx).lower()679 674- if value == 'adhoc':680+ if value == "adhoc":681 try:682 import OpenSSL683 except ImportError:684 raise click.BadParameter(679- 'Using ad-hoc certificates requires pyOpenSSL.',680- ctx, param)685+ "Using ad-hoc certificates requires pyOpenSSL.", ctx, param686+ )687 688 return value689 690 obj = import_string(value, silent=True)11 unmodified lines702 def _validate_key(ctx, param, value):703 """The ``--key`` option must be specified when ``--cert`` is a file.704 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.705 """700- cert = ctx.params.get('cert')701- is_adhoc = cert == 'adhoc'706+ cert = ctx.params.get("cert")707+ is_adhoc = cert == "adhoc"708 709 if sys.version_info < (2, 7, 9):710 is_context = cert and not isinstance(cert, (text_type, bytes))711 else:1 unmodified line713 714 if value is not None:715 if is_adhoc:716 raise click.BadParameter(711- 'When "--cert" is "adhoc", "--key" is not used.',712- ctx, param)717+ 'When "--cert" is "adhoc", "--key" is not used.', ctx, param718+ )719 720 if is_context:721 raise click.BadParameter(716- 'When "--cert" is an SSLContext object, "--key is not used.',717- ctx, param)722+ 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param723+ )724 725 if not cert:720- raise click.BadParameter(721- '"--cert" must also be specified.',722- ctx, param)726+ raise click.BadParameter('"--cert" must also be specified.', ctx, param)727 724- ctx.params['cert'] = cert, value728+ ctx.params["cert"] = cert, value729 730 else:731 if cert and not (is_adhoc or is_context):728- raise click.BadParameter(729- 'Required when using "--cert".',730- ctx, param)732+ raise click.BadParameter('Required when using "--cert".', ctx, param)733 734 return value735 736 735-@click.command('run', short_help='Run a development server.')736-@click.option('--host', '-h', default='127.0.0.1',737- help='The interface to bind to.')738-@click.option('--port', '-p', default=5000,739- help='The port to bind to.')740-@click.option('--cert', type=CertParamType(),741- help='Specify a certificate file to use HTTPS.')742-@click.option('--key',743- type=click.Path(exists=True, dir_okay=False, resolve_path=True),744- callback=_validate_key, expose_value=False,745- help='The key file to use when specifying a certificate.')746-@click.option('--reload/--no-reload', default=None,747- help='Enable or disable the reloader. By default the reloader '748- 'is active if debug is enabled.')749-@click.option('--debugger/--no-debugger', default=None,750- help='Enable or disable the debugger. By default the debugger '751- 'is active if debug is enabled.')752-@click.option('--eager-loading/--lazy-loader', default=None,753- help='Enable or disable eager loading. By default eager '754- 'loading is enabled if the reloader is disabled.')755-@click.option('--with-threads/--without-threads', default=True,756- help='Enable or disable multithreading.')737+@click.command("run", short_help="Run a development server.")738+@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")739+@click.option("--port", "-p", default=5000, help="The port to bind to.")740+@click.option(741+ "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."742+)743+@click.option(744+ "--key",745+ type=click.Path(exists=True, dir_okay=False, resolve_path=True),746+ callback=_validate_key,747+ expose_value=False,748+ help="The key file to use when specifying a certificate.",749+)750+@click.option(751+ "--reload/--no-reload",752+ default=None,753+ help="Enable or disable the reloader. By default the reloader "754+ "is active if debug is enabled.",755+)756+@click.option(757+ "--debugger/--no-debugger",758+ default=None,759+ help="Enable or disable the debugger. By default the debugger "760+ "is active if debug is enabled.",761+)762+@click.option(763+ "--eager-loading/--lazy-loader",764+ default=None,765+ help="Enable or disable eager loading. By default eager "766+ "loading is enabled if the reloader is disabled.",767+)768+@click.option(769+ "--with-threads/--without-threads",770+ default=True,771+ help="Enable or disable multithreading.",772+)773 @pass_script_info758-def run_command(info, host, port, reload, debugger, eager_loading,759- with_threads, cert):774+def run_command(info, host, port, reload, debugger, eager_loading, with_threads, cert):775 """Run a local development server.776 777 This server is for development purposes only. It does not provide778 the stability, security, or performance of production WSGI servers.15 unmodified lines794 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)795 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)796 797 from werkzeug.serving import run_simple783- run_simple(host, port, app, use_reloader=reload, use_debugger=debugger,784- threaded=with_threads, ssl_context=cert)798 799+ run_simple(800+ host,801+ port,802+ app,803+ use_reloader=reload,804+ use_debugger=debugger,805+ threaded=with_threads,806+ ssl_context=cert,807+ )808 787-@click.command('shell', short_help='Run a shell in the app context.')809+810+@click.command("shell", short_help="Run a shell in the app context.")811 @with_appcontext812 def shell_command():813 """Run an interactive Python shell in the context of a given814 Flask application. The application will populate the default3 unmodified lines818 without having to manually configure the application.819 """820 import code821 from flask.globals import _app_ctx_stack822+823 app = _app_ctx_stack.top.app800- banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % (824+ banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (825 sys.version,826 sys.platform,827 app.import_name,828 app.env,2 unmodified lines831 ctx = {}832 833 # Support the regular Python interpreter startup script if someone834 # is using it.811- startup = os.environ.get('PYTHONSTARTUP')835+ startup = os.environ.get("PYTHONSTARTUP")836 if startup and os.path.isfile(startup):813- with open(startup, 'r') as f:814- eval(compile(f.read(), startup, 'exec'), ctx)837+ with open(startup, "r") as f:838+ eval(compile(f.read(), startup, "exec"), ctx)839 840 ctx.update(app.make_shell_context())841 842 code.interact(banner=banner, local=ctx)843 844 821-@click.command('routes', short_help='Show the routes for the app.')845+@click.command("routes", short_help="Show the routes for the app.")846 @click.option(823- '--sort', '-s',824- type=click.Choice(('endpoint', 'methods', 'rule', 'match')),825- default='endpoint',847+ "--sort",848+ "-s",849+ type=click.Choice(("endpoint", "methods", "rule", "match")),850+ default="endpoint",851 help=(852 'Method to sort routes by. "match" is the order that Flask will match '828- 'routes when dispatching a request.'829- )853+ "routes when dispatching a request."854+ ),855 )831-@click.option(832- '--all-methods',833- is_flag=True,834- help="Show HEAD and OPTIONS methods."835-)856+@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")857 @with_appcontext858 def routes_command(sort, all_methods):859 """Show all registered routes with endpoints and methods."""860 861 rules = list(current_app.url_map.iter_rules())862 if not rules:842- click.echo('No routes were registered.')863+ click.echo("No routes were registered.")864 return865 845- ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))866+ ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))867 847- if sort in ('endpoint', 'rule'):868+ if sort in ("endpoint", "rule"):869 rules = sorted(rules, key=attrgetter(sort))849- elif sort == 'methods':870+ elif sort == "methods":871 rules = sorted(rules, key=lambda rule: sorted(rule.methods))872 852- rule_methods = [853- ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules854- ]873+ rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules]874 856- headers = ('Endpoint', 'Methods', 'Rule')875+ headers = ("Endpoint", "Methods", "Rule")876 widths = (877 max(len(rule.endpoint) for rule in rules),878 max(len(methods) for methods in rule_methods),879 max(len(rule.rule) for rule in rules),880 )881 widths = [max(len(h), w) for h, w in zip(headers, widths)]863- row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)882+ row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)883 884 click.echo(row.format(*headers).strip())866- click.echo(row.format(*('-' * width for width in widths)))885+ click.echo(row.format(*("-" * width for width in widths)))886 887 for rule, methods in zip(rules, rule_methods):888 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())889 890 872-cli = FlaskGroup(help="""\891+cli = FlaskGroup(892+ help="""\893 A general utility script for Flask applications.894 895 Provides commands from Flask, extensions, and the application. Loads the896 application defined in the FLASK_APP environment variable, or from a wsgi.py4 unmodified lines901 {prefix}{cmd} FLASK_APP=hello.py902 {prefix}{cmd} FLASK_ENV=development903 {prefix}flask run904 """.format(885- cmd='export' if os.name == 'posix' else 'set',886- prefix='$ ' if os.name == 'posix' else '> '887-))905+ cmd="export" if os.name == "posix" else "set",906+ prefix="$ " if os.name == "posix" else "> ",907+ )908+)909 910 911 def main(as_module=False):912 args = sys.argv[1:]913 914 if as_module:894- this_module = 'flask'915+ this_module = "flask"916 917 if sys.version_info < (2, 7):897- this_module += '.cli'918+ this_module += ".cli"919 899- name = 'python -m ' + this_module920+ name = "python -m " + this_module921 922 # Python rewrites "python -m flask" to the path to the file in argv.923 # Restore the original command so that the reloader works.903- sys.argv = ['-m', this_module] + args924+ sys.argv = ["-m", this_module] + args925 else:926 name = None927 928 cli.main(args=args, prog_name=name)929 930 910-if __name__ == '__main__':931+if __name__ == "__main__":932 main(as_module=True)modified:flask/config.py+16 added-17 removed
99 unmodified lines100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:103 return False104- raise RuntimeError('The environment variable %r is not set '105- 'and as such configuration could not be '106- 'loaded. Set this variable and make it '107- 'point to a configuration file' %108- variable_name)104+ raise RuntimeError(105+ "The environment variable %r is not set "106+ "and as such configuration could not be "107+ "loaded. Set this variable and make it "108+ "point to a configuration file" % variable_name109+ )110 return self.from_pyfile(rv, silent=silent)111 112 def from_pyfile(self, filename, silent=False):113 """Updates the values in the config from a Python file. This function9 unmodified lines123 .. versionadded:: 0.7124 `silent` parameter.125 """126 filename = os.path.join(self.root_path, filename)126- d = types.ModuleType('config')127+ d = types.ModuleType("config")128 d.__file__ = filename129 try:129- with open(filename, mode='rb') as config_file:130- exec(compile(config_file.read(), filename, 'exec'), d.__dict__)130+ with open(filename, mode="rb") as config_file:131+ exec(compile(config_file.read(), filename, "exec"), d.__dict__)132 except IOError as e:132- if silent and e.errno in (133- errno.ENOENT, errno.EISDIR, errno.ENOTDIR134- ):133+ if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):134 return False136- e.strerror = 'Unable to load configuration file (%s)' % e.strerror135+ e.strerror = "Unable to load configuration file (%s)" % e.strerror136 raise137 self.from_object(d)138 return True139 55 unmodified lines195 obj = json.loads(json_file.read())196 except IOError as e:197 if silent and e.errno in (errno.ENOENT, errno.EISDIR):198 return False200- e.strerror = 'Unable to load configuration file (%s)' % e.strerror199+ e.strerror = "Unable to load configuration file (%s)" % e.strerror200 raise201 return self.from_mapping(obj)202 203 def from_mapping(self, *mapping, **kwargs):3 unmodified lines207 .. versionadded:: 0.11208 """209 mappings = []210 if len(mapping) == 1:212- if hasattr(mapping[0], 'items'):211+ if hasattr(mapping[0], "items"):212 mappings.append(mapping[0].items())213 else:214 mappings.append(mapping[0])215 elif len(mapping) > 1:216 raise TypeError(218- 'expected at most 1 positional argument, got %d' % len(mapping)217+ "expected at most 1 positional argument, got %d" % len(mapping)218 )219 mappings.append(kwargs.items())220 for mapping in mappings:221 for (key, value) in mapping:33 unmodified lines255 for k, v in iteritems(self):256 if not k.startswith(namespace):257 continue258 if trim_namespace:260- key = k[len(namespace):]259+ key = k[len(namespace) :]260 else:261 key = k262 if lowercase:263 key = key.lower()264 rv[key] = v265 return rv266 267 def __repr__(self):269- return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))268+ return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))modified:flask/ctx.py+28 added-23 removed
87 unmodified lines88 89 def __repr__(self):90 top = _app_ctx_stack.top91 if top is not None:92- return '<flask.g of %r>' % top.app.name92+ return "<flask.g of %r>" % top.app.name93 return object.__repr__(self)94 95 96 def after_this_request(f):46 unmodified lines143 .. versionadded:: 0.10144 """145 top = _request_ctx_stack.top146 if top is None:147- raise RuntimeError('This decorator can only be used at local scopes '148- 'when a request context is on the stack. For instance within '149- 'view functions.')147+ raise RuntimeError(148+ "This decorator can only be used at local scopes "149+ "when a request context is on the stack. For instance within "150+ "view functions."151+ )152 reqctx = top.copy()153+154 def wrapper(*args, **kwargs):155 with reqctx:156 return f(*args, **kwargs)157+158 return update_wrapper(wrapper, f)159 160 161 def has_request_context():58 unmodified lines220 221 def push(self):222 """Binds the app context to the current context."""223 self._refcnt += 1220- if hasattr(sys, 'exc_clear'):224+ if hasattr(sys, "exc_clear"):225 sys.exc_clear()226 _app_ctx_stack.push(self)227 appcontext_pushed.send(self.app)228 6 unmodified lines235 exc = sys.exc_info()[1]236 self.app.do_teardown_appcontext(exc)237 finally:238 rv = _app_ctx_stack.pop()235- assert rv is self, 'Popped wrong app context. (%r instead of %r)' \236- % (rv, self)239+ assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)240 appcontext_popped.send(self.app)241 242 def __enter__(self):243 self.push()72 unmodified lines316 self.match_request()317 318 def _get_g(self):319 return _app_ctx_stack.top.g320+321 def _set_g(self, value):322 _app_ctx_stack.top.g = value323+324 g = property(_get_g, _set_g)325 del _get_g, _set_g326 327 def copy(self):8 unmodified lines336 .. versionchanged:: 1.1337 The current session object is used instead of reloading the original338 data. This prevents `flask.session` pointing to an out-of-date object.339 """335- return self.__class__(self.app,340+ return self.__class__(341+ self.app,342 environ=self.request.environ,343 request=self.request,338- session=self.session344+ session=self.session,345 )346 347 def match_request(self):348 """Can be overridden by a subclass to hook into the matching349 of the request.350 """351 try:346- url_rule, self.request.view_args = \347- self.url_adapter.match(return_rule=True)352+ url_rule, self.request.view_args = self.url_adapter.match(return_rule=True)353 self.request.url_rule = url_rule354 except HTTPException as e:355 self.request.routing_exception = e356 20 unmodified lines377 self._implicit_app_ctx_stack.append(app_ctx)378 else:379 self._implicit_app_ctx_stack.append(None)380 376- if hasattr(sys, 'exc_clear'):381+ if hasattr(sys, "exc_clear"):382 sys.exc_clear()383 384 _request_ctx_stack.push(self)385 2 unmodified lines388 # Only open a new session if this is the first time the request was389 # pushed, otherwise stream_with_context loses the session.390 if self.session is None:391 session_interface = self.app.session_interface387- self.session = session_interface.open_session(388- self.app, self.request389- )392+ self.session = session_interface.open_session(self.app, self.request)393 394 if self.session is None:395 self.session = session_interface.make_null_session(self.app)396 19 unmodified lines416 # If this interpreter supports clearing the exception information417 # we do that now. This will only go into effect on Python 2.x,418 # on 3.x it disappears automatically at the end of the exception419 # stack.417- if hasattr(sys, 'exc_clear'):420+ if hasattr(sys, "exc_clear"):421 sys.exc_clear()422 420- request_close = getattr(self.request, 'close', None)423+ request_close = getattr(self.request, "close", None)424 if request_close is not None:425 request_close()426 clear_request = True427 finally:1 unmodified line429 430 # get rid of circular dependencies at the end of the request431 # so that we don't require the GC to be active.432 if clear_request:430- rv.request.environ['werkzeug.request'] = None433+ rv.request.environ["werkzeug.request"] = None434 435 # Get rid of the app as well if necessary.436 if app_ctx is not None:437 app_ctx.pop(exc)438 436- assert rv is self, 'Popped wrong request context. ' \437- '(%r instead of %r)' % (rv, self)439+ assert (440+ rv is self441+ ), "Popped wrong request context. " "(%r instead of %r)" % (rv, self)442 443 def auto_pop(self, exc):440- if self.request.environ.get('flask._preserve_context') or \441- (exc is not None and self.app.preserve_context_on_exception):444+ if self.request.environ.get("flask._preserve_context") or (445+ exc is not None and self.app.preserve_context_on_exception446+ ):447 self.preserved = True448 self._preserved_exc = exc449 else:450 self.pop(exc)13 unmodified lines464 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:465 reraise(exc_type, exc_value, tb)466 467 def __repr__(self):463- return '<%s \'%s\' [%s] of %s>' % (468+ return "<%s '%s' [%s] of %s>" % (469 self.__class__.__name__,470 self.request.url,471 self.request.method,472 self.app.name,1 unmodified linemodified:flask/debughelpers.py+65 added-50 removed
30 unmodified lines31 """32 33 def __init__(self, request, key):34 form_matches = request.form.getlist(key)35- buf = ['You tried to access the file "%s" in the request.files '36- 'dictionary but it does not exist. The mimetype for the request '37- 'is "%s" instead of "multipart/form-data" which means that no '38- 'file contents were transmitted. To fix this error you should '39- 'provide enctype="multipart/form-data" in your form.' %40- (key, request.mimetype)]35+ buf = [36+ 'You tried to access the file "%s" in the request.files '37+ "dictionary but it does not exist. The mimetype for the request "38+ 'is "%s" instead of "multipart/form-data" which means that no '39+ "file contents were transmitted. To fix this error you should "40+ 'provide enctype="multipart/form-data" in your form.'41+ % (key, request.mimetype)42+ ]43 if form_matches:42- buf.append('\n\nThe browser instead transmitted some file names. '43- 'This was submitted: %s' % ', '.join('"%s"' % x44- for x in form_matches))45- self.msg = ''.join(buf)44+ buf.append(45+ "\n\nThe browser instead transmitted some file names. "46+ "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)47+ )48+ self.msg = "".join(buf)49 50 def __str__(self):51 return self.msg52 5 unmodified lines58 """59 60 def __init__(self, request):61 exc = request.routing_exception62+ buf = [59- buf = ['A request was sent to this URL (%s) but a redirect was '60- 'issued automatically by the routing system to "%s".'61- % (request.url, exc.new_url)]63+ "A request was sent to this URL (%s) but a redirect was "64+ 'issued automatically by the routing system to "%s".'65+ % (request.url, exc.new_url)66+ ]67 68 # In case just a slash was appended we can be extra helpful64- if request.base_url + '/' == exc.new_url.split('?')[0]:65- buf.append(' The URL was defined with a trailing slash so '66- 'Flask will automatically redirect to the URL '67- 'with the trailing slash if it was accessed '68- 'without one.')69+ if request.base_url + "/" == exc.new_url.split("?")[0]:70+ buf.append(71+ " The URL was defined with a trailing slash so "72+ "Flask will automatically redirect to the URL "73+ "with the trailing slash if it was accessed "74+ "without one."75+ )76 70- buf.append(' Make sure to directly send your %s-request to this URL '71- 'since we can\'t make browsers or HTTP clients redirect '72- 'with form data reliably or without user interaction.' %73- request.method)74- buf.append('\n\nNote: this exception is only raised in debug mode')75- AssertionError.__init__(self, ''.join(buf).encode('utf-8'))77+ buf.append(78+ " Make sure to directly send your %s-request to this URL "79+ "since we can't make browsers or HTTP clients redirect "80+ "with form data reliably or without user interaction." % request.method81+ )82+ buf.append("\n\nNote: this exception is only raised in debug mode")83+ AssertionError.__init__(self, "".join(buf).encode("utf-8"))84 85 86 def attach_enctype_error_multidict(request):87 """Since Flask 0.8 we're monkeypatching the files object in case a88 request is detected that does not use multipart form data but the files89 object is accessed.90 """91 oldcls = request.files.__class__92+93 class newcls(oldcls):94 def __getitem__(self, key):95 try:96 return oldcls.__getitem__(self, key)97 except KeyError:98 if key not in request.form:99 raise100 raise DebugFilesKeyError(request, key)101+102 newcls.__name__ = oldcls.__name__103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls105 106 107 def _dump_loader_info(loader):98- yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__)108+ yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)109 for key, value in sorted(loader.__dict__.items()):100- if key.startswith('_'):110+ if key.startswith("_"):111 continue112 if isinstance(value, (tuple, list)):113 if not all(isinstance(x, (str, text_type)) for x in value):114 continue105- yield '%s:' % key115+ yield "%s:" % key116 for item in value:107- yield ' - %s' % item117+ yield " - %s" % item118 continue119 elif not isinstance(value, (str, text_type, int, float, bool)):120 continue111- yield '%s: %r' % (key, value)121+ yield "%s: %r" % (key, value)122 123 124 def explain_template_loading_attempts(app, template, attempts):125 """This should help developers understand what failed"""7 unmodified lines133 for idx, (loader, srcobj, triple) in enumerate(attempts):134 if isinstance(srcobj, Flask):135 src_info = 'application "%s"' % srcobj.import_name136 elif isinstance(srcobj, Blueprint):127- src_info = 'blueprint "%s" (%s)' % (srcobj.name,128- srcobj.import_name)137+ src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)138 else:139 src_info = repr(srcobj)140 132- info.append('% 5d: trying loader of %s' % (133- idx + 1, src_info))141+ info.append("% 5d: trying loader of %s" % (idx + 1, src_info))142 143 for line in _dump_loader_info(loader):136- info.append(' %s' % line)144+ info.append(" %s" % line)145 146 if triple is None:139- detail = 'no match'147+ detail = "no match"148 else:141- detail = 'found (%r)' % (triple[1] or '<string>')149+ detail = "found (%r)" % (triple[1] or "<string>")150 total_found += 1143- info.append(' -> %s' % detail)151+ info.append(" -> %s" % detail)152 153 seems_fishy = False154 if total_found == 0:147- info.append('Error: the template could not be found.')155+ info.append("Error: the template could not be found.")156 seems_fishy = True157 elif total_found > 1:150- info.append('Warning: multiple loaders returned a match for the template.')158+ info.append("Warning: multiple loaders returned a match for the template.")159 seems_fishy = True160 161 if blueprint is not None and seems_fishy:154- info.append(' The template was looked up from an endpoint that '155- 'belongs to the blueprint "%s".' % blueprint)156- info.append(' Maybe you did not place a template in the right folder?')157- info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')162+ info.append(163+ " The template was looked up from an endpoint that "164+ 'belongs to the blueprint "%s".' % blueprint165+ )166+ info.append(" Maybe you did not place a template in the right folder?")167+ info.append(" See http://flask.pocoo.org/docs/blueprints/#templates")168 159- app.logger.info('\n'.join(info))169+ app.logger.info("\n".join(info))170 171 172 def explain_ignored_app_run():163- if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':164- warn(Warning('Silently ignoring app.run() because the '165- 'application is run from the flask command line '166- 'executable. Consider putting app.run() behind an '167- 'if __name__ == "__main__" guard to silence this '168- 'warning.'), stacklevel=3)173+ if os.environ.get("WERKZEUG_RUN_MAIN") != "true":174+ warn(175+ Warning(176+ "Silently ignoring app.run() because the "177+ "application is run from the flask command line "178+ "executable. Consider putting app.run() behind an "179+ 'if __name__ == "__main__" guard to silence this '180+ "warning."181+ ),182+ stacklevel=3,183+ )modified:flask/globals.py+7 added-7 removed
12 unmodified lines13 from functools import partial14 from werkzeug.local import LocalStack, LocalProxy15 16 17-_request_ctx_err_msg = '''\17+_request_ctx_err_msg = """\18 Working outside of request context.19 20 This typically means that you attempted to use functionality that needed21 an active HTTP request. Consult the documentation on testing for22 information about how to avoid this problem.\23-'''24-_app_ctx_err_msg = '''\23+"""24+_app_ctx_err_msg = """\25 Working outside of application context.26 27 This typically means that you attempted to use functionality that needed28 to interface with the current application object in some way. To solve29 this, set up an application context with app.app_context(). See the30 documentation for more information.\31-'''31+"""32 33 34 def _lookup_req_object(name):35 top = _request_ctx_stack.top19 unmodified lines55 # context locals56 _request_ctx_stack = LocalStack()57 _app_ctx_stack = LocalStack()58 current_app = LocalProxy(_find_app)59-request = LocalProxy(partial(_lookup_req_object, 'request'))60-session = LocalProxy(partial(_lookup_req_object, 'session'))61-g = LocalProxy(partial(_lookup_app_object, 'g'))59+request = LocalProxy(partial(_lookup_req_object, "request"))60+session = LocalProxy(partial(_lookup_req_object, "session"))61+g = LocalProxy(partial(_lookup_app_object, "g"))modified:flask/helpers.py+160 added-129 removed
22 unmodified lines23 from functools import update_wrapper24 25 from werkzeug.urls import url_quote26 from werkzeug.datastructures import Headers, Range27-from werkzeug.exceptions import BadRequest, NotFound, \28- RequestedRangeNotSatisfiable27+from werkzeug.exceptions import BadRequest, NotFound, RequestedRangeNotSatisfiable28 29 from werkzeug.wsgi import wrap_file30 from jinja2 import FileSystemLoader31 32 from .signals import message_flashed34-from .globals import session, _request_ctx_stack, _app_ctx_stack, \35- current_app, request33+from .globals import session, _request_ctx_stack, _app_ctx_stack, current_app, request34 from ._compat import string_types, text_type, PY2, fspath35 36 # sentinel37 _missing = object()1 unmodified line39 40 # what separators does this operating system provide that are not a slash?41 # this is used by the send_from_directory function to ensure that nobody is42 # able to access files from outside the filesystem.45-_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]46- if sep not in (None, '/'))43+_os_alt_seps = list(44+ sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, "/")45+)46 47 48 def get_env():49 """Get the environment the app is running in, indicated by the50 :envvar:`FLASK_ENV` environment variable. The default is51 ``'production'``.52 """54- return os.environ.get('FLASK_ENV') or 'production'53+ return os.environ.get("FLASK_ENV") or "production"54 55 56 def get_debug_flag():57 """Get whether debug mode should be enabled for the app, indicated58 by the :envvar:`FLASK_DEBUG` environment variable. The default is59 ``True`` if :func:`.get_env` returns ``'development'``, or ``False``60 otherwise.61 """63- val = os.environ.get('FLASK_DEBUG')62+ val = os.environ.get("FLASK_DEBUG")63 64 if not val:66- return get_env() == 'development'65+ return get_env() == "development"66 68- return val.lower() not in ('0', 'false', 'no')67+ return val.lower() not in ("0", "false", "no")68 69 70 def get_load_dotenv(default=True):71 """Get whether the user has disabled loading dotenv files by setting1 unmodified line73 files.74 75 :param default: What to return if the env var isn't set.76 """78- val = os.environ.get('FLASK_SKIP_DOTENV')77+ val = os.environ.get("FLASK_SKIP_DOTENV")78 79 if not val:80 return default81 83- return val.lower() in ('0', 'false', 'no')82+ return val.lower() in ("0", "false", "no")83 84 85 def _endpoint_from_view_func(view_func):86 """Internal helper that returns the default endpoint for a given87 function. This always is the function name.88 """90- assert view_func is not None, 'expected view func if endpoint ' \91- 'is not provided.'89+ assert view_func is not None, "expected view func if endpoint " "is not provided."90 return view_func.__name__91 92 93 def stream_with_context(generator_or_function):32 unmodified lines126 """127 try:128 gen = iter(generator_or_function)129 except TypeError:130+131 def decorator(*args, **kwargs):132 gen = generator_or_function(*args, **kwargs)133 return stream_with_context(gen)134+135 return update_wrapper(decorator, generator_or_function)136 137 def generator():138 ctx = _request_ctx_stack.top139 if ctx is None:140- raise RuntimeError('Attempted to stream with context but '141- 'there was no context in the first place to keep around.')140+ raise RuntimeError(141+ "Attempted to stream with context but "142+ "there was no context in the first place to keep around."143+ )144 with ctx:145 # Dummy sentinel. Has to be inside the context block or we're146 # not actually keeping the context around.147 yield None5 unmodified lines153 try:154 for item in gen:155 yield item156 finally:155- if hasattr(gen, 'close'):157+ if hasattr(gen, "close"):158 gen.close()159 160 # The trick is to start the generator. Then the code execution runs until161 # the first dummy None is yielded at which point the context was already130 unmodified lines292 reqctx = _request_ctx_stack.top293 294 if appctx is None:295 raise RuntimeError(294- 'Attempted to generate a URL without the application context being'295- ' pushed. This has to be executed when application context is'296- ' available.'296+ "Attempted to generate a URL without the application context being"297+ " pushed. This has to be executed when application context is"298+ " available."299 )300 301 # If request specific information is available we have some extra302 # features that support "relative" URLs.303 if reqctx is not None:304 url_adapter = reqctx.url_adapter305 blueprint_name = request.blueprint306 305- if endpoint[:1] == '.':307+ if endpoint[:1] == ".":308 if blueprint_name is not None:309 endpoint = blueprint_name + endpoint310 else:311 endpoint = endpoint[1:]312 311- external = values.pop('_external', False)313+ external = values.pop("_external", False)314 315 # Otherwise go with the url adapter from the appctx and make316 # the URLs external by default.317 else:318 url_adapter = appctx.url_adapter319 320 if url_adapter is None:321 raise RuntimeError(320- 'Application was not able to create a URL adapter for request'321- ' independent URL generation. You might be able to fix this by'322- ' setting the SERVER_NAME config variable.'322+ "Application was not able to create a URL adapter for request"323+ " independent URL generation. You might be able to fix this by"324+ " setting the SERVER_NAME config variable."325 )326 325- external = values.pop('_external', True)327+ external = values.pop("_external", True)328 327- anchor = values.pop('_anchor', None)328- method = values.pop('_method', None)329- scheme = values.pop('_scheme', None)329+ anchor = values.pop("_anchor", None)330+ method = values.pop("_method", None)331+ scheme = values.pop("_scheme", None)332 appctx.app.inject_url_defaults(endpoint, values)333 334 # This is not the best way to deal with this but currently the335 # underlying Werkzeug router does not support overriding the scheme on336 # a per build call basis.337 old_scheme = None338 if scheme is not None:339 if not external:338- raise ValueError('When specifying _scheme, _external must be True')340+ raise ValueError("When specifying _scheme, _external must be True")341 old_scheme = url_adapter.url_scheme342 url_adapter.url_scheme = scheme343 344 try:345 try:344- rv = url_adapter.build(endpoint, values, method=method,345- force_external=external)346+ rv = url_adapter.build(347+ endpoint, values, method=method, force_external=external348+ )349 finally:350 if old_scheme is not None:351 url_adapter.url_scheme = old_scheme352 except BuildError as error:353 # We need to inject the values again so that the app callback can354 # deal with that sort of stuff.352- values['_external'] = external353- values['_anchor'] = anchor354- values['_method'] = method355- values['_scheme'] = scheme355+ values["_external"] = external356+ values["_anchor"] = anchor357+ values["_method"] = method358+ values["_scheme"] = scheme359 return appctx.app.handle_url_build_error(error, endpoint, values)360 361 if anchor is not None:359- rv += '#' + url_quote(anchor)362+ rv += "#" + url_quote(anchor)363 return rv364 365 366 def get_template_attribute(template_name, attribute):14 unmodified lines381 382 :param template_name: the name of the template383 :param attribute: the name of the variable of macro to access384 """382- return getattr(current_app.jinja_env.get_template(template_name).module,383- attribute)385+ return getattr(current_app.jinja_env.get_template(template_name).module, attribute)386 387 386-def flash(message, category='message'):388+def flash(message, category="message"):389 """Flashes a message to the next request. In order to remove the390 flashed message from the session and to display it to the user,391 the template has to call :func:`get_flashed_messages`.392 13 unmodified lines406 #407 # This assumed that changes made to mutable structures in the session are408 # always in sync with the session object, which is not true for session409 # implementations that use external storage for keeping their keys/values.408- flashes = session.get('_flashes', [])410+ flashes = session.get("_flashes", [])411 flashes.append((category, message))410- session['_flashes'] = flashes411- message_flashed.send(current_app._get_current_object(),412- message=message, category=category)412+ session["_flashes"] = flashes413+ message_flashed.send(414+ current_app._get_current_object(), message=message, category=category415+ )416 417 418 def get_flashed_messages(with_categories=False, category_filter=[]):419 """Pulls all flashed messages from the session and returns them.24 unmodified lines444 :param category_filter: whitelist of categories to limit return values445 """446 flashes = _request_ctx_stack.top.flashes447 if flashes is None:445- _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \446- if '_flashes' in session else []448+ _request_ctx_stack.top.flashes = flashes = (449+ session.pop("_flashes") if "_flashes" in session else []450+ )451 if category_filter:452 flashes = list(filter(lambda f: f[0] in category_filter, flashes))453 if not with_categories:454 return [x[1] for x in flashes]455 return flashes456 457 454-def send_file(filename_or_fp, mimetype=None, as_attachment=False,455- attachment_filename=None, add_etags=True,456- cache_timeout=None, conditional=False, last_modified=None):458+def send_file(459+ filename_or_fp,460+ mimetype=None,461+ as_attachment=False,462+ attachment_filename=None,463+ add_etags=True,464+ cache_timeout=None,465+ conditional=False,466+ last_modified=None,467+):468 """Sends the contents of a file to the client. This will use the469 most efficient method available and configured. By default it will470 try to use the WSGI server's file_wrapper support. Alternatively471 you can set the application's :attr:`~Flask.use_x_sendfile` attribute83 unmodified lines555 """556 mtime = None557 fsize = None558 548- if hasattr(filename_or_fp, '__fspath__'):559+ if hasattr(filename_or_fp, "__fspath__"):560 filename_or_fp = fspath(filename_or_fp)561 562 if isinstance(filename_or_fp, string_types):563 filename = filename_or_fp7 unmodified lines571 filename = None572 573 if mimetype is None:574 if attachment_filename is not None:564- mimetype = mimetypes.guess_type(attachment_filename)[0] \565- or 'application/octet-stream'575+ mimetype = (576+ mimetypes.guess_type(attachment_filename)[0]577+ or "application/octet-stream"578+ )579 580 if mimetype is None:581 raise ValueError(569- 'Unable to infer MIME-type because no filename is available. '570- 'Please set either `attachment_filename`, pass a filepath to '571- '`filename_or_fp` or set your own MIME-type via `mimetype`.'582+ "Unable to infer MIME-type because no filename is available. "583+ "Please set either `attachment_filename`, pass a filepath to "584+ "`filename_or_fp` or set your own MIME-type via `mimetype`."585 )586 587 headers = Headers()588 if as_attachment:589 if attachment_filename is None:577- raise TypeError('filename unavailable, required for '578- 'sending as attachment')590+ raise TypeError(591+ "filename unavailable, required for " "sending as attachment"592+ )593 594 if not isinstance(attachment_filename, text_type):581- attachment_filename = attachment_filename.decode('utf-8')595+ attachment_filename = attachment_filename.decode("utf-8")596 597 try:584- attachment_filename = attachment_filename.encode('ascii')598+ attachment_filename = attachment_filename.encode("ascii")599 except UnicodeEncodeError:600 filenames = {587- 'filename': unicodedata.normalize(588- 'NFKD', attachment_filename).encode('ascii', 'ignore'),589- 'filename*': "UTF-8''%s" % url_quote(attachment_filename),601+ "filename": unicodedata.normalize("NFKD", attachment_filename).encode(602+ "ascii", "ignore"603+ ),604+ "filename*": "UTF-8''%s" % url_quote(attachment_filename),605 }606 else:592- filenames = {'filename': attachment_filename}607+ filenames = {"filename": attachment_filename}608 594- headers.add('Content-Disposition', 'attachment', **filenames)609+ headers.add("Content-Disposition", "attachment", **filenames)610 611 if current_app.use_x_sendfile and filename:612 if file is not None:613 file.close()599- headers['X-Sendfile'] = filename614+ headers["X-Sendfile"] = filename615 fsize = os.path.getsize(filename)601- headers['Content-Length'] = fsize616+ headers["Content-Length"] = fsize617 data = None618 else:619 if file is None:605- file = open(filename, 'rb')620+ file = open(filename, "rb")621 mtime = os.path.getmtime(filename)622 fsize = os.path.getsize(filename)608- headers['Content-Length'] = fsize623+ headers["Content-Length"] = fsize624 elif isinstance(file, io.BytesIO):625 try:626 fsize = file.getbuffer().nbytes627 except AttributeError:628 # Python 2 doesn't have getbuffer629 fsize = len(file.getvalue())615- headers['Content-Length'] = fsize630+ headers["Content-Length"] = fsize631 data = wrap_file(request.environ, file)632 618- rv = current_app.response_class(data, mimetype=mimetype, headers=headers,619- direct_passthrough=True)633+ rv = current_app.response_class(634+ data, mimetype=mimetype, headers=headers, direct_passthrough=True635+ )636 637 if last_modified is not None:638 rv.last_modified = last_modified639 elif mtime is not None:9 unmodified lines649 if add_etags and filename is not None:650 from warnings import warn651 652 try:637- rv.set_etag('%s-%s-%s' % (638- os.path.getmtime(filename),639- os.path.getsize(filename),640- adler32(641- filename.encode('utf-8') if isinstance(filename, text_type)642- else filename643- ) & 0xffffffff644- ))653+ rv.set_etag(654+ "%s-%s-%s"655+ % (656+ os.path.getmtime(filename),657+ os.path.getsize(filename),658+ adler32(659+ filename.encode("utf-8")660+ if isinstance(filename, text_type)661+ else filename662+ )663+ & 0xFFFFFFFF,664+ )665+ )666 except OSError:646- warn('Access %s failed, maybe it does not exist, so ignore etags in '647- 'headers' % filename, stacklevel=2)667+ warn(668+ "Access %s failed, maybe it does not exist, so ignore etags in "669+ "headers" % filename,670+ stacklevel=2,671+ )672 673 if conditional:674 try:651- rv = rv.make_conditional(request, accept_ranges=True,652- complete_length=fsize)675+ rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize)676 except RequestedRangeNotSatisfiable:677 if file is not None:678 file.close()679 raise680 # make sure we don't send x-sendfile for servers that681 # ignore the 304 status code for x-sendfile.682 if rv.status_code == 304:660- rv.headers.pop('x-sendfile', None)683+ rv.headers.pop("x-sendfile", None)684 return rv685 686 687 def safe_join(directory, *pathnames):16 unmodified lines704 705 parts = [directory]706 707 for filename in pathnames:685- if filename != '':708+ if filename != "":709 filename = posixpath.normpath(filename)710 711 if (712 any(sep in filename for sep in _os_alt_seps)713 or os.path.isabs(filename)691- or filename == '..'692- or filename.startswith('../')714+ or filename == ".."715+ or filename.startswith("../")716 ):717 raise NotFound()718 719 parts.append(filename)37 unmodified lines757 if not os.path.isfile(filename):758 raise NotFound()759 except (TypeError, ValueError):760 raise BadRequest()738- options.setdefault('conditional', True)761+ options.setdefault("conditional", True)762 return send_file(filename, **options)763 764 765 def get_root_path(import_name):3 unmodified lines769 Not to be confused with the package path returned by :func:`find_package`.770 """771 # Module already imported and has a file attribute. Use that first.772 mod = sys.modules.get(import_name)750- if mod is not None and hasattr(mod, '__file__'):773+ if mod is not None and hasattr(mod, "__file__"):774 return os.path.dirname(os.path.abspath(mod.__file__))775 776 # Next attempt: check the loader.777 loader = pkgutil.get_loader(import_name)778 779 # Loader does not exist or we're referring to an unloaded main module780 # or a main module without path (interactive sessions), go with the781 # current working directory.759- if loader is None or import_name == '__main__':782+ if loader is None or import_name == "__main__":783 return os.getcwd()784 785 # For .egg, zipimporter does not have get_filename until Python 2.7.786 # Some other loaders might exhibit the same behavior.764- if hasattr(loader, 'get_filename'):787+ if hasattr(loader, "get_filename"):788 filepath = loader.get_filename(import_name)789 else:790 # Fall back to imports.791 __import__(import_name)792 mod = sys.modules[import_name]770- filepath = getattr(mod, '__file__', None)793+ filepath = getattr(mod, "__file__", None)794 795 # If we don't have a filepath it might be because we are a796 # namespace package. In this case we pick the root path from the797 # first module that is contained in our package.798 if filepath is None:776- raise RuntimeError('No root path can be found for the provided '777- 'module "%s". This can happen because the '778- 'module came from an import hook that does '779- 'not provide file name information or because '780- 'it\'s a namespace package. In this case '781- 'the root path needs to be explicitly '782- 'provided.' % import_name)799+ raise RuntimeError(800+ "No root path can be found for the provided "801+ 'module "%s". This can happen because the '802+ "module came from an import hook that does "803+ "not provide file name information or because "804+ "it's a namespace package. In this case "805+ "the root path needs to be explicitly "806+ "provided." % import_name807+ )808 809 # filepath is import_name.py for a module, or __init__.py for a package.810 return os.path.dirname(os.path.abspath(filepath))811 3 unmodified lines815 attempts to figure out if the given module is actually a package.816 """817 # If the loader can tell us if something is a package, we can818 # directly ask the loader.794- if hasattr(loader, 'is_package'):819+ if hasattr(loader, "is_package"):820 return loader.is_package(mod_name)821 # importlib's namespace loaders do not have this functionality but822 # all the modules it loads are packages, so we can take advantage of823 # this information.799- elif (loader.__class__.__module__ == '_frozen_importlib' and800- loader.__class__.__name__ == 'NamespaceLoader'):824+ elif (825+ loader.__class__.__module__ == "_frozen_importlib"826+ and loader.__class__.__name__ == "NamespaceLoader"827+ ):828 return True829 # Otherwise we need to fail with an error that explains what went830 # wrong.831 raise AttributeError(805- ('%s.is_package() method is missing but is required by Flask of '806- 'PEP 302 import hooks. If you do not use import hooks and '807- 'you encounter this error please file a bug against Flask.') %808- loader.__class__.__name__)832+ (833+ "%s.is_package() method is missing but is required by Flask of "834+ "PEP 302 import hooks. If you do not use import hooks and "835+ "you encounter this error please file a bug against Flask."836+ )837+ % loader.__class__.__name__838+ )839 840 841 def find_package(import_name):842 """Finds a package and returns the prefix (or None if the package is2 unmodified lines845 have to be added to the pythonpath in order to make it possible to846 import the module. The prefix is the path below which a UNIX like847 folder structure exists (lib, share etc.).848 """819- root_mod_name = import_name.split('.')[0]849+ root_mod_name = import_name.split(".")[0]850 loader = pkgutil.get_loader(root_mod_name)821- if loader is None or import_name == '__main__':851+ if loader is None or import_name == "__main__":852 # import name is not found, or interactive/main module853 package_path = os.getcwd()854 else:855 # For .egg, zipimporter does not have get_filename until Python 2.7.826- if hasattr(loader, 'get_filename'):856+ if hasattr(loader, "get_filename"):857 filename = loader.get_filename(root_mod_name)828- elif hasattr(loader, 'archive'):858+ elif hasattr(loader, "archive"):859 # zipimporter's loader.archive points to the .egg or .zip860 # archive filename is dropped in call to dirname below.861 filename = loader.archive862 else:7 unmodified lines870 871 # In case the root module is a package we need to chop of the872 # rightmost part. This needs to go through a helper function873 # because of python 3.3 namespace packages.844- if _matching_loader_thinks_module_is_package(845- loader, root_mod_name):874+ if _matching_loader_thinks_module_is_package(loader, root_mod_name):875 package_path = os.path.dirname(package_path)876 877 site_parent, site_folder = os.path.split(package_path)878 py_prefix = os.path.abspath(sys.prefix)879 if package_path.startswith(py_prefix):880 return py_prefix, package_path852- elif site_folder.lower() == 'site-packages':881+ elif site_folder.lower() == "site-packages":882 parent, folder = os.path.split(site_parent)883 # Windows like installations855- if folder.lower() == 'lib':884+ if folder.lower() == "lib":885 base_dir = parent886 # UNIX like installations858- elif os.path.basename(parent).lower() == 'lib':887+ elif os.path.basename(parent).lower() == "lib":888 base_dir = os.path.dirname(parent)889 else:890 base_dir = site_parent891 return base_dir, package_path57 unmodified lines949 def _set_static_folder(self, value):950 self._static_folder = value951 952 static_folder = property(924- _get_static_folder, _set_static_folder,925- doc='The absolute path to the configured static folder.'953+ _get_static_folder,954+ _set_static_folder,955+ doc="The absolute path to the configured static folder.",956 )957 del _get_static_folder, _set_static_folder958 959 def _get_static_url_path(self):960 if self._static_url_path is not None:961 return self._static_url_path962 963 if self.static_folder is not None:934- return '/' + os.path.basename(self.static_folder)964+ return "/" + os.path.basename(self.static_folder)965 966 def _set_static_url_path(self, value):967 self._static_url_path = value968 969 static_url_path = property(940- _get_static_url_path, _set_static_url_path,941- doc='The URL prefix that the static route will be registered for.'970+ _get_static_url_path,971+ _set_static_url_path,972+ doc="The URL prefix that the static route will be registered for.",973 )974 del _get_static_url_path, _set_static_url_path975 976 @property11 unmodified lines988 989 .. versionadded:: 0.5990 """991 if self.template_folder is not None:961- return FileSystemLoader(os.path.join(self.root_path,962- self.template_folder))992+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))993 994 def get_send_file_max_age(self, filename):995 """Provides default cache_timeout for the :func:`send_file` functions.996 26 unmodified lines1023 1024 .. versionadded:: 0.51025 """1026 if not self.has_static_folder:997- raise RuntimeError('No static folder for this object')1027+ raise RuntimeError("No static folder for this object")1028 # Ensure get_send_file_max_age is called in all cases.1029 # Here, we ensure get_send_file_max_age is called for Blueprints.1030 cache_timeout = self.get_send_file_max_age(filename)1001- return send_from_directory(self.static_folder, filename,1002- cache_timeout=cache_timeout)1031+ return send_from_directory(1032+ self.static_folder, filename, cache_timeout=cache_timeout1033+ )1034 1004- def open_resource(self, resource, mode='rb'):1035+ def open_resource(self, resource, mode="rb"):1036 """Opens a resource from the application's resource folder. To see1037 how this works, consider the following folder structure::1038 1039 /myapplication.py14 unmodified lines1054 :param resource: the name of the resource. To access resources within1055 subfolders use forward slashes as separator.1056 :param mode: resource file opening mode, default is 'rb'.1057 """1027- if mode not in ('r', 'rb'):1028- raise ValueError('Resources can only be opened for reading')1058+ if mode not in ("r", "rb"):1059+ raise ValueError("Resources can only be opened for reading")1060 return open(os.path.join(self.root_path, resource), mode)1061 1062 1063 def total_seconds(td):18 unmodified lines1082 1083 :return: True if string is an IP address1084 :rtype: bool1085 """1055- if PY2 and os.name == 'nt':1086+ if PY2 and os.name == "nt":1087 try:1088 socket.inet_aton(value)1089 return True1090 except socket.error:11 unmodified linesmodified:flask/logging.py+5 added-5 removed
25 unmodified lines26 use this for the stream. If you are using file or dict configuration and27 can't import this directly, you can refer to it as28 ``ext://flask.logging.wsgi_errors_stream``.29 """30- return request.environ['wsgi.errors'] if request else sys.stderr30+ return request.environ["wsgi.errors"] if request else sys.stderr31 32 33 def has_level_handler(logger):34 """Check if there is a handler in the logging chain that will handle the16 unmodified lines51 52 #: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format53 #: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.54 default_handler = logging.StreamHandler(wsgi_errors_stream)55-default_handler.setFormatter(logging.Formatter(56- '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'57-))55+default_handler.setFormatter(56+ logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")57+)58 59 60 def create_logger(app):61 """Get the ``'flask.app'`` logger and configure it if needed.4 unmodified lines66 If there is no handler for the logger's effective level, add a67 :class:`~logging.StreamHandler` for68 :func:`~flask.logging.wsgi_errors_stream` with a basic format.69 """70- logger = logging.getLogger('flask.app')70+ logger = logging.getLogger("flask.app")71 72 if app.debug and logger.level == logging.NOTSET:73 logger.setLevel(logging.DEBUG)74 4 unmodified linesmodified:flask/sessions.py+40 added-38 removed
25 unmodified lines26 27 @property28 def permanent(self):29 """This reflects the ``'_permanent'`` key in the dict."""30- return self.get('_permanent', False)30+ return self.get("_permanent", False)31 32 @permanent.setter33 def permanent(self, value):34- self['_permanent'] = bool(value)34+ self["_permanent"] = bool(value)35 36 #: Some implementations can detect whether a session is newly37 #: created, but that is not guaranteed. Use with caution. The mixin38 # default is hard-coded ``False``.58 unmodified lines97 but fail on setting.98 """99 100 def _fail(self, *args, **kwargs):101- raise RuntimeError('The session is unavailable because no secret '102- 'key was set. Set the secret_key on the '103- 'application to something unique and secret.')104- __setitem__ = __delitem__ = clear = pop = popitem = \105- update = setdefault = _fail101+ raise RuntimeError(102+ "The session is unavailable because no secret "103+ "key was set. Set the secret_key on the "104+ "application to something unique and secret."105+ )106+107+ __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109 110 111 class SessionInterface(object):69 unmodified lines181 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is182 updated to avoid re-running the logic.183 """184 183- rv = app.config['SESSION_COOKIE_DOMAIN']185+ rv = app.config["SESSION_COOKIE_DOMAIN"]186 187 # set explicitly, or cached from SERVER_NAME detection188 # if False, return None189 if rv is not None:190 return rv if rv else None191 190- rv = app.config['SERVER_NAME']192+ rv = app.config["SERVER_NAME"]193 194 # server name not set, cache False to return none next time195 if not rv:194- app.config['SESSION_COOKIE_DOMAIN'] = False196+ app.config["SESSION_COOKIE_DOMAIN"] = False197 return None198 199 # chop off the port which is usually not supported by browsers200 # remove any leading '.' since we'll add that later199- rv = rv.rsplit(':', 1)[0].lstrip('.')201+ rv = rv.rsplit(":", 1)[0].lstrip(".")202 201- if '.' not in rv:203+ if "." not in rv:204 # Chrome doesn't allow names without a '.'205 # this should only come up with localhost206 # hack around this by not setting the name, and show a warning207 warnings.warn(208 '"{rv}" is not a valid cookie domain, it must contain a ".".'207- ' Add an entry to your hosts file, for example'209+ " Add an entry to your hosts file, for example"210 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)211 )210- app.config['SESSION_COOKIE_DOMAIN'] = False212+ app.config["SESSION_COOKIE_DOMAIN"] = False213 return None214 215 ip = is_ip(rv)216 217 if ip:218 warnings.warn(217- 'The session cookie domain is an IP address. This may not work'218- ' as intended in some browsers. Add an entry to your hosts'219+ "The session cookie domain is an IP address. This may not work"220+ " as intended in some browsers. Add an entry to your hosts"221 ' file, for example "localhost.localdomain", and use that'220- ' instead.'222+ " instead."223 )224 225 # if this is not an ip and app is mounted at the root, allow subdomain226 # matching by adding a '.' prefix225- if self.get_cookie_path(app) == '/' and not ip:226- rv = '.' + rv227+ if self.get_cookie_path(app) == "/" and not ip:228+ rv = "." + rv229 228- app.config['SESSION_COOKIE_DOMAIN'] = rv230+ app.config["SESSION_COOKIE_DOMAIN"] = rv231 return rv232 233 def get_cookie_path(self, app):234 """Returns the path for which the cookie should be valid. The235 default implementation uses the value from the ``SESSION_COOKIE_PATH``236 config var if it's set, and falls back to ``APPLICATION_ROOT`` or237 uses ``/`` if it's ``None``.238 """237- return app.config['SESSION_COOKIE_PATH'] \238- or app.config['APPLICATION_ROOT']239+ return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]240 241 def get_cookie_httponly(self, app):242 """Returns True if the session cookie should be httponly. This243 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``244 config var.245 """245- return app.config['SESSION_COOKIE_HTTPONLY']246+ return app.config["SESSION_COOKIE_HTTPONLY"]247 248 def get_cookie_secure(self, app):249 """Returns True if the cookie should be secure. This currently250 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.251 """251- return app.config['SESSION_COOKIE_SECURE']252+ return app.config["SESSION_COOKIE_SECURE"]253 254 def get_cookie_samesite(self, app):255 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the256 ``SameSite`` attribute. This currently just returns the value of257 the :data:`SESSION_COOKIE_SAMESITE` setting.258 """258- return app.config['SESSION_COOKIE_SAMESITE']259+ return app.config["SESSION_COOKIE_SAMESITE"]260 261 def get_expiration_time(self, app, session):262 """A helper method that returns an expiration date for the session263 or ``None`` if the session is linked to the browser session. The15 unmodified lines279 .. versionadded:: 0.11280 """281 282 return session.modified or (282- session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']283+ session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]284 )285 286 def open_session(self, app, request):287 """This method has to be implemented and must either return ``None``18 unmodified lines306 class SecureCookieSessionInterface(SessionInterface):307 """The default session interface that stores sessions in signed cookies308 through the :mod:`itsdangerous` module.309 """310+311 #: the salt that should be applied on top of the secret key for the312 #: signing of cookie based sessions.311- salt = 'cookie-session'313+ salt = "cookie-session"314 #: the hash function to use for the signature. The default is sha1315 digest_method = staticmethod(hashlib.sha1)316 #: the name of the itsdangerous supported key derivation. The default317 #: is hmac.316- key_derivation = 'hmac'318+ key_derivation = "hmac"319 #: A python serializer for the payload. The default is a compact320 #: JSON derived serializer with support for some extra Python types321 #: such as datetime objects or tuples.322 serializer = session_json_serializer2 unmodified lines325 def get_signing_serializer(self, app):326 if not app.secret_key:327 return None328 signer_kwargs = dict(327- key_derivation=self.key_derivation,328- digest_method=self.digest_method329+ key_derivation=self.key_derivation, digest_method=self.digest_method330 )331+ return URLSafeTimedSerializer(332+ app.secret_key,330- return URLSafeTimedSerializer(app.secret_key, salt=self.salt,331- serializer=self.serializer,332- signer_kwargs=signer_kwargs)333+ salt=self.salt,334+ serializer=self.serializer,335+ signer_kwargs=signer_kwargs,336+ )337 338 def open_session(self, app, request):339 s = self.get_signing_serializer(app)340 if s is None:16 unmodified lines357 # If the session is empty, return without setting the cookie.358 if not session:359 if session.modified:360 response.delete_cookie(357- app.session_cookie_name,358- domain=domain,359- path=path361+ app.session_cookie_name, domain=domain, path=path362 )363 364 return365 366 # Add a "Vary: Cookie" header if the session was accessed at all.367 if session.accessed:366- response.vary.add('Cookie')368+ response.vary.add("Cookie")369 370 if not self.should_set_cookie(app, session):371 return372 9 unmodified lines382 httponly=httponly,383 domain=domain,384 path=path,385 secure=secure,384- samesite=samesite386+ samesite=samesite,387 )modified:flask/signals.py+25 added-15 removed
11 unmodified lines12 13 signals_available = False14 try:15 from blinker import Namespace16+17 signals_available = True18 except ImportError:19+20 class Namespace(object):21 def signal(self, name, doc=None):22 return _FakeSignal(name, doc)23 6 unmodified lines30 31 def __init__(self, name, doc=None):32 self.name = name33 self.__doc__ = doc34+35 def _fail(self, *args, **kwargs):33- raise RuntimeError('signalling support is unavailable '34- 'because the blinker library is '35- 'not installed.')36+ raise RuntimeError(37+ "signalling support is unavailable "38+ "because the blinker library is "39+ "not installed."40+ )41+42 send = lambda *a, **kw: None37- connect = disconnect = has_receivers_for = receivers_for = \38- temporarily_connected_to = connected_to = _fail43+ connect = (44+ disconnect45+ ) = (46+ has_receivers_for47+ ) = receivers_for = temporarily_connected_to = connected_to = _fail48 del _fail49 50+51 # The namespace for code signals. If you are not Flask code, do52 # not put signals in here. Create your own namespace instead.53 _signals = Namespace()54 55 56 # Core signals. For usage examples grep the source code or consult57 # the API documentation in docs/api.rst as well as docs/signals.rst48-template_rendered = _signals.signal('template-rendered')49-before_render_template = _signals.signal('before-render-template')50-request_started = _signals.signal('request-started')51-request_finished = _signals.signal('request-finished')52-request_tearing_down = _signals.signal('request-tearing-down')53-got_request_exception = _signals.signal('got-request-exception')54-appcontext_tearing_down = _signals.signal('appcontext-tearing-down')55-appcontext_pushed = _signals.signal('appcontext-pushed')56-appcontext_popped = _signals.signal('appcontext-popped')57-message_flashed = _signals.signal('message-flashed')58+template_rendered = _signals.signal("template-rendered")59+before_render_template = _signals.signal("before-render-template")60+request_started = _signals.signal("request-started")61+request_finished = _signals.signal("request-finished")62+request_tearing_down = _signals.signal("request-tearing-down")63+got_request_exception = _signals.signal("got-request-exception")64+appcontext_tearing_down = _signals.signal("appcontext-tearing-down")65+appcontext_pushed = _signals.signal("appcontext-pushed")66+appcontext_popped = _signals.signal("appcontext-popped")67+message_flashed = _signals.signal("message-flashed")modified:flask/templating.py+14 added-12 removed
7 unmodified lines8 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10 """11 12-from jinja2 import BaseLoader, Environment as BaseEnvironment, \13- TemplateNotFound12+from jinja2 import BaseLoader, Environment as BaseEnvironment, TemplateNotFound13 14 from .globals import _request_ctx_stack, _app_ctx_stack15 from .signals import template_rendered, before_render_template16 5 unmodified lines22 reqctx = _request_ctx_stack.top23 appctx = _app_ctx_stack.top24 rv = {}25 if appctx is not None:27- rv['g'] = appctx.g26+ rv["g"] = appctx.g27 if reqctx is not None:29- rv['request'] = reqctx.request30- rv['session'] = reqctx.session28+ rv["request"] = reqctx.request29+ rv["session"] = reqctx.session30 return rv31 32 33 class Environment(BaseEnvironment):2 unmodified lines36 name of the blueprint to referenced templates if necessary.37 """38 39 def __init__(self, app, **options):41- if 'loader' not in options:42- options['loader'] = app.create_global_jinja_loader()40+ if "loader" not in options:41+ options["loader"] = app.create_global_jinja_loader()42 BaseEnvironment.__init__(self, **options)43 self.app = app44 45 5 unmodified lines51 def __init__(self, app):52 self.app = app53 54 def get_source(self, environment, template):56- if self.app.config['EXPLAIN_TEMPLATE_LOADING']:55+ if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:56 return self._get_source_explained(environment, template)57 return self._get_source_fast(environment, template)58 59 def _get_source_explained(self, environment, template):9 unmodified lines69 rv = None70 attempts.append((loader, srcobj, rv))71 72 from .debughelpers import explain_template_loading_attempts73+74 explain_template_loading_attempts(self.app, template, attempts)75 76 if trv is not None:77 return trv52 unmodified lines130 context of the template.131 """132 ctx = _app_ctx_stack.top133 ctx.app.update_template_context(context)134+ return _render(134- return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),135- context, ctx.app)135+ ctx.app.jinja_env.get_or_select_template(template_name_or_list),136+ context,137+ ctx.app,138+ )139 140 141 def render_template_string(source, **context):142 """Renders a template from the given template source string5 unmodified lines148 context of the template.149 """150 ctx = _app_ctx_stack.top151 ctx.app.update_template_context(context)149- return _render(ctx.app.jinja_env.from_string(source),150- context, ctx.app)152+ return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)modified:flask/testing.py+41 added-41 removed
20 unmodified lines21 from werkzeug.urls import url_parse22 23 24 def make_test_environ_builder(25- app, path='/', base_url=None, subdomain=None, url_scheme=None,26- *args, **kwargs25+ app, path="/", base_url=None, subdomain=None, url_scheme=None, *args, **kwargs26 ):27 """Create a :class:`~werkzeug.test.EnvironBuilder`, taking some28 defaults from the application.29 14 unmodified lines44 :param kwargs: other keyword arguments passed to45 :class:`~werkzeug.test.EnvironBuilder`.46 """47 49- assert (50- not (base_url or subdomain or url_scheme)51- or (base_url is not None) != bool(subdomain or url_scheme)48+ assert not (base_url or subdomain or url_scheme) or (base_url is not None) != bool(49+ subdomain or url_scheme50 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'51 52 if base_url is None:55- http_host = app.config.get('SERVER_NAME') or 'localhost'56- app_root = app.config['APPLICATION_ROOT']53+ http_host = app.config.get("SERVER_NAME") or "localhost"54+ app_root = app.config["APPLICATION_ROOT"]55 56 if subdomain:59- http_host = '{0}.{1}'.format(subdomain, http_host)57+ http_host = "{0}.{1}".format(subdomain, http_host)58 59 if url_scheme is None:62- url_scheme = app.config['PREFERRED_URL_SCHEME']60+ url_scheme = app.config["PREFERRED_URL_SCHEME"]61 62 url = url_parse(path)65- base_url = '{scheme}://{netloc}/{path}'.format(63+ base_url = "{scheme}://{netloc}/{path}".format(64 scheme=url.scheme or url_scheme,65 netloc=url.netloc or http_host,68- path=app_root.lstrip('/')66+ path=app_root.lstrip("/"),67 )68 path = url.path69 70 if url.query:73- sep = b'?' if isinstance(url.query, bytes) else '?'71+ sep = b"?" if isinstance(url.query, bytes) else "?"72 path += sep + url.query73 76- if 'json' in kwargs:77- assert 'data' not in kwargs, (78- "Client cannot provide both 'json' and 'data'."79- )74+ if "json" in kwargs:75+ assert "data" not in kwargs, "Client cannot provide both 'json' and 'data'."76 77 # push a context so flask.json can use app's json attributes78 with app.app_context():83- kwargs['data'] = json_dumps(kwargs.pop('json'))79+ kwargs["data"] = json_dumps(kwargs.pop("json"))80 85- if 'content_type' not in kwargs:86- kwargs['content_type'] = 'application/json'81+ if "content_type" not in kwargs:82+ kwargs["content_type"] = "application/json"83 84 return EnvironBuilder(path, base_url, *args, **kwargs)85 86 17 unmodified lines104 def __init__(self, *args, **kwargs):105 super(FlaskClient, self).__init__(*args, **kwargs)106 self.environ_base = {107 "REMOTE_ADDR": "127.0.0.1",112- "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__108+ "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,109 }110 111 @contextmanager112 def session_transaction(self, *args, **kwargs):13 unmodified lines126 :meth:`~flask.Flask.test_request_context` which are directly127 passed through.128 """129 if self.cookie_jar is None:134- raise RuntimeError('Session transactions only make sense '135- 'with cookies enabled.')130+ raise RuntimeError(131+ "Session transactions only make sense " "with cookies enabled."132+ )133 app = self.application137- environ_overrides = kwargs.setdefault('environ_overrides', {})134+ environ_overrides = kwargs.setdefault("environ_overrides", {})135 self.cookie_jar.inject_wsgi(environ_overrides)136 outer_reqctx = _request_ctx_stack.top137 with app.test_request_context(*args, **kwargs) as c:138 session_interface = app.session_interface139 sess = session_interface.open_session(app, c.request)140 if sess is None:144- raise RuntimeError('Session backend did not open a session. '145- 'Check the configuration')141+ raise RuntimeError(142+ "Session backend did not open a session. " "Check the configuration"143+ )144 145 # Since we have to open a new request context for the session146 # handling we want to make sure that we hide out own context147 # from the caller. By pushing the original request context13 unmodified lines161 headers = resp.get_wsgi_headers(c.request.environ)162 self.cookie_jar.extract_wsgi(c.request.environ, headers)163 164 def open(self, *args, **kwargs):167- as_tuple = kwargs.pop('as_tuple', False)168- buffered = kwargs.pop('buffered', False)169- follow_redirects = kwargs.pop('follow_redirects', False)165+ as_tuple = kwargs.pop("as_tuple", False)166+ buffered = kwargs.pop("buffered", False)167+ follow_redirects = kwargs.pop("follow_redirects", False)168 169 if (172- not kwargs and len(args) == 1170+ not kwargs171+ and len(args) == 1172 and isinstance(args[0], (EnvironBuilder, dict))173 ):174 environ = self.environ_base.copy()175 1 unmodified line177 environ.update(args[0].get_environ())178 else:179 environ.update(args[0])180 182- environ['flask._preserve_context'] = self.preserve_context181+ environ["flask._preserve_context"] = self.preserve_context182 else:184- kwargs.setdefault('environ_overrides', {}) \185- ['flask._preserve_context'] = self.preserve_context186- kwargs.setdefault('environ_base', self.environ_base)187- builder = make_test_environ_builder(188- self.application, *args, **kwargs189- )183+ kwargs.setdefault("environ_overrides", {})[184+ "flask._preserve_context"185+ ] = self.preserve_context186+ kwargs.setdefault("environ_base", self.environ_base)187+ builder = make_test_environ_builder(self.application, *args, **kwargs)188 189 try:190 environ = builder.get_environ()191 finally:192 builder.close()193 194 return Client.open(197- self, environ,195+ self,196+ environ,197 as_tuple=as_tuple,198 buffered=buffered,200- follow_redirects=follow_redirects199+ follow_redirects=follow_redirects,200 )201 202 def __enter__(self):203 if self.preserve_context:205- raise RuntimeError('Cannot nest client invocations')204+ raise RuntimeError("Cannot nest client invocations")205 self.preserve_context = True206 return self207 208 def __exit__(self, exc_type, exc_value, tb):11 unmodified lines220 """A :class:`~click.testing.CliRunner` for testing a Flask app's221 CLI commands. Typically created using222 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.223 """224+225 def __init__(self, app, **kwargs):226 self.app = app227 super(FlaskCliRunner, self).__init__(**kwargs)228 14 unmodified lines243 """244 if cli is None:245 cli = self.app.cli246 247- if 'obj' not in kwargs:248- kwargs['obj'] = ScriptInfo(create_app=lambda: self.app)247+ if "obj" not in kwargs:248+ kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)249 250 return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)modified:flask/views.py+8 added-6 removed
11 unmodified lines12 from .globals import request13 from ._compat import with_metaclass14 15 16-http_method_funcs = frozenset(['get', 'post', 'head', 'options',17- 'delete', 'put', 'trace', 'patch'])16+http_method_funcs = frozenset(17+ ["get", "post", "head", "options", "delete", "put", "trace", "patch"]18+)19 20 21 class View(object):22 """Alternative way to use view functions. A subclass has to implement60 unmodified lines83 84 The arguments passed to :meth:`as_view` are forwarded to the85 constructor of the class.86 """87+88 def view(*args, **kwargs):89 self = view.view_class(*class_args, **class_kwargs)90 return self.dispatch_request(*args, **kwargs)91 24 unmodified lines116 117 def __init__(cls, name, bases, d):118 super(MethodViewType, cls).__init__(name, bases, d)119 118- if 'methods' not in d:120+ if "methods" not in d:121 methods = set()122 123 for key in http_method_funcs:124 if hasattr(cls, key):27 unmodified lines152 meth = getattr(self, request.method.lower(), None)153 154 # If the request method is HEAD and we don't have a handler for it155 # retry with GET.154- if meth is None and request.method == 'HEAD':155- meth = getattr(self, 'get', None)156+ if meth is None and request.method == "HEAD":157+ meth = getattr(self, "get", None)158 157- assert meth is not None, 'Unimplemented method %r' % request.method159+ assert meth is not None, "Unimplemented method %r" % request.method160 return meth(*args, **kwargs)modified:flask/wrappers.py+11 added-9 removed
32 unmodified lines33 .. versionadded:: 0.1134 """35 mt = self.mimetype36 return (37- mt == 'application/json'38- or (mt.startswith('application/')) and mt.endswith('+json')37+ mt == "application/json"38+ or (mt.startswith("application/"))39+ and mt.endswith("+json")40 )41 42 @property43 def json(self):59 unmodified lines103 104 .. versionadded:: 0.8105 """106 if current_app is not None and current_app.debug:106- raise BadRequest('Failed to decode JSON object: {0}'.format(e))107+ raise BadRequest("Failed to decode JSON object: {0}".format(e))108 109 raise BadRequest()110 111 34 unmodified lines146 @property147 def max_content_length(self):148 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""149 if current_app:149- return current_app.config['MAX_CONTENT_LENGTH']150+ return current_app.config["MAX_CONTENT_LENGTH"]151 152 @property153 def endpoint(self):154 """The endpoint that matched the request. This in combination with6 unmodified lines161 162 @property163 def blueprint(self):164 """The name of the current blueprint"""164- if self.url_rule and '.' in self.url_rule.endpoint:165- return self.url_rule.endpoint.rsplit('.', 1)[0]165+ if self.url_rule and "." in self.url_rule.endpoint:166+ return self.url_rule.endpoint.rsplit(".", 1)[0]167 168 def _load_form_data(self):169 RequestBase._load_form_data(self)170 1 unmodified line172 # subclass that raises a different error for key errors.173 if (174 current_app175 and current_app.debug175- and self.mimetype != 'multipart/form-data'176+ and self.mimetype != "multipart/form-data"177 and not self.files178 ):179 from .debughelpers import attach_enctype_error_multidict180+181 attach_enctype_error_multidict(self)182 183 184 class Response(ResponseBase, JSONMixin):13 unmodified lines198 199 Added :attr:`max_cookie_size`.200 """201 200- default_mimetype = 'text/html'202+ default_mimetype = "text/html"203 204 def _get_data_for_json(self, cache):205 return self.get_data()206 4 unmodified lines211 See :attr:`~werkzeug.wrappers.BaseResponse.max_cookie_size` in212 Werkzeug's docs.213 """214 if current_app:213- return current_app.config['MAX_COOKIE_SIZE']215+ return current_app.config["MAX_COOKIE_SIZE"]216 217 # return Werkzeug's default when not in an app context218 return super(Response, self).max_cookie_sizemodified:scripts/make-release.py+36 added-38 removed
5 unmodified lines6 import sys7 from datetime import date, datetime8 from subprocess import PIPE, Popen9 10-_date_strip_re = re.compile(r'(?<=\d)(st|nd|rd|th)')10+_date_strip_re = re.compile(r"(?<=\d)(st|nd|rd|th)")11 12 13 def parse_changelog():14- with open('CHANGES.rst') as f:14+ with open("CHANGES.rst") as f:15 lineiter = iter(f)16 for line in lineiter:17- match = re.search('^Version\s+(.*)', line.strip())17+ match = re.search("^Version\s+(.*)", line.strip())18 19 if match is None:20 continue21 22 version = match.group(1).strip()23 24- if next(lineiter).count('-') != len(match.group(0)):24+ if next(lineiter).count("-") != len(match.group(0)):25 continue26 27 while 1:28 change_info = next(lineiter).strip()1 unmodified line30 if change_info:31 break32 33 match = re.search(34- r'released on (\w+\s+\d+\w+\s+\d+)(?:, codename (.*))?',34+ r"released on (\w+\s+\d+\w+\s+\d+)(?:, codename (.*))?",35 change_info,36- flags=re.IGNORECASE36+ flags=re.IGNORECASE,37 )38 39 if match is None:40 continue3 unmodified lines44 45 46 def bump_version(version):47 try:48- parts = [int(i) for i in version.split('.')]48+ parts = [int(i) for i in version.split(".")]49 except ValueError:50- fail('Current version is not numeric')50+ fail("Current version is not numeric")51 52 parts[-1] += 153- return '.'.join(map(str, parts))53+ return ".".join(map(str, parts))54 55 56 def parse_date(string):57- string = _date_strip_re.sub('', string)58- return datetime.strptime(string, '%B %d %Y')57+ string = _date_strip_re.sub("", string)58+ return datetime.strptime(string, "%B %d %Y")59 60 61 def set_filename_version(filename, version_number, pattern):62 changed = []5 unmodified lines68 69 with open(filename) as f:70 contents = re.sub(71 r"^(\s*%s\s*=\s*')(.+?)(')" % pattern,72- inject_version, f.read(),73- flags=re.DOTALL | re.MULTILINE72+ inject_version,73+ f.read(),74+ flags=re.DOTALL | re.MULTILINE,75 )76 77 if not changed:77- fail('Could not find %s in %s', pattern, filename)78+ fail("Could not find %s in %s", pattern, filename)79 79- with open(filename, 'w') as f:80+ with open(filename, "w") as f:81 f.write(contents)82 83 84 def set_init_version(version):84- info('Setting __init__.py version to %s', version)85- set_filename_version('flask/__init__.py', version, '__version__')85+ info("Setting __init__.py version to %s", version)86+ set_filename_version("flask/__init__.py", version, "__version__")87 88 89 def build():89- cmd = [sys.executable, 'setup.py', 'sdist', 'bdist_wheel']90+ cmd = [sys.executable, "setup.py", "sdist", "bdist_wheel"]91 Popen(cmd).wait()92 93 94 def fail(message, *args):94- print('Error:', message % args, file=sys.stderr)95+ print("Error:", message % args, file=sys.stderr)96 sys.exit(1)97 98 99 def info(message, *args):100 print(message % args, file=sys.stderr)101 102 103 def get_git_tags():103- return set(104- Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()105- )104+ return set(Popen(["git", "tag"], stdout=PIPE).communicate()[0].splitlines())105 106 107 def git_is_clean():109- return Popen(['git', 'diff', '--quiet']).wait() == 0108+ return Popen(["git", "diff", "--quiet"]).wait() == 0109 110 111 def make_git_commit(message, *args):112 message = message % args114- Popen(['git', 'commit', '-am', message]).wait()113+ Popen(["git", "commit", "-am", message]).wait()114 115 116 def make_git_tag(tag):117 info('Tagging "%s"', tag)119- Popen(['git', 'tag', tag]).wait()118+ Popen(["git", "tag", tag]).wait()119 120 121 def main():123- os.chdir(os.path.join(os.path.dirname(__file__), '..'))122+ os.chdir(os.path.join(os.path.dirname(__file__), ".."))123 124 rv = parse_changelog()125 126 if rv is None:128- fail('Could not parse changelog')127+ fail("Could not parse changelog")128 129 version, release_date, codename = rv131- dev_version = bump_version(version) + '.dev'130+ dev_version = bump_version(version) + ".dev"131 132 info(134- 'Releasing %s (codename %s, release date %s)',135- version, codename, release_date.strftime('%d/%m/%Y')133+ "Releasing %s (codename %s, release date %s)",134+ version,135+ codename,136+ release_date.strftime("%d/%m/%Y"),137 )138 tags = get_git_tags()139 140 if version in tags:141 fail('Version "%s" is already tagged', version)142 143 if release_date.date() != date.today():143- fail(144- 'Release date is not today (%s != %s)',145- release_date.date(), date.today()146- )144+ fail("Release date is not today (%s != %s)", release_date.date(), date.today())145 146 if not git_is_clean():149- fail('You have uncommitted changes in git')147+ fail("You have uncommitted changes in git")148 149 try:150 import wheel # noqa: F401151 except ImportError:154- fail('You need to install the wheel package.')152+ fail("You need to install the wheel package.")153 154 set_init_version(version)157- make_git_commit('Bump version number to %s', version)155+ make_git_commit("Bump version number to %s", version)156 make_git_tag(version)157 build()158 set_init_version(dev_version)159 160 163-if __name__ == '__main__':161+if __name__ == "__main__":162 main()modified:tests/test_apps/blueprintapp/apps/admin/__init__.py+11 added-7 removed
1 from flask import Blueprint, render_template2 3-admin = Blueprint('admin', __name__, url_prefix='/admin',4- template_folder='templates',5- static_folder='static')3+admin = Blueprint(4+ "admin",5+ __name__,6+ url_prefix="/admin",7+ template_folder="templates",8+ static_folder="static",9+)10 11 8-@admin.route('/')12+@admin.route("/")13 def index():10- return render_template('admin/index.html')14+ return render_template("admin/index.html")15 16 13-@admin.route('/index2')17+@admin.route("/index2")18 def index2():15- return render_template('./admin/index.html')19+ return render_template("./admin/index.html")modified:tests/test_apps/blueprintapp/apps/frontend/__init__.py+5 added-5 removed
1 from flask import Blueprint, render_template2 3-frontend = Blueprint('frontend', __name__, template_folder='templates')3+frontend = Blueprint("frontend", __name__, template_folder="templates")4 5 6-@frontend.route('/')6+@frontend.route("/")7 def index():8- return render_template('frontend/index.html')8+ return render_template("frontend/index.html")9 10 11-@frontend.route('/missing')11+@frontend.route("/missing")12 def missing_template():13- return render_template('missing_template.html')13+ return render_template("missing_template.html")modified:tests/test_apps/blueprintapp/__init__.py+2 added-1 removed
1 from flask import Flask2 3 app = Flask(__name__)4-app.config['DEBUG'] = True4+app.config["DEBUG"] = True5 from blueprintapp.apps.admin import admin6 from blueprintapp.apps.frontend import frontend7+8 app.register_blueprint(admin)9 app.register_blueprint(frontend)modified:tests/test_apps/cliapp/app.py+1 added-1 removed
1 from __future__ import absolute_import, print_function2 3 from flask import Flask4 5-testapp = Flask('testapp')5+testapp = Flask("testapp")modified:tests/test_apps/cliapp/factory.py+3 added-3 removed
2 unmodified lines3 from flask import Flask4 5 6 def create_app():7- return Flask('app')7+ return Flask("app")8 9 10 def create_app2(foo, bar):11- return Flask('_'.join(['app2', foo, bar]))11+ return Flask("_".join(["app2", foo, bar]))12 13 14 def create_app3(foo, script_info):15- return Flask('_'.join(['app3', foo, script_info.data['test']]))15+ return Flask("_".join(["app3", foo, script_info.data["test"]]))16 17 18 def no_app():19 passmodified:tests/test_apps/cliapp/importerrorapp.py+1 added-1 removed
2 unmodified lines3 from flask import Flask4 5 raise ImportError()6 7-testapp = Flask('testapp')7+testapp = Flask("testapp")modified:tests/test_apps/cliapp/multiapp.py+2 added-2 removed
1 from __future__ import absolute_import, print_function2 3 from flask import Flask4 5-app1 = Flask('app1')6-app2 = Flask('app2')5+app1 = Flask("app1")6+app2 = Flask("app2")modified:tests/test_apps/helloworld/hello.py+2 added
1 from flask import Flask2+3 app = Flask(__name__)4 5+6 @app.route("/")7 def hello():8 return "Hello World!"modified:tests/test_apps/subdomaintestmodule/__init__.py+1 added-1 removed
1 from flask import Module2 3 4-mod = Module(__name__, 'foo', subdomain='foo')4+mod = Module(__name__, "foo", subdomain="foo")modified:tests/conftest.py+33 added-27 removed
18 unmodified lines19 import flask20 from flask import Flask as _Flask21 22 23-@pytest.fixture(scope='session', autouse=True)23+@pytest.fixture(scope="session", autouse=True)24 def _standard_os_environ():25 """Set up ``os.environ`` at the start of the test session to have26 standard values. Returns a list of operations that is used by27 :func:`._reset_os_environ` after each test.28 """29 mp = monkeypatch.MonkeyPatch()30 out = (31- (os.environ, 'FLASK_APP', monkeypatch.notset),32- (os.environ, 'FLASK_ENV', monkeypatch.notset),33- (os.environ, 'FLASK_DEBUG', monkeypatch.notset),34- (os.environ, 'FLASK_RUN_FROM_CLI', monkeypatch.notset),35- (os.environ, 'WERKZEUG_RUN_MAIN', monkeypatch.notset),31+ (os.environ, "FLASK_APP", monkeypatch.notset),32+ (os.environ, "FLASK_ENV", monkeypatch.notset),33+ (os.environ, "FLASK_DEBUG", monkeypatch.notset),34+ (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),35+ (os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),36 )37 38 for _, key, value in out:39 if value is monkeypatch.notset:14 unmodified lines54 55 56 class Flask(_Flask):57 testing = True58- secret_key = 'test key'58+ secret_key = "test key"59 60 61 @pytest.fixture62 def app():63- app = Flask('flask_test', root_path=os.path.dirname(__file__))63+ app = Flask("flask_test", root_path=os.path.dirname(__file__))64 return app65 66 67 @pytest.fixture15 unmodified lines83 84 @pytest.fixture85 def test_apps(monkeypatch):86 monkeypatch.syspath_prepend(87- os.path.abspath(os.path.join(88- os.path.dirname(__file__), 'test_apps'))87+ os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))88 )89 90 91 @pytest.fixture(autouse=True)26 unmodified lines118 def __init__(self, loader):119 self.loader = loader120 121 def __getattr__(self, name):123- if name in ('archive', 'get_filename'):124- msg = 'Mocking a loader which does not have `%s.`' % name122+ if name in ("archive", "get_filename"):123+ msg = "Mocking a loader which does not have `%s.`" % name124 raise AttributeError(msg)125 return getattr(self.loader, name)126 127 old_get_loader = pkgutil.get_loader128 129 def get_loader(*args, **kwargs):130 return LimitedLoader(old_get_loader(*args, **kwargs))131 133- monkeypatch.setattr(pkgutil, 'get_loader', get_loader)132+ monkeypatch.setattr(pkgutil, "get_loader", get_loader)133 134 135 @pytest.fixture136 def modules_tmpdir(tmpdir, monkeypatch):137 """A tmpdir added to sys.path."""139- rv = tmpdir.mkdir('modules_tmpdir')138+ rv = tmpdir.mkdir("modules_tmpdir")139 monkeypatch.syspath_prepend(str(rv))140 return rv141 142 143 @pytest.fixture144 def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):146- monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))145+ monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))146 return modules_tmpdir147 148 149 @pytest.fixture150 def site_packages(modules_tmpdir, monkeypatch):151 """Create a fake site-packages."""153- rv = modules_tmpdir \154- .mkdir('lib') \155- .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \156- .mkdir('site-packages')152+ rv = (153+ modules_tmpdir.mkdir("lib")154+ .mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))155+ .mkdir("site-packages")156+ )157 monkeypatch.syspath_prepend(str(rv))158 return rv159 160 5 unmodified lines166 def inner(name, base=modules_tmpdir):167 if not isinstance(name, str):168 raise ValueError(name)169 base.join(name).ensure_dir()170- base.join(name).join('__init__.py').ensure()170+ base.join(name).join("__init__.py").ensure()171 172- egg_setup = base.join('setup.py')173- egg_setup.write(textwrap.dedent("""172+ egg_setup = base.join("setup.py")173+ egg_setup.write(174+ textwrap.dedent(175+ """176 from setuptools import setup177 setup(name='{0}',178 version='1.0',179 packages=['site_egg'],180 zip_safe=True)179- """.format(name)))181+ """.format(182+ name183+ )184+ )185+ )186 187 import subprocess188+189 subprocess.check_call(183- [sys.executable, 'setup.py', 'bdist_egg'],184- cwd=str(modules_tmpdir)190+ [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)191 )186- egg_path, = modules_tmpdir.join('dist/').listdir()192+ egg_path, = modules_tmpdir.join("dist/").listdir()193 monkeypatch.syspath_prepend(str(egg_path))194 return egg_path195 196 return inner10 unmodified lines207 @pytest.fixture(autouse=True)208 def catch_deprecation_warnings(recwarn):209 yield210 gc.collect()205- assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)211+ assert not recwarn.list, "\n".join(str(w.message) for w in recwarn.list)modified:tests/test_appctx.py+43 added-43 removed
13 unmodified lines14 import flask15 16 17 def test_basic_url_generation(app):18- app.config['SERVER_NAME'] = 'localhost'19- app.config['PREFERRED_URL_SCHEME'] = 'https'18+ app.config["SERVER_NAME"] = "localhost"19+ app.config["PREFERRED_URL_SCHEME"] = "https"20 21- @app.route('/')21+ @app.route("/")22 def index():23 pass24 25 with app.app_context():26- rv = flask.url_for('index')27- assert rv == 'https://localhost/'26+ rv = flask.url_for("index")27+ assert rv == "https://localhost/"28 29 30 def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33- flask.url_for('index')33+ flask.url_for("index")34 35 36 def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38- flask.url_for('index')38+ flask.url_for("index")39 40 41 def test_request_context_means_app_context(app):42 with app.test_request_context():27 unmodified lines70 def cleanup(exception):71 cleanup_stuff.append(exception)72 73 try:74- raise Exception('dummy')74+ raise Exception("dummy")75 except Exception:76 pass77 78 with app.app_context():10 unmodified lines89 cleanup_stuff.append(exception)90 91 with app.app_context():92 try:93- raise Exception('dummy')93+ raise Exception("dummy")94 except Exception:95 pass96 97 assert cleanup_stuff == [None]98 99 100 def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):101- app.config['PROPAGATE_EXCEPTIONS'] = True101+ app.config["PROPAGATE_EXCEPTIONS"] = True102 cleanup_stuff = []103 104 @app.teardown_appcontext105 def cleanup(exception):106 cleanup_stuff.append(exception)107 108- @app.route('/')108+ @app.route("/")109 def index():110- raise Exception('dummy')110+ raise Exception("dummy")111 112 @app.errorhandler(Exception)113 def handler(f):114 return flask.jsonify(str(f))115 116 with app.app_context():117- client.get('/')117+ client.get("/")118 119 assert cleanup_stuff == [None]120 121 122 def test_app_tearing_down_with_unhandled_exception(app, client):123- app.config['PROPAGATE_EXCEPTIONS'] = True123+ app.config["PROPAGATE_EXCEPTIONS"] = True124 cleanup_stuff = []125 126 @app.teardown_appcontext127 def cleanup(exception):128 cleanup_stuff.append(exception)129 130- @app.route('/')130+ @app.route("/")131 def index():132- raise Exception('dummy')132+ raise Exception("dummy")133 134 with pytest.raises(Exception):135 with app.app_context():136- client.get('/')136+ client.get("/")137 138 assert len(cleanup_stuff) == 1139 assert isinstance(cleanup_stuff[0], Exception)140- assert str(cleanup_stuff[0]) == 'dummy'140+ assert str(cleanup_stuff[0]) == "dummy"141 142 143 def test_app_ctx_globals_methods(app, app_ctx):144 # get145- assert flask.g.get('foo') is None146- assert flask.g.get('foo', 'bar') == 'bar'145+ assert flask.g.get("foo") is None146+ assert flask.g.get("foo", "bar") == "bar"147 # __contains__148- assert 'foo' not in flask.g149- flask.g.foo = 'bar'150- assert 'foo' in flask.g148+ assert "foo" not in flask.g149+ flask.g.foo = "bar"150+ assert "foo" in flask.g151 # setdefault152- flask.g.setdefault('bar', 'the cake is a lie')153- flask.g.setdefault('bar', 'hello world')154- assert flask.g.bar == 'the cake is a lie'152+ flask.g.setdefault("bar", "the cake is a lie")153+ flask.g.setdefault("bar", "hello world")154+ assert flask.g.bar == "the cake is a lie"155 # pop156- assert flask.g.pop('bar') == 'the cake is a lie'156+ assert flask.g.pop("bar") == "the cake is a lie"157 with pytest.raises(KeyError):158- flask.g.pop('bar')159- assert flask.g.pop('bar', 'more cake') == 'more cake'158+ flask.g.pop("bar")159+ assert flask.g.pop("bar", "more cake") == "more cake"160 # __iter__161- assert list(flask.g) == ['foo']162- #__repr__161+ assert list(flask.g) == ["foo"]162+ # __repr__163 assert repr(flask.g) == "<flask.g of 'flask_test'>"164 165 166 def test_custom_app_ctx_globals_class(app):167 class CustomRequestGlobals(object):168 def __init__(self):169- self.spam = 'eggs'169+ self.spam = "eggs"170 171 app.app_ctx_globals_class = CustomRequestGlobals172 with app.app_context():173- assert flask.render_template_string('{{ g.spam }}') == 'eggs'173+ assert flask.render_template_string("{{ g.spam }}") == "eggs"174 175 176 def test_context_refcounts(app, client):177 called = []178 179 @app.teardown_request180 def teardown_req(error=None):181- called.append('request')181+ called.append("request")182 183 @app.teardown_appcontext184 def teardown_app(error=None):185- called.append('app')185+ called.append("app")186 187- @app.route('/')187+ @app.route("/")188 def index():189 with flask._app_ctx_stack.top:190 with flask._request_ctx_stack.top:191 pass192 env = flask._request_ctx_stack.top.request.environ193- assert env['werkzeug.request'] is not None194- return u''193+ assert env["werkzeug.request"] is not None194+ return u""195 196- res = client.get('/')196+ res = client.get("/")197 assert res.status_code == 200198- assert res.data == b''199- assert called == ['request', 'app']198+ assert res.data == b""199+ assert called == ["request", "app"]200 201 202 def test_clean_pop(app):203 app.testing = False4 unmodified lines208 1 / 0209 210 @app.teardown_appcontext211 def teardown_app(error=None):212- called.append('TEARDOWN')212+ called.append("TEARDOWN")213 214 try:215 with app.test_request_context():216 called.append(flask.current_app.name)217 except ZeroDivisionError:218 pass219 220- assert called == ['flask_test', 'TEARDOWN']220+ assert called == ["flask_test", "TEARDOWN"]221 assert not flask.current_appmodified:tests/test_basic.py+695 added-713 removed
24 unmodified lines25 from flask._compat import text_type26 27 28 def test_options_work(app, client):29- @app.route('/', methods=['GET', 'POST'])29+ @app.route("/", methods=["GET", "POST"])30 def index():31- return 'Hello World'31+ return "Hello World"32 33- rv = client.open('/', method='OPTIONS')34- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35- assert rv.data == b''33+ rv = client.open("/", method="OPTIONS")34+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35+ assert rv.data == b""36 37 38 def test_options_on_multiple_rules(app, client):39- @app.route('/', methods=['GET', 'POST'])39+ @app.route("/", methods=["GET", "POST"])40 def index():41- return 'Hello World'41+ return "Hello World"42 43- @app.route('/', methods=['PUT'])43+ @app.route("/", methods=["PUT"])44 def index_put():45- return 'Aha!'45+ return "Aha!"46 47- rv = client.open('/', method='OPTIONS')48- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']47+ rv = client.open("/", method="OPTIONS")48+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]49 50 51 def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)53 54 def index():55- return 'Hello World!'55+ return "Hello World!"56 57 index.provide_automatic_options = False58- app.route('/')(index)59- rv = app.test_client().open('/', method='OPTIONS')58+ app.route("/")(index)59+ rv = app.test_client().open("/", method="OPTIONS")60 assert rv.status_code == 40561 62 app = flask.Flask(__name__)63 64 def index2():65- return 'Hello World!'65+ return "Hello World!"66 67 index2.provide_automatic_options = True68- app.route('/', methods=['OPTIONS'])(index2)69- rv = app.test_client().open('/', method='OPTIONS')70- assert sorted(rv.allow) == ['OPTIONS']68+ app.route("/", methods=["OPTIONS"])(index2)69+ rv = app.test_client().open("/", method="OPTIONS")70+ assert sorted(rv.allow) == ["OPTIONS"]71 72 73 def test_provide_automatic_options_kwarg(app, client):74 def index():1 unmodified line76 77 def more():78 return flask.request.method79 80- app.add_url_rule('/', view_func=index, provide_automatic_options=False)80+ app.add_url_rule("/", view_func=index, provide_automatic_options=False)81 app.add_url_rule(82- '/more', view_func=more, methods=['GET', 'POST'],83- provide_automatic_options=False82+ "/more",83+ view_func=more,84+ methods=["GET", "POST"],85+ provide_automatic_options=False,86 )85- assert client.get('/').data == b'GET'87+ assert client.get("/").data == b"GET"88 87- rv = client.post('/')89+ rv = client.post("/")90 assert rv.status_code == 40589- assert sorted(rv.allow) == ['GET', 'HEAD']91+ assert sorted(rv.allow) == ["GET", "HEAD"]92 93 # Older versions of Werkzeug.test.Client don't have an options method92- if hasattr(client, 'options'):93- rv = client.options('/')94+ if hasattr(client, "options"):95+ rv = client.options("/")96 else:95- rv = client.open('/', method='OPTIONS')97+ rv = client.open("/", method="OPTIONS")98 99 assert rv.status_code == 405100 99- rv = client.head('/')101+ rv = client.head("/")102 assert rv.status_code == 200103 assert not rv.data # head truncates102- assert client.post('/more').data == b'POST'103- assert client.get('/more').data == b'GET'104+ assert client.post("/more").data == b"POST"105+ assert client.get("/more").data == b"GET"106 105- rv = client.delete('/more')107+ rv = client.delete("/more")108 assert rv.status_code == 405107- assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109+ assert sorted(rv.allow) == ["GET", "HEAD", "POST"]110 109- if hasattr(client, 'options'):110- rv = client.options('/more')111+ if hasattr(client, "options"):112+ rv = client.options("/more")113 else:112- rv = client.open('/more', method='OPTIONS')114+ rv = client.open("/more", method="OPTIONS")115 116 assert rv.status_code == 405117 118 119 def test_request_dispatching(app, client):118- @app.route('/')120+ @app.route("/")121 def index():122 return flask.request.method123 122- @app.route('/more', methods=['GET', 'POST'])124+ @app.route("/more", methods=["GET", "POST"])125 def more():126 return flask.request.method127 126- assert client.get('/').data == b'GET'127- rv = client.post('/')128+ assert client.get("/").data == b"GET"129+ rv = client.post("/")130 assert rv.status_code == 405129- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']130- rv = client.head('/')131+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]132+ rv = client.head("/")133 assert rv.status_code == 200134 assert not rv.data # head truncates133- assert client.post('/more').data == b'POST'134- assert client.get('/more').data == b'GET'135- rv = client.delete('/more')135+ assert client.post("/more").data == b"POST"136+ assert client.get("/more").data == b"GET"137+ rv = client.delete("/more")138 assert rv.status_code == 405137- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]140 141 142 def test_disallow_string_for_allowed_methods(app):143 with pytest.raises(TypeError):142- @app.route('/', methods='GET POST')144+145+ @app.route("/", methods="GET POST")146 def index():147 return "Hey"148 149 8 unmodified lines158 159 def options():160 return random_uuid4161 159- app.add_url_rule('/', 'index', index)160- app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162+ app.add_url_rule("/", "index", index)163+ app.add_url_rule("/more", "more", more, methods=["GET", "POST"])164 165 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163- app.add_url_rule('/options', 'options', options, methods=['options'])166+ app.add_url_rule("/options", "options", options, methods=["options"])167 165- assert client.get('/').data == b'GET'166- rv = client.post('/')168+ assert client.get("/").data == b"GET"169+ rv = client.post("/")170 assert rv.status_code == 405168- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']169- rv = client.head('/')171+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]172+ rv = client.head("/")173 assert rv.status_code == 200174 assert not rv.data # head truncates172- assert client.post('/more').data == b'POST'173- assert client.get('/more').data == b'GET'174- rv = client.delete('/more')175+ assert client.post("/more").data == b"POST"176+ assert client.get("/more").data == b"GET"177+ rv = client.delete("/more")178 assert rv.status_code == 405176- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']177- rv = client.open('/options', method='OPTIONS')179+ assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]180+ rv = client.open("/options", method="OPTIONS")181 assert rv.status_code == 200182 assert random_uuid4 in rv.data.decode("utf-8")183 184 185 def test_werkzeug_routing(app, client):186 from werkzeug.routing import Submount, Rule184- app.url_map.add(Submount('/foo', [185- Rule('/bar', endpoint='bar'),186- Rule('/', endpoint='index')187- ]))187 188+ app.url_map.add(189+ Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])190+ )191+192 def bar():190- return 'bar'193+ return "bar"194 195 def index():193- return 'index'196+ return "index"197 195- app.view_functions['bar'] = bar196- app.view_functions['index'] = index198+ app.view_functions["bar"] = bar199+ app.view_functions["index"] = index200 198- assert client.get('/foo/').data == b'index'199- assert client.get('/foo/bar').data == b'bar'201+ assert client.get("/foo/").data == b"index"202+ assert client.get("/foo/bar").data == b"bar"203 204 205 def test_endpoint_decorator(app, client):206 from werkzeug.routing import Submount, Rule204- app.url_map.add(Submount('/foo', [205- Rule('/bar', endpoint='bar'),206- Rule('/', endpoint='index')207- ]))207 208+ app.url_map.add(209+ Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])210+ )211+209- @app.endpoint('bar')212+ @app.endpoint("bar")213 def bar():211- return 'bar'214+ return "bar"215 213- @app.endpoint('index')216+ @app.endpoint("index")217 def index():215- return 'index'218+ return "index"219 217- assert client.get('/foo/').data == b'index'218- assert client.get('/foo/bar').data == b'bar'220+ assert client.get("/foo/").data == b"index"221+ assert client.get("/foo/bar").data == b"bar"222 223 224 def test_session(app, client):222- @app.route('/set', methods=['POST'])225+ @app.route("/set", methods=["POST"])226 def set():227 assert not flask.session.accessed228 assert not flask.session.modified226- flask.session['value'] = flask.request.form['value']229+ flask.session["value"] = flask.request.form["value"]230 assert flask.session.accessed231 assert flask.session.modified229- return 'value set'232+ return "value set"233 231- @app.route('/get')234+ @app.route("/get")235 def get():236 assert not flask.session.accessed237 assert not flask.session.modified235- v = flask.session.get('value', 'None')238+ v = flask.session.get("value", "None")239 assert flask.session.accessed240 assert not flask.session.modified241 return v242 240- assert client.post('/set', data={'value': '42'}).data == b'value set'241- assert client.get('/get').data == b'42'243+ assert client.post("/set", data={"value": "42"}).data == b"value set"244+ assert client.get("/get").data == b"42"245 246 247 def test_session_using_server_name(app, client):245- app.config.update(246- SERVER_NAME='example.com'247- )248+ app.config.update(SERVER_NAME="example.com")249 249- @app.route('/')250+ @app.route("/")251 def index():251- flask.session['testing'] = 42252- return 'Hello World'252+ flask.session["testing"] = 42253+ return "Hello World"254 254- rv = client.get('/', 'http://example.com/')255- assert 'domain=.example.com' in rv.headers['set-cookie'].lower()256- assert 'httponly' in rv.headers['set-cookie'].lower()255+ rv = client.get("/", "http://example.com/")256+ assert "domain=.example.com" in rv.headers["set-cookie"].lower()257+ assert "httponly" in rv.headers["set-cookie"].lower()258 259 260 def test_session_using_server_name_and_port(app, client):260- app.config.update(261- SERVER_NAME='example.com:8080'262- )261+ app.config.update(SERVER_NAME="example.com:8080")262 264- @app.route('/')263+ @app.route("/")264 def index():266- flask.session['testing'] = 42267- return 'Hello World'265+ flask.session["testing"] = 42266+ return "Hello World"267 269- rv = client.get('/', 'http://example.com:8080/')270- assert 'domain=.example.com' in rv.headers['set-cookie'].lower()271- assert 'httponly' in rv.headers['set-cookie'].lower()268+ rv = client.get("/", "http://example.com:8080/")269+ assert "domain=.example.com" in rv.headers["set-cookie"].lower()270+ assert "httponly" in rv.headers["set-cookie"].lower()271 272 273 def test_session_using_server_name_port_and_path(app, client):275- app.config.update(276- SERVER_NAME='example.com:8080',277- APPLICATION_ROOT='/foo'278- )274+ app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")275 280- @app.route('/')276+ @app.route("/")277 def index():282- flask.session['testing'] = 42283- return 'Hello World'278+ flask.session["testing"] = 42279+ return "Hello World"280 285- rv = client.get('/', 'http://example.com:8080/foo')286- assert 'domain=example.com' in rv.headers['set-cookie'].lower()287- assert 'path=/foo' in rv.headers['set-cookie'].lower()288- assert 'httponly' in rv.headers['set-cookie'].lower()281+ rv = client.get("/", "http://example.com:8080/foo")282+ assert "domain=example.com" in rv.headers["set-cookie"].lower()283+ assert "path=/foo" in rv.headers["set-cookie"].lower()284+ assert "httponly" in rv.headers["set-cookie"].lower()285 286 287 def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):1 unmodified line290 self.app = app291 self.prefix = prefix292 293 def __call__(self, environ, start_response):298- environ['SCRIPT_NAME'] = self.prefix294+ environ["SCRIPT_NAME"] = self.prefix295 return self.app(environ, start_response)296 301- app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')302- app.config.update(303- APPLICATION_ROOT='/bar'304- )297+ app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")298+ app.config.update(APPLICATION_ROOT="/bar")299 306- @app.route('/')300+ @app.route("/")301 def index():308- flask.session['testing'] = 42309- return 'Hello World'302+ flask.session["testing"] = 42303+ return "Hello World"304 311- rv = client.get('/', 'http://example.com:8080/')312- assert 'path=/bar' in rv.headers['set-cookie'].lower()305+ rv = client.get("/", "http://example.com:8080/")306+ assert "path=/bar" in rv.headers["set-cookie"].lower()307 308 309 def test_session_using_session_settings(app, client):310 app.config.update(317- SERVER_NAME='www.example.com:8080',318- APPLICATION_ROOT='/test',319- SESSION_COOKIE_DOMAIN='.example.com',311+ SERVER_NAME="www.example.com:8080",312+ APPLICATION_ROOT="/test",313+ SESSION_COOKIE_DOMAIN=".example.com",314 SESSION_COOKIE_HTTPONLY=False,315 SESSION_COOKIE_SECURE=True,322- SESSION_COOKIE_SAMESITE='Lax',323- SESSION_COOKIE_PATH='/'316+ SESSION_COOKIE_SAMESITE="Lax",317+ SESSION_COOKIE_PATH="/",318 )319 326- @app.route('/')320+ @app.route("/")321 def index():328- flask.session['testing'] = 42329- return 'Hello World'322+ flask.session["testing"] = 42323+ return "Hello World"324 331- rv = client.get('/', 'http://www.example.com:8080/test/')332- cookie = rv.headers['set-cookie'].lower()333- assert 'domain=.example.com' in cookie334- assert 'path=/' in cookie335- assert 'secure' in cookie336- assert 'httponly' not in cookie337- assert 'samesite' in cookie325+ rv = client.get("/", "http://www.example.com:8080/test/")326+ cookie = rv.headers["set-cookie"].lower()327+ assert "domain=.example.com" in cookie328+ assert "path=/" in cookie329+ assert "secure" in cookie330+ assert "httponly" not in cookie331+ assert "samesite" in cookie332 333 334 def test_session_using_samesite_attribute(app, client):341- @app.route('/')335+ @app.route("/")336 def index():343- flask.session['testing'] = 42344- return 'Hello World'337+ flask.session["testing"] = 42338+ return "Hello World"339 346- app.config.update(SESSION_COOKIE_SAMESITE='invalid')340+ app.config.update(SESSION_COOKIE_SAMESITE="invalid")341 342 with pytest.raises(ValueError):349- client.get('/')343+ client.get("/")344 345 app.config.update(SESSION_COOKIE_SAMESITE=None)352- rv = client.get('/')353- cookie = rv.headers['set-cookie'].lower()354- assert 'samesite' not in cookie346+ rv = client.get("/")347+ cookie = rv.headers["set-cookie"].lower()348+ assert "samesite" not in cookie349 356- app.config.update(SESSION_COOKIE_SAMESITE='Strict')357- rv = client.get('/')358- cookie = rv.headers['set-cookie'].lower()359- assert 'samesite=strict' in cookie350+ app.config.update(SESSION_COOKIE_SAMESITE="Strict")351+ rv = client.get("/")352+ cookie = rv.headers["set-cookie"].lower()353+ assert "samesite=strict" in cookie354 361- app.config.update(SESSION_COOKIE_SAMESITE='Lax')362- rv = client.get('/')363- cookie = rv.headers['set-cookie'].lower()364- assert 'samesite=lax' in cookie355+ app.config.update(SESSION_COOKIE_SAMESITE="Lax")356+ rv = client.get("/")357+ cookie = rv.headers["set-cookie"].lower()358+ assert "samesite=lax" in cookie359 360 361 def test_session_localhost_warning(recwarn, app, client):368- app.config.update(369- SERVER_NAME='localhost:5000',370- )362+ app.config.update(SERVER_NAME="localhost:5000")363 372- @app.route('/')364+ @app.route("/")365 def index():374- flask.session['testing'] = 42375- return 'testing'366+ flask.session["testing"] = 42367+ return "testing"368 377- rv = client.get('/', 'http://localhost:5000/')378- assert 'domain' not in rv.headers['set-cookie'].lower()369+ rv = client.get("/", "http://localhost:5000/")370+ assert "domain" not in rv.headers["set-cookie"].lower()371 w = recwarn.pop(UserWarning)372 assert '"localhost" is not a valid cookie domain' in str(w.message)373 374 375 def test_session_ip_warning(recwarn, app, client):384- app.config.update(385- SERVER_NAME='127.0.0.1:5000',386- )376+ app.config.update(SERVER_NAME="127.0.0.1:5000")377 388- @app.route('/')378+ @app.route("/")379 def index():390- flask.session['testing'] = 42391- return 'testing'380+ flask.session["testing"] = 42381+ return "testing"382 393- rv = client.get('/', 'http://127.0.0.1:5000/')394- assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()383+ rv = client.get("/", "http://127.0.0.1:5000/")384+ assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()385 w = recwarn.pop(UserWarning)396- assert 'cookie domain is an IP' in str(w.message)386+ assert "cookie domain is an IP" in str(w.message)387 388 389 def test_missing_session(app):390 app.secret_key = None391 392 def expect_exception(f, *args, **kwargs):393 e = pytest.raises(RuntimeError, f, *args, **kwargs)404- assert e.value.args and 'session is unavailable' in e.value.args[0]394+ assert e.value.args and "session is unavailable" in e.value.args[0]395 396 with app.test_request_context():407- assert flask.session.get('missing_key') is None408- expect_exception(flask.session.__setitem__, 'foo', 42)409- expect_exception(flask.session.pop, 'foo')397+ assert flask.session.get("missing_key") is None398+ expect_exception(flask.session.__setitem__, "foo", 42)399+ expect_exception(flask.session.pop, "foo")400 401 402 def test_session_expiration(app, client):403 permanent = True404 415- @app.route('/')405+ @app.route("/")406 def index():417- flask.session['test'] = 42407+ flask.session["test"] = 42408 flask.session.permanent = permanent419- return ''409+ return ""410 421- @app.route('/test')411+ @app.route("/test")412 def test():413 return text_type(flask.session.permanent)414 425- rv = client.get('/')426- assert 'set-cookie' in rv.headers427- match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])415+ rv = client.get("/")416+ assert "set-cookie" in rv.headers417+ match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])418 expires = parse_date(match.group())419 expected = datetime.utcnow() + app.permanent_session_lifetime420 assert expires.year == expected.year421 assert expires.month == expected.month422 assert expires.day == expected.day423 434- rv = client.get('/test')435- assert rv.data == b'True'424+ rv = client.get("/test")425+ assert rv.data == b"True"426 427 permanent = False438- rv = client.get('/')439- assert 'set-cookie' in rv.headers440- match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])428+ rv = client.get("/")429+ assert "set-cookie" in rv.headers430+ match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])431 assert match is None432 433 434 def test_session_stored_last(app, client):435 @app.after_request436 def modify_session(response):447- flask.session['foo'] = 42437+ flask.session["foo"] = 42438 return response439 450- @app.route('/')440+ @app.route("/")441 def dump_session_contents():452- return repr(flask.session.get('foo'))442+ return repr(flask.session.get("foo"))443 454- assert client.get('/').data == b'None'455- assert client.get('/').data == b'42'444+ assert client.get("/").data == b"None"445+ assert client.get("/").data == b"42"446 447 448 def test_session_special_types(app, client):449 now = datetime.utcnow().replace(microsecond=0)450 the_uuid = uuid.uuid4()451 462- @app.route('/')452+ @app.route("/")453 def dump_session_contents():464- flask.session['t'] = (1, 2, 3)465- flask.session['b'] = b'\xff'466- flask.session['m'] = flask.Markup('<html>')467- flask.session['u'] = the_uuid468- flask.session['d'] = now469- flask.session['t_tag'] = {' t': 'not-a-tuple'}470- flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}471- flask.session['di_tag'] = {' di': 'not-a-dict'}472- return '', 204454+ flask.session["t"] = (1, 2, 3)455+ flask.session["b"] = b"\xff"456+ flask.session["m"] = flask.Markup("<html>")457+ flask.session["u"] = the_uuid458+ flask.session["d"] = now459+ flask.session["t_tag"] = {" t": "not-a-tuple"}460+ flask.session["di_t_tag"] = {" t__": "not-a-tuple"}461+ flask.session["di_tag"] = {" di": "not-a-dict"}462+ return "", 204463 464 with client:475- client.get('/')465+ client.get("/")466 s = flask.session477- assert s['t'] == (1, 2, 3)478- assert type(s['b']) == bytes479- assert s['b'] == b'\xff'480- assert type(s['m']) == flask.Markup481- assert s['m'] == flask.Markup('<html>')482- assert s['u'] == the_uuid483- assert s['d'] == now484- assert s['t_tag'] == {' t': 'not-a-tuple'}485- assert s['di_t_tag'] == {' t__': 'not-a-tuple'}486- assert s['di_tag'] == {' di': 'not-a-dict'}467+ assert s["t"] == (1, 2, 3)468+ assert type(s["b"]) == bytes469+ assert s["b"] == b"\xff"470+ assert type(s["m"]) == flask.Markup471+ assert s["m"] == flask.Markup("<html>")472+ assert s["u"] == the_uuid473+ assert s["d"] == now474+ assert s["t_tag"] == {" t": "not-a-tuple"}475+ assert s["di_t_tag"] == {" t__": "not-a-tuple"}476+ assert s["di_tag"] == {" di": "not-a-dict"}477 478 479 def test_session_cookie_setting(app):480 is_permanent = True481 492- @app.route('/bump')482+ @app.route("/bump")483 def bump():494- rv = flask.session['foo'] = flask.session.get('foo', 0) + 1484+ rv = flask.session["foo"] = flask.session.get("foo", 0) + 1485 flask.session.permanent = is_permanent486 return str(rv)487 498- @app.route('/read')488+ @app.route("/read")489 def read():500- return str(flask.session.get('foo', 0))490+ return str(flask.session.get("foo", 0))491 492 def run_test(expect_header):493 with app.test_client() as c:504- assert c.get('/bump').data == b'1'505- assert c.get('/bump').data == b'2'506- assert c.get('/bump').data == b'3'494+ assert c.get("/bump").data == b"1"495+ assert c.get("/bump").data == b"2"496+ assert c.get("/bump").data == b"3"497 508- rv = c.get('/read')509- set_cookie = rv.headers.get('set-cookie')498+ rv = c.get("/read")499+ set_cookie = rv.headers.get("set-cookie")500 assert (set_cookie is not None) == expect_header511- assert rv.data == b'3'501+ assert rv.data == b"3"502 503 is_permanent = True514- app.config['SESSION_REFRESH_EACH_REQUEST'] = True504+ app.config["SESSION_REFRESH_EACH_REQUEST"] = True505 run_test(expect_header=True)506 507 is_permanent = True518- app.config['SESSION_REFRESH_EACH_REQUEST'] = False508+ app.config["SESSION_REFRESH_EACH_REQUEST"] = False509 run_test(expect_header=False)510 511 is_permanent = False522- app.config['SESSION_REFRESH_EACH_REQUEST'] = True512+ app.config["SESSION_REFRESH_EACH_REQUEST"] = True513 run_test(expect_header=False)514 515 is_permanent = False526- app.config['SESSION_REFRESH_EACH_REQUEST'] = False516+ app.config["SESSION_REFRESH_EACH_REQUEST"] = False517 run_test(expect_header=False)518 519 520 def test_session_vary_cookie(app, client):531- @app.route('/set')521+ @app.route("/set")522 def set_session():533- flask.session['test'] = 'test'534- return ''523+ flask.session["test"] = "test"524+ return ""525 536- @app.route('/get')526+ @app.route("/get")527 def get():538- return flask.session.get('test')528+ return flask.session.get("test")529 540- @app.route('/getitem')530+ @app.route("/getitem")531 def getitem():542- return flask.session['test']532+ return flask.session["test"]533 544- @app.route('/setdefault')534+ @app.route("/setdefault")535 def setdefault():546- return flask.session.setdefault('test', 'default')536+ return flask.session.setdefault("test", "default")537 548- @app.route('/vary-cookie-header-set')538+ @app.route("/vary-cookie-header-set")539 def vary_cookie_header_set():540 response = flask.Response()551- response.vary.add('Cookie')552- flask.session['test'] = 'test'541+ response.vary.add("Cookie")542+ flask.session["test"] = "test"543 return response544 555- @app.route('/vary-header-set')545+ @app.route("/vary-header-set")546 def vary_header_set():547 response = flask.Response()558- response.vary.update(('Accept-Encoding', 'Accept-Language'))559- flask.session['test'] = 'test'548+ response.vary.update(("Accept-Encoding", "Accept-Language"))549+ flask.session["test"] = "test"550 return response551 562- @app.route('/no-vary-header')552+ @app.route("/no-vary-header")553 def no_vary_header():564- return ''554+ return ""555 566- def expect(path, header_value='Cookie'):556+ def expect(path, header_value="Cookie"):557 rv = client.get(path)558 559 if header_value:560 # The 'Vary' key should exist in the headers only once.571- assert len(rv.headers.get_all('Vary')) == 1572- assert rv.headers['Vary'] == header_value561+ assert len(rv.headers.get_all("Vary")) == 1562+ assert rv.headers["Vary"] == header_value563 else:574- assert 'Vary' not in rv.headers564+ assert "Vary" not in rv.headers565 576- expect('/set')577- expect('/get')578- expect('/getitem')579- expect('/setdefault')580- expect('/vary-cookie-header-set')581- expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')582- expect('/no-vary-header', None)566+ expect("/set")567+ expect("/get")568+ expect("/getitem")569+ expect("/setdefault")570+ expect("/vary-cookie-header-set")571+ expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")572+ expect("/no-vary-header", None)573 574 575 def test_flashes(app, req_ctx):576 assert not flask.session.modified587- flask.flash('Zap')577+ flask.flash("Zap")578 flask.session.modified = False589- flask.flash('Zip')579+ flask.flash("Zip")580 assert flask.session.modified591- assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']581+ assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]582 583 584 def test_extended_flashing(app):585 # Be sure app.testing=True below, else tests can fail silently.1 unmodified line587 # Specifically, if app.testing is not set to True, the AssertionErrors588 # in the view functions will cause a 500 response to the test client589 # instead of propagating exceptions.590 601- @app.route('/')591+ @app.route("/")592 def index():603- flask.flash(u'Hello World')604- flask.flash(u'Hello World', 'error')605- flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')606- return ''593+ flask.flash(u"Hello World")594+ flask.flash(u"Hello World", "error")595+ flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")596+ return ""597 608- @app.route('/test/')598+ @app.route("/test/")599 def test():600 messages = flask.get_flashed_messages()601 assert list(messages) == [612- u'Hello World',613- u'Hello World',614- flask.Markup(u'<em>Testing</em>')602+ u"Hello World",603+ u"Hello World",604+ flask.Markup(u"<em>Testing</em>"),605 ]616- return ''606+ return ""607 618- @app.route('/test_with_categories/')608+ @app.route("/test_with_categories/")609 def test_with_categories():610 messages = flask.get_flashed_messages(with_categories=True)611 assert len(messages) == 3612 assert list(messages) == [623- ('message', u'Hello World'),624- ('error', u'Hello World'),625- ('warning', flask.Markup(u'<em>Testing</em>'))613+ ("message", u"Hello World"),614+ ("error", u"Hello World"),615+ ("warning", flask.Markup(u"<em>Testing</em>")),616 ]627- return ''617+ return ""618 629- @app.route('/test_filter/')619+ @app.route("/test_filter/")620 def test_filter():621 messages = flask.get_flashed_messages(632- category_filter=['message'], with_categories=True)633- assert list(messages) == [('message', u'Hello World')]634- return ''622+ category_filter=["message"], with_categories=True623+ )624+ assert list(messages) == [("message", u"Hello World")]625+ return ""626 636- @app.route('/test_filters/')627+ @app.route("/test_filters/")628 def test_filters():629 messages = flask.get_flashed_messages(639- category_filter=['message', 'warning'], with_categories=True)630+ category_filter=["message", "warning"], with_categories=True631+ )632 assert list(messages) == [641- ('message', u'Hello World'),642- ('warning', flask.Markup(u'<em>Testing</em>'))633+ ("message", u"Hello World"),634+ ("warning", flask.Markup(u"<em>Testing</em>")),635 ]644- return ''636+ return ""637 646- @app.route('/test_filters_without_returning_categories/')638+ @app.route("/test_filters_without_returning_categories/")639 def test_filters2():648- messages = flask.get_flashed_messages(649- category_filter=['message', 'warning'])640+ messages = flask.get_flashed_messages(category_filter=["message", "warning"])641 assert len(messages) == 2651- assert messages[0] == u'Hello World'652- assert messages[1] == flask.Markup(u'<em>Testing</em>')653- return ''642+ assert messages[0] == u"Hello World"643+ assert messages[1] == flask.Markup(u"<em>Testing</em>")644+ return ""645 646 # Create new test client on each test to clean flashed messages.647 648 client = app.test_client()658- client.get('/')659- client.get('/test_with_categories/')649+ client.get("/")650+ client.get("/test_with_categories/")651 652 client = app.test_client()662- client.get('/')663- client.get('/test_filter/')653+ client.get("/")654+ client.get("/test_filter/")655 656 client = app.test_client()666- client.get('/')667- client.get('/test_filters/')657+ client.get("/")658+ client.get("/test_filters/")659 660 client = app.test_client()670- client.get('/')671- client.get('/test_filters_without_returning_categories/')661+ client.get("/")662+ client.get("/test_filters_without_returning_categories/")663 664 665 def test_request_processing(app, client):666 evts = []667 668 @app.before_request669 def before_request():679- evts.append('before')670+ evts.append("before")671 672 @app.after_request673 def after_request(response):683- response.data += b'|after'684- evts.append('after')674+ response.data += b"|after"675+ evts.append("after")676 return response677 687- @app.route('/')678+ @app.route("/")679 def index():689- assert 'before' in evts690- assert 'after' not in evts691- return 'request'680+ assert "before" in evts681+ assert "after" not in evts682+ return "request"683 693- assert 'after' not in evts694- rv = client.get('/').data695- assert 'after' in evts696- assert rv == b'request|after'684+ assert "after" not in evts685+ rv = client.get("/").data686+ assert "after" in evts687+ assert rv == b"request|after"688 689 690 def test_request_preprocessing_early_return(app, client):691 evts = []11 unmodified lines703 def before_request3():704 evts.append(3)705 return "bye"706 716- @app.route('/')707+ @app.route("/")708 def index():718- evts.append('index')709+ evts.append("index")710 return "damnit"711 721- rv = client.get('/').data.strip()722- assert rv == b'hello'712+ rv = client.get("/").data.strip()713+ assert rv == b"hello"714 assert evts == [1, 2]715 716 717 def test_after_request_processing(app, client):727- @app.route('/')718+ @app.route("/")719 def index():720 @flask.after_this_request721 def foo(response):731- response.headers['X-Foo'] = 'a header'722+ response.headers["X-Foo"] = "a header"723 return response724 734- return 'Test'725+ return "Test"726 736- resp = client.get('/')727+ resp = client.get("/")728 assert resp.status_code == 200738- assert resp.headers['X-Foo'] == 'a header'729+ assert resp.headers["X-Foo"] == "a header"730 731 732 def test_teardown_request_handler(app, client):733 called = []2 unmodified lines736 def teardown_request(exc):737 called.append(True)738 return "Ignored"739 749- @app.route('/')740+ @app.route("/")741 def root():742 return "Response"743 753- rv = client.get('/')744+ rv = client.get("/")745 assert rv.status_code == 200755- assert b'Response' in rv.data746+ assert b"Response" in rv.data747 assert len(called) == 1748 749 750 def test_teardown_request_handler_debug_mode(app, client):3 unmodified lines754 def teardown_request(exc):755 called.append(True)756 return "Ignored"757 767- @app.route('/')758+ @app.route("/")759 def root():760 return "Response"761 771- rv = client.get('/')762+ rv = client.get("/")763 assert rv.status_code == 200773- assert b'Response' in rv.data764+ assert b"Response" in rv.data765 assert len(called) == 1766 767 768 def test_teardown_request_handler_error(app, client):23 unmodified lines792 raise TypeError()793 except:794 pass795 805- @app.route('/')796+ @app.route("/")797 def fails():798 1 // 0799 809- rv = client.get('/')800+ rv = client.get("/")801 assert rv.status_code == 500811- assert b'Internal Server Error' in rv.data802+ assert b"Internal Server Error" in rv.data803 assert len(called) == 2804 805 806 def test_before_after_request_order(app, client):24 unmodified lines831 @app.teardown_request832 def finish2(exc):833 called.append(5)834 844- @app.route('/')835+ @app.route("/")836 def index():846- return '42'837+ return "42"838 848- rv = client.get('/')849- assert rv.data == b'42'839+ rv = client.get("/")840+ assert rv.data == b"42"841 assert called == [1, 2, 3, 4, 5, 6]842 843 844 def test_error_handling(app, client):845 app.testing = False846 847 @app.errorhandler(404)848 def not_found(e):858- return 'not found', 404849+ return "not found", 404850 851 @app.errorhandler(500)852 def internal_server_error(e):862- return 'internal server error', 500853+ return "internal server error", 500854 855 @app.errorhandler(Forbidden)856 def forbidden(e):866- return 'forbidden', 403857+ return "forbidden", 403858 868- @app.route('/')859+ @app.route("/")860 def index():861 flask.abort(404)862 872- @app.route('/error')863+ @app.route("/error")864 def error():865 1 // 0866 876- @app.route('/forbidden')867+ @app.route("/forbidden")868 def error2():869 flask.abort(403)870 880- rv = client.get('/')871+ rv = client.get("/")872 assert rv.status_code == 404882- assert rv.data == b'not found'883- rv = client.get('/error')873+ assert rv.data == b"not found"874+ rv = client.get("/error")875 assert rv.status_code == 500885- assert b'internal server error' == rv.data886- rv = client.get('/forbidden')876+ assert b"internal server error" == rv.data877+ rv = client.get("/forbidden")878 assert rv.status_code == 403888- assert b'forbidden' == rv.data879+ assert b"forbidden" == rv.data880 881 882 def test_error_handler_unknown_code(app):883 with pytest.raises(KeyError) as exc_info:893- app.register_error_handler(999, lambda e: ('999', 999))884+ app.register_error_handler(999, lambda e: ("999", 999))885 895- assert 'Use a subclass' in exc_info.value.args[0]886+ assert "Use a subclass" in exc_info.value.args[0]887 888 889 def test_error_handling_processing(app, client):890 app.testing = False891 892 @app.errorhandler(500)893 def internal_server_error(e):903- return 'internal server error', 500894+ return "internal server error", 500895 905- @app.route('/')896+ @app.route("/")897 def broken_func():898 1 // 0899 900 @app.after_request901 def after_request(resp):911- resp.mimetype = 'text/x-special'902+ resp.mimetype = "text/x-special"903 return resp904 914- resp = client.get('/')915- assert resp.mimetype == 'text/x-special'916- assert resp.data == b'internal server error'905+ resp = client.get("/")906+ assert resp.mimetype == "text/x-special"907+ assert resp.data == b"internal server error"908 909 910 def test_baseexception_error_handling(app, client):911 app.testing = False912 922- @app.route('/')913+ @app.route("/")914 def broken_func():915 raise KeyboardInterrupt()916 917 with pytest.raises(KeyboardInterrupt):927- client.get('/')918+ client.get("/")919 920 ctx = flask._request_ctx_stack.top921 assert ctx.preserved922 assert type(ctx._preserved_exc) is KeyboardInterrupt1 unmodified line924 925 def test_before_request_and_routing_errors(app, client):926 @app.before_request927 def attach_something():937- flask.g.something = 'value'928+ flask.g.something = "value"929 930 @app.errorhandler(404)931 def return_something(error):932 return flask.g.something, 404933 943- rv = client.get('/')934+ rv = client.get("/")935 assert rv.status_code == 404945- assert rv.data == b'value'936+ assert rv.data == b"value"937 938 939 def test_user_error_handling(app, client):940 class MyException(Exception):1 unmodified line942 943 @app.errorhandler(MyException)944 def handle_my_exception(e):945 assert isinstance(e, MyException)955- return '42'946+ return "42"947 957- @app.route('/')948+ @app.route("/")949 def index():950 raise MyException()951 961- assert client.get('/').data == b'42'952+ assert client.get("/").data == b"42"953 954 955 def test_http_error_subclass_handling(app, client):956 class ForbiddenSubclass(Forbidden):1 unmodified line958 959 @app.errorhandler(ForbiddenSubclass)960 def handle_forbidden_subclass(e):961 assert isinstance(e, ForbiddenSubclass)971- return 'banana'962+ return "banana"963 964 @app.errorhandler(403)965 def handle_forbidden_subclass(e):966 assert not isinstance(e, ForbiddenSubclass)967 assert isinstance(e, Forbidden)977- return 'apple'968+ return "apple"969 979- @app.route('/1')970+ @app.route("/1")971 def index1():972 raise ForbiddenSubclass()973 983- @app.route('/2')974+ @app.route("/2")975 def index2():976 flask.abort(403)977 987- @app.route('/3')978+ @app.route("/3")979 def index3():980 raise Forbidden()981 991- assert client.get('/1').data == b'banana'992- assert client.get('/2').data == b'apple'993- assert client.get('/3').data == b'apple'982+ assert client.get("/1").data == b"banana"983+ assert client.get("/2").data == b"apple"984+ assert client.get("/3").data == b"apple"985 986 987 def test_errorhandler_precedence(app, client):988 class E1(Exception):6 unmodified lines995 pass996 997 @app.errorhandler(E2)998 def handle_e2(e):1008- return 'E2'999+ return "E2"1000 1001 @app.errorhandler(Exception)1002 def handle_exception(e):1012- return 'Exception'1003+ return "Exception"1004 1014- @app.route('/E1')1005+ @app.route("/E1")1006 def raise_e1():1007 raise E11008 1018- @app.route('/E3')1009+ @app.route("/E3")1010 def raise_e3():1011 raise E31012 1022- rv = client.get('/E1')1023- assert rv.data == b'Exception'1013+ rv = client.get("/E1")1014+ assert rv.data == b"Exception"1015 1025- rv = client.get('/E3')1026- assert rv.data == b'E2'1016+ rv = client.get("/E3")1017+ assert rv.data == b"E2"1018 1019 1020 def test_trapping_of_bad_request_key_errors(app, client):1030- @app.route('/key')1021+ @app.route("/key")1022 def fail():1032- flask.request.form['missing_key']1023+ flask.request.form["missing_key"]1024 1034- @app.route('/abort')1025+ @app.route("/abort")1026 def allow_abort():1027 flask.abort(400)1028 1038- rv = client.get('/key')1029+ rv = client.get("/key")1030 assert rv.status_code == 4001040- assert b'missing_key' not in rv.data1041- rv = client.get('/abort')1031+ assert b"missing_key" not in rv.data1032+ rv = client.get("/abort")1033 assert rv.status_code == 4001034 1035 app.debug = True1036 with pytest.raises(KeyError) as e:1037 client.get("/key")1038 assert e.errisinstance(BadRequest)1048- assert 'missing_key' in e.value.get_description()1049- rv = client.get('/abort')1039+ assert "missing_key" in e.value.get_description()1040+ rv = client.get("/abort")1041 assert rv.status_code == 4001042 1043 app.debug = False1053- app.config['TRAP_BAD_REQUEST_ERRORS'] = True1044+ app.config["TRAP_BAD_REQUEST_ERRORS"] = True1045 with pytest.raises(KeyError):1055- client.get('/key')1046+ client.get("/key")1047 with pytest.raises(BadRequest):1057- client.get('/abort')1048+ client.get("/abort")1049 1050 1051 def test_trapping_of_all_http_exceptions(app, client):1061- app.config['TRAP_HTTP_EXCEPTIONS'] = True1052+ app.config["TRAP_HTTP_EXCEPTIONS"] = True1053 1063- @app.route('/fail')1054+ @app.route("/fail")1055 def fail():1056 flask.abort(404)1057 1058 with pytest.raises(NotFound):1068- client.get('/fail')1059+ client.get("/fail")1060 1061 1062 def test_error_handler_after_processor_error(app, client):1063 app.testing = False1064 1065 @app.before_request1066 def before_request():1076- if trigger == 'before':1067+ if trigger == "before":1068 1 // 01069 1070 @app.after_request1071 def after_request(response):1081- if trigger == 'after':1072+ if trigger == "after":1073 1 // 01074 return response1075 1085- @app.route('/')1076+ @app.route("/")1077 def index():1087- return 'Foo'1078+ return "Foo"1079 1080 @app.errorhandler(500)1081 def internal_server_error(e):1091- return 'Hello Server Error', 5001082+ return "Hello Server Error", 5001083 1093- for trigger in 'before', 'after':1094- rv = client.get('/')1084+ for trigger in "before", "after":1085+ rv = client.get("/")1086 assert rv.status_code == 5001096- assert rv.data == b'Hello Server Error'1087+ assert rv.data == b"Hello Server Error"1088 1089 1090 def test_enctype_debug_helper(app, client):1091 from flask.debughelpers import DebugFilesKeyError1092+1093 app.debug = True1094 1103- @app.route('/fail', methods=['POST'])1095+ @app.route("/fail", methods=["POST"])1096 def index():1105- return flask.request.files['foo'].filename1097+ return flask.request.files["foo"].filename1098 1099 # with statement is important because we leave an exception on the1100 # stack otherwise and we want to ensure that this is not the case1101 # to not negatively affect other tests.1102 with client:1103 with pytest.raises(DebugFilesKeyError) as e:1112- client.post('/fail', data={'foo': 'index.txt'})1113- assert 'no file contents were transmitted' in str(e.value)1104+ client.post("/fail", data={"foo": "index.txt"})1105+ assert "no file contents were transmitted" in str(e.value)1106 assert 'This was submitted: "index.txt"' in str(e.value)1107 1108 1109 def test_response_types(app, client):1118- @app.route('/text')1110+ @app.route("/text")1111 def from_text():1120- return u'Hällo Wörld'1112+ return u"Hällo Wörld"1113 1122- @app.route('/bytes')1114+ @app.route("/bytes")1115 def from_bytes():1124- return u'Hällo Wörld'.encode('utf-8')1116+ return u"Hällo Wörld".encode("utf-8")1117 1126- @app.route('/full_tuple')1118+ @app.route("/full_tuple")1119 def from_full_tuple():1128- return 'Meh', 400, {1129- 'X-Foo': 'Testing',1130- 'Content-Type': 'text/plain; charset=utf-8'1131- }1120+ return (1121+ "Meh",1122+ 400,1123+ {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1124+ )1125 1133- @app.route('/text_headers')1126+ @app.route("/text_headers")1127 def from_text_headers():1135- return 'Hello', {1136- 'X-Foo': 'Test',1137- 'Content-Type': 'text/plain; charset=utf-8'1138- }1128+ return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}1129 1140- @app.route('/text_status')1130+ @app.route("/text_status")1131 def from_text_status():1142- return 'Hi, status!', 4001132+ return "Hi, status!", 4001133 1144- @app.route('/response_headers')1134+ @app.route("/response_headers")1135 def from_response_headers():1146- return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1147- "X-Foo": "Bar",1148- "X-Bar": "Foo"1149- }1136+ return (1137+ flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1138+ {"X-Foo": "Bar", "X-Bar": "Foo"},1139+ )1140 1151- @app.route('/response_status')1141+ @app.route("/response_status")1142 def from_response_status():1153- return app.response_class('Hello world', 400), 5001143+ return app.response_class("Hello world", 400), 5001144 1155- @app.route('/wsgi')1145+ @app.route("/wsgi")1146 def from_wsgi():1147 return NotFound()1148 1159- assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1160- assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1149+ assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1150+ assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")1151 1162- rv = client.get('/full_tuple')1163- assert rv.data == b'Meh'1164- assert rv.headers['X-Foo'] == 'Testing'1152+ rv = client.get("/full_tuple")1153+ assert rv.data == b"Meh"1154+ assert rv.headers["X-Foo"] == "Testing"1155 assert rv.status_code == 4001166- assert rv.mimetype == 'text/plain'1156+ assert rv.mimetype == "text/plain"1157 1168- rv = client.get('/text_headers')1169- assert rv.data == b'Hello'1170- assert rv.headers['X-Foo'] == 'Test'1158+ rv = client.get("/text_headers")1159+ assert rv.data == b"Hello"1160+ assert rv.headers["X-Foo"] == "Test"1161 assert rv.status_code == 2001172- assert rv.mimetype == 'text/plain'1162+ assert rv.mimetype == "text/plain"1163 1174- rv = client.get('/text_status')1175- assert rv.data == b'Hi, status!'1164+ rv = client.get("/text_status")1165+ assert rv.data == b"Hi, status!"1166 assert rv.status_code == 4001177- assert rv.mimetype == 'text/html'1167+ assert rv.mimetype == "text/html"1168 1179- rv = client.get('/response_headers')1180- assert rv.data == b'Hello world'1181- assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1182- assert rv.headers['X-Bar'] == 'Foo'1169+ rv = client.get("/response_headers")1170+ assert rv.data == b"Hello world"1171+ assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1172+ assert rv.headers["X-Bar"] == "Foo"1173 assert rv.status_code == 4041174 1185- rv = client.get('/response_status')1186- assert rv.data == b'Hello world'1175+ rv = client.get("/response_status")1176+ assert rv.data == b"Hello world"1177 assert rv.status_code == 5001178 1189- rv = client.get('/wsgi')1190- assert b'Not Found' in rv.data1179+ rv = client.get("/wsgi")1180+ assert b"Not Found" in rv.data1181 assert rv.status_code == 4041182 1183 1184 def test_response_type_errors():1185 app = flask.Flask(__name__)1186 app.testing = True1187 1198- @app.route('/none')1188+ @app.route("/none")1189 def from_none():1190 pass1191 1202- @app.route('/small_tuple')1192+ @app.route("/small_tuple")1193 def from_small_tuple():1204- return 'Hello',1194+ return ("Hello",)1195 1206- @app.route('/large_tuple')1196+ @app.route("/large_tuple")1197 def from_large_tuple():1208- return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1198+ return "Hello", 234, {"X-Foo": "Bar"}, "???"1199 1210- @app.route('/bad_type')1200+ @app.route("/bad_type")1201 def from_bad_type():1202 return True1203 1214- @app.route('/bad_wsgi')1204+ @app.route("/bad_wsgi")1205 def from_bad_wsgi():1206 return lambda: None1207 1208 c = app.test_client()1209 1210 with pytest.raises(TypeError) as e:1221- c.get('/none')1222- assert 'returned None' in str(e)1211+ c.get("/none")1212+ assert "returned None" in str(e)1213 1214 with pytest.raises(TypeError) as e:1225- c.get('/small_tuple')1226- assert 'tuple must have the form' in str(e)1215+ c.get("/small_tuple")1216+ assert "tuple must have the form" in str(e)1217 1228- pytest.raises(TypeError, c.get, '/large_tuple')1218+ pytest.raises(TypeError, c.get, "/large_tuple")1219 1220 with pytest.raises(TypeError) as e:1231- c.get('/bad_type')1232- assert 'it was a bool' in str(e)1221+ c.get("/bad_type")1222+ assert "it was a bool" in str(e)1223 1234- pytest.raises(TypeError, c.get, '/bad_wsgi')1224+ pytest.raises(TypeError, c.get, "/bad_wsgi")1225 1226 1227 def test_make_response(app, req_ctx):1228 rv = flask.make_response()1229 assert rv.status_code == 2001240- assert rv.data == b''1241- assert rv.mimetype == 'text/html'1230+ assert rv.data == b""1231+ assert rv.mimetype == "text/html"1232 1243- rv = flask.make_response('Awesome')1233+ rv = flask.make_response("Awesome")1234 assert rv.status_code == 2001245- assert rv.data == b'Awesome'1246- assert rv.mimetype == 'text/html'1235+ assert rv.data == b"Awesome"1236+ assert rv.mimetype == "text/html"1237 1248- rv = flask.make_response('W00t', 404)1238+ rv = flask.make_response("W00t", 404)1239 assert rv.status_code == 4041250- assert rv.data == b'W00t'1251- assert rv.mimetype == 'text/html'1240+ assert rv.data == b"W00t"1241+ assert rv.mimetype == "text/html"1242 1243 1244 def test_make_response_with_response_instance(app, req_ctx):1255- rv = flask.make_response(1256- flask.jsonify({'msg': 'W00t'}), 400)1245+ rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1246 assert rv.status_code == 4001247 assert rv.data == b'{"msg":"W00t"}\n'1259- assert rv.mimetype == 'application/json'1248+ assert rv.mimetype == "application/json"1249 1261- rv = flask.make_response(1262- flask.Response(''), 400)1250+ rv = flask.make_response(flask.Response(""), 400)1251 assert rv.status_code == 4001264- assert rv.data == b''1265- assert rv.mimetype == 'text/html'1252+ assert rv.data == b""1253+ assert rv.mimetype == "text/html"1254 1255 rv = flask.make_response(1268- flask.Response('', headers={'Content-Type': 'text/html'}),1269- 400, [('X-Foo', 'bar')])1256+ flask.Response("", headers={"Content-Type": "text/html"}),1257+ 400,1258+ [("X-Foo", "bar")],1259+ )1260 assert rv.status_code == 4001271- assert rv.headers['Content-Type'] == 'text/html'1272- assert rv.headers['X-Foo'] == 'bar'1261+ assert rv.headers["Content-Type"] == "text/html"1262+ assert rv.headers["X-Foo"] == "bar"1263 1264 1265 def test_jsonify_no_prettyprint(app, req_ctx):1266 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1267 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1278- uncompressed_msg = {1279- "msg": {1280- "submsg": "W00t"1281- },1282- "msg2": "foobar"1283- }1268+ uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1269 1285- rv = flask.make_response(1286- flask.jsonify(uncompressed_msg), 200)1270+ rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1271 assert rv.data == compressed_msg1272 1273 1274 def test_jsonify_prettyprint(app, req_ctx):1275 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1276 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1293- pretty_response = \1277+ pretty_response = (1278 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1279+ )1280 1296- rv = flask.make_response(1297- flask.jsonify(compressed_msg), 200)1281+ rv = flask.make_response(flask.jsonify(compressed_msg), 200)1282 assert rv.data == pretty_response1283 1284 1285 def test_jsonify_mimetype(app, req_ctx):1302- app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1303- msg = {1304- "msg": {"submsg": "W00t"},1305- }1306- rv = flask.make_response(1307- flask.jsonify(msg), 200)1308- assert rv.mimetype == 'application/vnd.api+json'1286+ app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1287+ msg = {"msg": {"submsg": "W00t"}}1288+ rv = flask.make_response(flask.jsonify(msg), 200)1289+ assert rv.mimetype == "application/vnd.api+json"1290 1291 1292 def test_jsonify_args_and_kwargs_check(app, req_ctx):1293 with pytest.raises(TypeError) as e:1313- flask.jsonify('fake args', kwargs='fake')1314- assert 'behavior undefined' in str(e.value)1294+ flask.jsonify("fake args", kwargs="fake")1295+ assert "behavior undefined" in str(e.value)1296 1297 1298 def test_url_generation(app, req_ctx):1318- @app.route('/hello/<name>', methods=['POST'])1299+ @app.route("/hello/<name>", methods=["POST"])1300 def hello():1301 pass1302 1322- assert flask.url_for('hello', name='test x') == '/hello/test%20x'1323- assert flask.url_for('hello', name='test x', _external=True) == \1324- 'http://localhost/hello/test%20x'1303+ assert flask.url_for("hello", name="test x") == "/hello/test%20x"1304+ assert (1305+ flask.url_for("hello", name="test x", _external=True)1306+ == "http://localhost/hello/test%20x"1307+ )1308 1309 1310 def test_build_error_handler(app):1311 # Test base case, a URL which results in a BuildError.1312 with app.test_request_context():1330- pytest.raises(BuildError, flask.url_for, 'spam')1313+ pytest.raises(BuildError, flask.url_for, "spam")1314 1315 # Verify the error is re-raised if not the current exception.1316 try:1317 with app.test_request_context():1335- flask.url_for('spam')1318+ flask.url_for("spam")1319 except BuildError as err:1320 error = err1321 try:1339- raise RuntimeError('Test case where BuildError is not current.')1322+ raise RuntimeError("Test case where BuildError is not current.")1323 except RuntimeError:1341- pytest.raises(1342- BuildError, app.handle_url_build_error, error, 'spam', {})1324+ pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})1325 1326 # Test a custom handler.1327 def handler(error, endpoint, values):1328 # Just a test.1347- return '/test_handler/'1329+ return "/test_handler/"1330 1331 app.url_build_error_handlers.append(handler)1332 with app.test_request_context():1351- assert flask.url_for('spam') == '/test_handler/'1333+ assert flask.url_for("spam") == "/test_handler/"1334 1335 1336 def test_build_error_handler_reraise(app):1337 # Test a custom handler which reraises the BuildError2 unmodified lines1340 1341 app.url_build_error_handlers.append(handler_raises_build_error)1342 1343 with app.test_request_context():1362- pytest.raises(BuildError, flask.url_for, 'not.existing')1344+ pytest.raises(BuildError, flask.url_for, "not.existing")1345 1346 1347 def test_url_for_passes_special_values_to_build_error_handler(app):1348 @app.url_build_error_handlers.append1349 def handler(error, endpoint, values):1350 assert values == {1369- '_external': False,1370- '_anchor': None,1371- '_method': None,1372- '_scheme': None,1351+ "_external": False,1352+ "_anchor": None,1353+ "_method": None,1354+ "_scheme": None,1355 }1374- return 'handled'1356+ return "handled"1357 1358 with app.test_request_context():1377- flask.url_for('/')1359+ flask.url_for("/")1360 1361 1362 def test_custom_converters(app, client):1363 from werkzeug.routing import BaseConverter1364 1365 class ListConverter(BaseConverter):1366 def to_python(self, value):1385- return value.split(',')1367+ return value.split(",")1368 1369 def to_url(self, value):1370 base_to_url = super(ListConverter, self).to_url1389- return ','.join(base_to_url(x) for x in value)1371+ return ",".join(base_to_url(x) for x in value)1372 1391- app.url_map.converters['list'] = ListConverter1373+ app.url_map.converters["list"] = ListConverter1374 1393- @app.route('/<list:args>')1375+ @app.route("/<list:args>")1376 def index(args):1395- return '|'.join(args)1377+ return "|".join(args)1378 1397- assert client.get('/1,2,3').data == b'1|2|3'1379+ assert client.get("/1,2,3").data == b"1|2|3"1380 1381 1382 def test_static_files(app, client):1401- rv = client.get('/static/index.html')1383+ rv = client.get("/static/index.html")1384 assert rv.status_code == 2001403- assert rv.data.strip() == b'<h1>Hello World!</h1>'1385+ assert rv.data.strip() == b"<h1>Hello World!</h1>"1386 with app.test_request_context():1405- assert flask.url_for('static', filename='index.html') == \1406- '/static/index.html'1387+ assert flask.url_for("static", filename="index.html") == "/static/index.html"1388 rv.close()1389 1390 1391 def test_static_url_path():1411- app = flask.Flask(__name__, static_url_path='/foo')1392+ app = flask.Flask(__name__, static_url_path="/foo")1393 app.testing = True1413- rv = app.test_client().get('/foo/index.html')1394+ rv = app.test_client().get("/foo/index.html")1395 assert rv.status_code == 2001396 rv.close()1397 1398 with app.test_request_context():1418- assert flask.url_for('static', filename='index.html') == '/foo/index.html'1399+ assert flask.url_for("static", filename="index.html") == "/foo/index.html"1400 1401 1402 def test_static_route_with_host_matching():1422- app = flask.Flask(__name__, host_matching=True, static_host='example.com')1403+ app = flask.Flask(__name__, host_matching=True, static_host="example.com")1404 c = app.test_client()1424- rv = c.get('http://example.com/static/index.html')1405+ rv = c.get("http://example.com/static/index.html")1406 assert rv.status_code == 2001407 rv.close()1408 with app.test_request_context():1428- rv = flask.url_for('static', filename='index.html', _external=True)1429- assert rv == 'http://example.com/static/index.html'1409+ rv = flask.url_for("static", filename="index.html", _external=True)1410+ assert rv == "http://example.com/static/index.html"1411 # Providing static_host without host_matching=True should error.1412 with pytest.raises(Exception):1432- flask.Flask(__name__, static_host='example.com')1413+ flask.Flask(__name__, static_host="example.com")1414 # Providing host_matching=True with static_folder but without static_host should error.1415 with pytest.raises(Exception):1416 flask.Flask(__name__, host_matching=True)1417 # Providing host_matching=True without static_host but with static_folder=None should not error.1418 flask.Flask(__name__, host_matching=True, static_folder=None)1419 1420 1421 def test_request_locals():1441- assert repr(flask.g) == '<LocalProxy unbound>'1422+ assert repr(flask.g) == "<LocalProxy unbound>"1423 assert not flask.g1424 1425 1426 def test_test_app_proper_environ():1427 app = flask.Flask(__name__, subdomain_matching=True)1447- app.config.update(1448- SERVER_NAME='localhost.localdomain:5000'1449- )1428+ app.config.update(SERVER_NAME="localhost.localdomain:5000")1429 client = app.test_client()1430 1452- @app.route('/')1431+ @app.route("/")1432 def index():1454- return 'Foo'1433+ return "Foo"1434 1456- @app.route('/', subdomain='foo')1435+ @app.route("/", subdomain="foo")1436 def subdomain():1458- return 'Foo SubDomain'1437+ return "Foo SubDomain"1438 1460- rv = client.get('/')1461- assert rv.data == b'Foo'1439+ rv = client.get("/")1440+ assert rv.data == b"Foo"1441 1463- rv = client.get('/', 'http://localhost.localdomain:5000')1464- assert rv.data == b'Foo'1442+ rv = client.get("/", "http://localhost.localdomain:5000")1443+ assert rv.data == b"Foo"1444 1466- rv = client.get('/', 'https://localhost.localdomain:5000')1467- assert rv.data == b'Foo'1445+ rv = client.get("/", "https://localhost.localdomain:5000")1446+ assert rv.data == b"Foo"1447 1469- app.config.update(SERVER_NAME='localhost.localdomain')1470- rv = client.get('/', 'https://localhost.localdomain')1471- assert rv.data == b'Foo'1448+ app.config.update(SERVER_NAME="localhost.localdomain")1449+ rv = client.get("/", "https://localhost.localdomain")1450+ assert rv.data == b"Foo"1451 1452 try:1474- app.config.update(SERVER_NAME='localhost.localdomain:443')1475- rv = client.get('/', 'https://localhost.localdomain')1453+ app.config.update(SERVER_NAME="localhost.localdomain:443")1454+ rv = client.get("/", "https://localhost.localdomain")1455 # Werkzeug 0.81456 assert rv.status_code == 4041457 except ValueError as e:1458 # Werkzeug 0.73 unmodified lines1462 "server name from the WSGI environment ('localhost.localdomain')"1463 )1464 1465 try:1487- app.config.update(SERVER_NAME='localhost.localdomain')1488- rv = client.get('/', 'http://foo.localhost')1466+ app.config.update(SERVER_NAME="localhost.localdomain")1467+ rv = client.get("/", "http://foo.localhost")1468 # Werkzeug 0.81469 assert rv.status_code == 4041470 except ValueError as e:1471 # Werkzeug 0.72 unmodified lines1474 "('localhost.localdomain') does not match the "1475 "server name from the WSGI environment ('foo.localhost')"1476 )1477 1499- rv = client.get('/', 'http://foo.localhost.localdomain')1500- assert rv.data == b'Foo SubDomain'1478+ rv = client.get("/", "http://foo.localhost.localdomain")1479+ assert rv.data == b"Foo SubDomain"1480 1481 1482 def test_exception_propagation(app, client):1483 def apprunner(config_key):1505-1506- @app.route('/')1484+ @app.route("/")1485 def index():1486 1 // 01487 1488 if config_key is not None:1489 app.config[config_key] = True1490 with pytest.raises(Exception):1513- client.get('/')1491+ client.get("/")1492 else:1515- assert client.get('/').status_code == 5001493+ assert client.get("/").status_code == 5001494 1495 # we have to run this test in an isolated thread because if the1496 # debug flag is set to true and an exception happens the context is1497 # not torn down. This causes other tests that run after this fail1498 # when they expect no exception on the stack.1521- for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1499+ for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1500 t = Thread(target=apprunner, args=(config_key,))1501 t.start()1502 t.join()1503 1504 1527-@pytest.mark.parametrize('debug', [True, False])1528-@pytest.mark.parametrize('use_debugger', [True, False])1529-@pytest.mark.parametrize('use_reloader', [True, False])1530-@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1531-def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1532- use_reloader, propagate_exceptions, app):1505+@pytest.mark.parametrize("debug", [True, False])1506+@pytest.mark.parametrize("use_debugger", [True, False])1507+@pytest.mark.parametrize("use_reloader", [True, False])1508+@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1509+def test_werkzeug_passthrough_errors(1510+ monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1511+):1512 rv = {}1513 1514 # Mocks werkzeug.serving.run_simple method1515 def run_simple_mock(*args, **kwargs):1537- rv['passthrough_errors'] = kwargs.get('passthrough_errors')1516+ rv["passthrough_errors"] = kwargs.get("passthrough_errors")1517 1539- monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1540- app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1518+ monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1519+ app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1520 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1521 1522 1523 def test_max_content_length(app, client):1545- app.config['MAX_CONTENT_LENGTH'] = 641524+ app.config["MAX_CONTENT_LENGTH"] = 641525 1526 @app.before_request1527 def always_first():1549- flask.request.form['myfile']1528+ flask.request.form["myfile"]1529 assert False1530 1552- @app.route('/accept', methods=['POST'])1531+ @app.route("/accept", methods=["POST"])1532 def accept_file():1554- flask.request.form['myfile']1533+ flask.request.form["myfile"]1534 assert False1535 1536 @app.errorhandler(413)1537 def catcher(error):1559- return '42'1538+ return "42"1539 1561- rv = client.post('/accept', data={'myfile': 'foo' * 100})1562- assert rv.data == b'42'1540+ rv = client.post("/accept", data={"myfile": "foo" * 100})1541+ assert rv.data == b"42"1542 1543 1544 def test_url_processors(app, client):1566-1545 @app.url_defaults1546 def add_language_code(endpoint, values):1569- if flask.g.lang_code is not None and \1570- app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1571- values.setdefault('lang_code', flask.g.lang_code)1547+ if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1548+ endpoint, "lang_code"1549+ ):1550+ values.setdefault("lang_code", flask.g.lang_code)1551 1552 @app.url_value_preprocessor1553 def pull_lang_code(endpoint, values):1575- flask.g.lang_code = values.pop('lang_code', None)1554+ flask.g.lang_code = values.pop("lang_code", None)1555 1577- @app.route('/<lang_code>/')1556+ @app.route("/<lang_code>/")1557 def index():1579- return flask.url_for('about')1558+ return flask.url_for("about")1559 1581- @app.route('/<lang_code>/about')1560+ @app.route("/<lang_code>/about")1561 def about():1583- return flask.url_for('something_else')1562+ return flask.url_for("something_else")1563 1585- @app.route('/foo')1564+ @app.route("/foo")1565 def something_else():1587- return flask.url_for('about', lang_code='en')1566+ return flask.url_for("about", lang_code="en")1567 1589- assert client.get('/de/').data == b'/de/about'1590- assert client.get('/de/about').data == b'/foo'1591- assert client.get('/foo').data == b'/en/about'1568+ assert client.get("/de/").data == b"/de/about"1569+ assert client.get("/de/about").data == b"/foo"1570+ assert client.get("/foo").data == b"/en/about"1571 1572 1573 def test_inject_blueprint_url_defaults(app):1595- bp = flask.Blueprint('foo.bar.baz', __name__,1596- template_folder='template')1574+ bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")1575 1576 @bp.url_defaults1577 def bp_defaults(endpoint, values):1600- values['page'] = 'login'1578+ values["page"] = "login"1579 1602- @bp.route('/<page>')1580+ @bp.route("/<page>")1581 def view(page):1582 pass1583 1584 app.register_blueprint(bp)1585 1586 values = dict()1609- app.inject_url_defaults('foo.bar.baz.view', values)1610- expected = dict(page='login')1587+ app.inject_url_defaults("foo.bar.baz.view", values)1588+ expected = dict(page="login")1589 assert values == expected1590 1613- with app.test_request_context('/somepage'):1614- url = flask.url_for('foo.bar.baz.view')1615- expected = '/login'1591+ with app.test_request_context("/somepage"):1592+ url = flask.url_for("foo.bar.baz.view")1593+ expected = "/login"1594 assert url == expected1595 1596 1597 def test_nonascii_pathinfo(app, client):1620- @app.route(u'/киртест')1598+ @app.route(u"/киртест")1599 def index():1622- return 'Hello World!'1600+ return "Hello World!"1601 1624- rv = client.get(u'/киртест')1625- assert rv.data == b'Hello World!'1602+ rv = client.get(u"/киртест")1603+ assert rv.data == b"Hello World!"1604 1605 1606 def test_debug_mode_complains_after_first_request(app, client):1607 app.debug = True1608 1631- @app.route('/')1609+ @app.route("/")1610 def index():1633- return 'Awesome'1611+ return "Awesome"1612 1613 assert not app.got_first_request1636- assert client.get('/').data == b'Awesome'1614+ assert client.get("/").data == b"Awesome"1615 with pytest.raises(AssertionError) as e:1616+1638- @app.route('/foo')1617+ @app.route("/foo")1618 def broken():1640- return 'Meh'1641- assert 'A setup function was called' in str(e)1619+ return "Meh"1620 1621+ assert "A setup function was called" in str(e)1622+1623 app.debug = False1624 1645- @app.route('/foo')1625+ @app.route("/foo")1626 def working():1647- return 'Meh'1627+ return "Meh"1628 1649- assert client.get('/foo').data == b'Meh'1629+ assert client.get("/foo").data == b"Meh"1630 assert app.got_first_request1631 1632 1633 def test_before_first_request_functions(app, client):2 unmodified lines1636 @app.before_first_request1637 def foo():1638 got.append(42)1639 1660- client.get('/')1640+ client.get("/")1641 assert got == [42]1662- client.get('/')1642+ client.get("/")1643 assert got == [42]1644 assert app.got_first_request1645 1646 18 unmodified lines1665 1666 def test_routing_redirect_debugging(app, client):1667 app.debug = True1668 1689- @app.route('/foo/', methods=['GET', 'POST'])1669+ @app.route("/foo/", methods=["GET", "POST"])1670 def foo():1691- return 'success'1671+ return "success"1672 1673 with client:1674 with pytest.raises(AssertionError) as e:1695- client.post('/foo', data={})1696- assert 'http://localhost/foo/' in str(e)1697- assert ('Make sure to directly send '1698- 'your POST-request to this URL') in str(e)1675+ client.post("/foo", data={})1676+ assert "http://localhost/foo/" in str(e)1677+ assert ("Make sure to directly send " "your POST-request to this URL") in str(e)1678 1700- rv = client.get('/foo', data={}, follow_redirects=True)1701- assert rv.data == b'success'1679+ rv = client.get("/foo", data={}, follow_redirects=True)1680+ assert rv.data == b"success"1681 1682 app.debug = False1683 with client:1705- rv = client.post('/foo', data={}, follow_redirects=True)1706- assert rv.data == b'success'1684+ rv = client.post("/foo", data={}, follow_redirects=True)1685+ assert rv.data == b"success"1686 1687 1688 def test_route_decorator_custom_endpoint(app, client):1689 app.debug = True1690 1712- @app.route('/foo/')1691+ @app.route("/foo/")1692 def foo():1693 return flask.request.endpoint1694 1716- @app.route('/bar/', endpoint='bar')1695+ @app.route("/bar/", endpoint="bar")1696 def for_bar():1697 return flask.request.endpoint1698 1720- @app.route('/bar/123', endpoint='123')1699+ @app.route("/bar/123", endpoint="123")1700 def for_bar_foo():1701 return flask.request.endpoint1702 1703 with app.test_request_context():1725- assert flask.url_for('foo') == '/foo/'1726- assert flask.url_for('bar') == '/bar/'1727- assert flask.url_for('123') == '/bar/123'1704+ assert flask.url_for("foo") == "/foo/"1705+ assert flask.url_for("bar") == "/bar/"1706+ assert flask.url_for("123") == "/bar/123"1707 1729- assert client.get('/foo/').data == b'foo'1730- assert client.get('/bar/').data == b'bar'1731- assert client.get('/bar/123').data == b'123'1708+ assert client.get("/foo/").data == b"foo"1709+ assert client.get("/bar/").data == b"bar"1710+ assert client.get("/bar/123").data == b"123"1711 1712 1713 def test_preserve_only_once(app, client):1714 app.debug = True1715 1737- @app.route('/fail')1716+ @app.route("/fail")1717 def fail_func():1718 1 // 01719 1720 for x in range(3):1721 with pytest.raises(ZeroDivisionError):1743- client.get('/fail')1722+ client.get("/fail")1723 1724 assert flask._request_ctx_stack.top is not None1725 assert flask._app_ctx_stack.top is not None1726 # implicit appctx disappears too5 unmodified lines1732 def test_preserve_remembers_exception(app, client):1733 app.debug = True1734 errors = []1735 1757- @app.route('/fail')1736+ @app.route("/fail")1737 def fail_func():1738 1 // 01739 1761- @app.route('/success')1740+ @app.route("/success")1741 def success_func():1763- return 'Okay'1742+ return "Okay"1743 1744 @app.teardown_request1745 def teardown_handler(exc):1746 errors.append(exc)1747 1748 # After this failure we did not yet call the teardown handler1749 with pytest.raises(ZeroDivisionError):1771- client.get('/fail')1750+ client.get("/fail")1751 assert errors == []1752 1753 # But this request triggers it, and it's an error1775- client.get('/success')1754+ client.get("/success")1755 assert len(errors) == 21756 assert isinstance(errors[0], ZeroDivisionError)1757 1758 # At this point another request does nothing.1780- client.get('/success')1759+ client.get("/success")1760 assert len(errors) == 31761 assert errors[1] is None1762 1763 1764 def test_get_method_on_g(app_ctx):1786- assert flask.g.get('x') is None1787- assert flask.g.get('x', 11) == 111765+ assert flask.g.get("x") is None1766+ assert flask.g.get("x", 11) == 111767 flask.g.x = 421789- assert flask.g.get('x') == 421768+ assert flask.g.get("x") == 421769 assert flask.g.x == 421770 1771 1772 def test_g_iteration_protocol(app_ctx):1773 flask.g.foo = 231774 flask.g.bar = 421796- assert 'foo' in flask.g1797- assert 'foos' not in flask.g1798- assert sorted(flask.g) == ['bar', 'foo']1775+ assert "foo" in flask.g1776+ assert "foos" not in flask.g1777+ assert sorted(flask.g) == ["bar", "foo"]1778 1779 1780 def test_subdomain_basic_support():1781 app = flask.Flask(__name__, subdomain_matching=True)1803- app.config['SERVER_NAME'] = 'localhost.localdomain'1782+ app.config["SERVER_NAME"] = "localhost.localdomain"1783 client = app.test_client()1784 1806- @app.route('/')1785+ @app.route("/")1786 def normal_index():1808- return 'normal index'1787+ return "normal index"1788 1810- @app.route('/', subdomain='test')1789+ @app.route("/", subdomain="test")1790 def test_index():1812- return 'test index'1791+ return "test index"1792 1814- rv = client.get('/', 'http://localhost.localdomain/')1815- assert rv.data == b'normal index'1793+ rv = client.get("/", "http://localhost.localdomain/")1794+ assert rv.data == b"normal index"1795 1817- rv = client.get('/', 'http://test.localhost.localdomain/')1818- assert rv.data == b'test index'1796+ rv = client.get("/", "http://test.localhost.localdomain/")1797+ assert rv.data == b"test index"1798 1799 1800 def test_subdomain_matching():1801 app = flask.Flask(__name__, subdomain_matching=True)1802 client = app.test_client()1824- app.config['SERVER_NAME'] = 'localhost.localdomain'1803+ app.config["SERVER_NAME"] = "localhost.localdomain"1804 1826- @app.route('/', subdomain='<user>')1805+ @app.route("/", subdomain="<user>")1806 def index(user):1828- return 'index for %s' % user1807+ return "index for %s" % user1808 1830- rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1831- assert rv.data == b'index for mitsuhiko'1809+ rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1810+ assert rv.data == b"index for mitsuhiko"1811 1812 1813 def test_subdomain_matching_with_ports():1814 app = flask.Flask(__name__, subdomain_matching=True)1836- app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1815+ app.config["SERVER_NAME"] = "localhost.localdomain:3000"1816 client = app.test_client()1817 1839- @app.route('/', subdomain='<user>')1818+ @app.route("/", subdomain="<user>")1819 def index(user):1841- return 'index for %s' % user1820+ return "index for %s" % user1821 1843- rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1844- assert rv.data == b'index for mitsuhiko'1822+ rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1823+ assert rv.data == b"index for mitsuhiko"1824 1825 1847-@pytest.mark.parametrize('matching', (False, True))1826+@pytest.mark.parametrize("matching", (False, True))1827 def test_subdomain_matching_other_name(matching):1828 app = flask.Flask(__name__, subdomain_matching=matching)1850- app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1829+ app.config["SERVER_NAME"] = "localhost.localdomain:3000"1830 client = app.test_client()1831 1853- @app.route('/')1832+ @app.route("/")1833 def index():1855- return '', 2041834+ return "", 2041835 1836 # ip address can't match name1858- rv = client.get('/', 'http://127.0.0.1:3000/')1837+ rv = client.get("/", "http://127.0.0.1:3000/")1838 assert rv.status_code == 404 if matching else 2041839 1840 # allow all subdomains if matching is disabled1862- rv = client.get('/', 'http://www.localhost.localdomain:3000/')1841+ rv = client.get("/", "http://www.localhost.localdomain:3000/")1842 assert rv.status_code == 404 if matching else 2041843 1844 1845 def test_multi_route_rules(app, client):1867- @app.route('/')1868- @app.route('/<test>/')1869- def index(test='a'):1846+ @app.route("/")1847+ @app.route("/<test>/")1848+ def index(test="a"):1849 return test1850 1872- rv = client.open('/')1873- assert rv.data == b'a'1874- rv = client.open('/b/')1875- assert rv.data == b'b'1851+ rv = client.open("/")1852+ assert rv.data == b"a"1853+ rv = client.open("/b/")1854+ assert rv.data == b"b"1855 1856 1857 def test_multi_route_class_views(app, client):1858 class View(object):1859 def __init__(self, app):1881- app.add_url_rule('/', 'index', self.index)1882- app.add_url_rule('/<test>/', 'index', self.index)1860+ app.add_url_rule("/", "index", self.index)1861+ app.add_url_rule("/<test>/", "index", self.index)1862 1884- def index(self, test='a'):1863+ def index(self, test="a"):1864 return test1865 1866 _ = View(app)1888- rv = client.open('/')1889- assert rv.data == b'a'1890- rv = client.open('/b/')1891- assert rv.data == b'b'1867+ rv = client.open("/")1868+ assert rv.data == b"a"1869+ rv = client.open("/b/")1870+ assert rv.data == b"b"1871 1872 1873 def test_run_defaults(monkeypatch, app):1874 rv = {}1875 1876 # Mocks werkzeug.serving.run_simple method1877 def run_simple_mock(*args, **kwargs):1899- rv['result'] = 'running...'1878+ rv["result"] = "running..."1879 1901- monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1880+ monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1881 app.run()1903- assert rv['result'] == 'running...'1882+ assert rv["result"] == "running..."1883 1884 1885 def test_run_server_port(monkeypatch, app):1886 rv = {}1887 1888 # Mocks werkzeug.serving.run_simple method1889 def run_simple_mock(hostname, port, application, *args, **kwargs):1911- rv['result'] = 'running on %s:%s ...' % (hostname, port)1890+ rv["result"] = "running on %s:%s ..." % (hostname, port)1891 1913- monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1914- hostname, port = 'localhost', 80001892+ monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1893+ hostname, port = "localhost", 80001894 app.run(hostname, port, debug=True)1916- assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1895+ assert rv["result"] == "running on %s:%s ..." % (hostname, port)1896 1897 1919-@pytest.mark.parametrize('host,port,expect_host,expect_port', (1920- (None, None, 'pocoo.org', 8080),1921- ('localhost', None, 'localhost', 8080),1922- (None, 80, 'pocoo.org', 80),1923- ('localhost', 80, 'localhost', 80),1924-))1898+@pytest.mark.parametrize(1899+ "host,port,expect_host,expect_port",1900+ (1901+ (None, None, "pocoo.org", 8080),1902+ ("localhost", None, "localhost", 8080),1903+ (None, 80, "pocoo.org", 80),1904+ ("localhost", 80, "localhost", 80),1905+ ),1906+)1907 def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1908 def run_simple_mock(hostname, port, *args, **kwargs):1909 assert hostname == expect_host1910 assert port == expect_port1911 1930- monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1931- app.config['SERVER_NAME'] = 'pocoo.org:8080'1912+ monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1913+ app.config["SERVER_NAME"] = "pocoo.org:8080"1914 app.run(host, port)1915 1916 1917 def test_max_cookie_size(app, client, recwarn):1936- app.config['MAX_COOKIE_SIZE'] = 1001918+ app.config["MAX_COOKIE_SIZE"] = 1001919 1920 # outside app context, default to Werkzeug static value,1921 # which is also the default config1922 response = flask.Response()1941- default = flask.Flask.default_config['MAX_COOKIE_SIZE']1923+ default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1924 assert response.max_cookie_size == default1925 1926 # inside app context, use app config1927 with app.app_context():1928 assert flask.Response().max_cookie_size == 1001929 1948- @app.route('/')1930+ @app.route("/")1931 def index():1950- r = flask.Response('', status=204)1951- r.set_cookie('foo', 'bar' * 100)1932+ r = flask.Response("", status=204)1933+ r.set_cookie("foo", "bar" * 100)1934 return r1935 1954- client.get('/')1936+ client.get("/")1937 assert len(recwarn) == 11938 w = recwarn.pop()1957- assert 'cookie is too large' in str(w.message)1939+ assert "cookie is too large" in str(w.message)1940 1959- app.config['MAX_COOKIE_SIZE'] = 01941+ app.config["MAX_COOKIE_SIZE"] = 01942 1961- client.get('/')1943+ client.get("/")1944 assert len(recwarn) == 0modified:tests/test_blueprints.py+320 added-312 removed
18 unmodified lines19 from jinja2 import TemplateNotFound20 21 22 def test_blueprint_specific_error_handling(app, client):23- frontend = flask.Blueprint('frontend', __name__)24- backend = flask.Blueprint('backend', __name__)25- sideend = flask.Blueprint('sideend', __name__)23+ frontend = flask.Blueprint("frontend", __name__)24+ backend = flask.Blueprint("backend", __name__)25+ sideend = flask.Blueprint("sideend", __name__)26 27 @frontend.errorhandler(403)28 def frontend_forbidden(e):29- return 'frontend says no', 40329+ return "frontend says no", 40330 31- @frontend.route('/frontend-no')31+ @frontend.route("/frontend-no")32 def frontend_no():33 flask.abort(403)34 35 @backend.errorhandler(403)36 def backend_forbidden(e):37- return 'backend says no', 40337+ return "backend says no", 40338 39- @backend.route('/backend-no')39+ @backend.route("/backend-no")40 def backend_no():41 flask.abort(403)42 43- @sideend.route('/what-is-a-sideend')43+ @sideend.route("/what-is-a-sideend")44 def sideend_no():45 flask.abort(403)46 47 app.register_blueprint(frontend)1 unmodified line49 app.register_blueprint(sideend)50 51 @app.errorhandler(403)52 def app_forbidden(e):53- return 'application itself says no', 40353+ return "application itself says no", 40354 55- assert client.get('/frontend-no').data == b'frontend says no'56- assert client.get('/backend-no').data == b'backend says no'57- assert client.get('/what-is-a-sideend').data == b'application itself says no'55+ assert client.get("/frontend-no").data == b"frontend says no"56+ assert client.get("/backend-no").data == b"backend says no"57+ assert client.get("/what-is-a-sideend").data == b"application itself says no"58 59 60 def test_blueprint_specific_user_error_handling(app, client):61 class MyDecoratorException(Exception):1 unmodified line63 64 class MyFunctionException(Exception):65 pass66 67- blue = flask.Blueprint('blue', __name__)67+ blue = flask.Blueprint("blue", __name__)68 69 @blue.errorhandler(MyDecoratorException)70 def my_decorator_exception_handler(e):71 assert isinstance(e, MyDecoratorException)72- return 'boom'72+ return "boom"73 74 def my_function_exception_handler(e):75 assert isinstance(e, MyFunctionException)76- return 'bam'76+ return "bam"77 78 blue.register_error_handler(MyFunctionException, my_function_exception_handler)79 80- @blue.route('/decorator')80+ @blue.route("/decorator")81 def blue_deco_test():82 raise MyDecoratorException()83 84- @blue.route('/function')84+ @blue.route("/function")85 def blue_func_test():86 raise MyFunctionException()87 88 app.register_blueprint(blue)89 90- assert client.get('/decorator').data == b'boom'91- assert client.get('/function').data == b'bam'90+ assert client.get("/decorator").data == b"boom"91+ assert client.get("/function").data == b"bam"92 93 94 def test_blueprint_app_error_handling(app, client):95- errors = flask.Blueprint('errors', __name__)95+ errors = flask.Blueprint("errors", __name__)96 97 @errors.app_errorhandler(403)98 def forbidden_handler(e):99- return 'you shall not pass', 40399+ return "you shall not pass", 403100 101- @app.route('/forbidden')101+ @app.route("/forbidden")102 def app_forbidden():103 flask.abort(403)104 105- forbidden_bp = flask.Blueprint('forbidden_bp', __name__)105+ forbidden_bp = flask.Blueprint("forbidden_bp", __name__)106 107- @forbidden_bp.route('/nope')107+ @forbidden_bp.route("/nope")108 def bp_forbidden():109 flask.abort(403)110 111 app.register_blueprint(errors)112 app.register_blueprint(forbidden_bp)113 114- assert client.get('/forbidden').data == b'you shall not pass'115- assert client.get('/nope').data == b'you shall not pass'114+ assert client.get("/forbidden").data == b"you shall not pass"115+ assert client.get("/nope").data == b"you shall not pass"116 117 118-@pytest.mark.parametrize(('prefix', 'rule', 'url'), (119- ('', '/', '/'),120- ('/', '', '/'),121- ('/', '/', '/'),122- ('/foo', '', '/foo'),123- ('/foo/', '', '/foo/'),124- ('', '/bar', '/bar'),125- ('/foo/', '/bar', '/foo/bar'),126- ('/foo/', 'bar', '/foo/bar'),127- ('/foo', '/bar', '/foo/bar'),128- ('/foo/', '//bar', '/foo/bar'),129- ('/foo//', '/bar', '/foo/bar'),130-))118+@pytest.mark.parametrize(119+ ("prefix", "rule", "url"),120+ (121+ ("", "/", "/"),122+ ("/", "", "/"),123+ ("/", "/", "/"),124+ ("/foo", "", "/foo"),125+ ("/foo/", "", "/foo/"),126+ ("", "/bar", "/bar"),127+ ("/foo/", "/bar", "/foo/bar"),128+ ("/foo/", "bar", "/foo/bar"),129+ ("/foo", "/bar", "/foo/bar"),130+ ("/foo/", "//bar", "/foo/bar"),131+ ("/foo//", "/bar", "/foo/bar"),132+ ),133+)134 def test_blueprint_prefix_slash(app, client, prefix, rule, url):132- bp = flask.Blueprint('test', __name__, url_prefix=prefix)135+ bp = flask.Blueprint("test", __name__, url_prefix=prefix)136 137 @bp.route(rule)138 def index():136- return '', 204139+ return "", 204140 141 app.register_blueprint(bp)142 assert client.get(url).status_code == 204143 144 145 def test_blueprint_url_defaults(app, client):143- bp = flask.Blueprint('test', __name__)146+ bp = flask.Blueprint("test", __name__)147 145- @bp.route('/foo', defaults={'baz': 42})148+ @bp.route("/foo", defaults={"baz": 42})149 def foo(bar, baz):147- return '%s/%d' % (bar, baz)150+ return "%s/%d" % (bar, baz)151 149- @bp.route('/bar')152+ @bp.route("/bar")153 def bar(bar):154 return text_type(bar)155 153- app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})154- app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})156+ app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})157+ app.register_blueprint(bp, url_prefix="/2", url_defaults={"bar": 19})158 156- assert client.get('/1/foo').data == b'23/42'157- assert client.get('/2/foo').data == b'19/42'158- assert client.get('/1/bar').data == b'23'159- assert client.get('/2/bar').data == b'19'159+ assert client.get("/1/foo").data == b"23/42"160+ assert client.get("/2/foo").data == b"19/42"161+ assert client.get("/1/bar").data == b"23"162+ assert client.get("/2/bar").data == b"19"163 164 165 def test_blueprint_url_processors(app, client):163- bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')166+ bp = flask.Blueprint("frontend", __name__, url_prefix="/<lang_code>")167 168 @bp.url_defaults169 def add_language_code(endpoint, values):167- values.setdefault('lang_code', flask.g.lang_code)170+ values.setdefault("lang_code", flask.g.lang_code)171 172 @bp.url_value_preprocessor173 def pull_lang_code(endpoint, values):171- flask.g.lang_code = values.pop('lang_code')174+ flask.g.lang_code = values.pop("lang_code")175 173- @bp.route('/')176+ @bp.route("/")177 def index():175- return flask.url_for('.about')178+ return flask.url_for(".about")179 177- @bp.route('/about')180+ @bp.route("/about")181 def about():179- return flask.url_for('.index')182+ return flask.url_for(".index")183 184 app.register_blueprint(bp)185 183- assert client.get('/de/').data == b'/de/about'184- assert client.get('/de/about').data == b'/de/'186+ assert client.get("/de/").data == b"/de/about"187+ assert client.get("/de/about").data == b"/de/"188 189 190 def test_templates_and_static(test_apps):191 from blueprintapp import app192+193 client = app.test_client()194 191- rv = client.get('/')192- assert rv.data == b'Hello from the Frontend'193- rv = client.get('/admin/')194- assert rv.data == b'Hello from the Admin'195- rv = client.get('/admin/index2')196- assert rv.data == b'Hello from the Admin'197- rv = client.get('/admin/static/test.txt')198- assert rv.data.strip() == b'Admin File'195+ rv = client.get("/")196+ assert rv.data == b"Hello from the Frontend"197+ rv = client.get("/admin/")198+ assert rv.data == b"Hello from the Admin"199+ rv = client.get("/admin/index2")200+ assert rv.data == b"Hello from the Admin"201+ rv = client.get("/admin/static/test.txt")202+ assert rv.data.strip() == b"Admin File"203 rv.close()200- rv = client.get('/admin/static/css/test.css')201- assert rv.data.strip() == b'/* nested file */'204+ rv = client.get("/admin/static/css/test.css")205+ assert rv.data.strip() == b"/* nested file */"206 rv.close()207 208 # try/finally, in case other tests use this app for Blueprint tests.205- max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']209+ max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]210 try:211 expected_max_age = 3600208- if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:212+ if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:213 expected_max_age = 7200210- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age211- rv = client.get('/admin/static/css/test.css')212- cc = parse_cache_control_header(rv.headers['Cache-Control'])214+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age215+ rv = client.get("/admin/static/css/test.css")216+ cc = parse_cache_control_header(rv.headers["Cache-Control"])217 assert cc.max_age == expected_max_age218 rv.close()219 finally:216- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default220+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default221 222 with app.test_request_context():219- assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'223+ assert (224+ flask.url_for("admin.static", filename="test.txt")225+ == "/admin/static/test.txt"226+ )227 228 with app.test_request_context():229 with pytest.raises(TemplateNotFound) as e:223- flask.render_template('missing.html')224- assert e.value.name == 'missing.html'230+ flask.render_template("missing.html")231+ assert e.value.name == "missing.html"232 233 with flask.Flask(__name__).test_request_context():227- assert flask.render_template('nested/nested.txt') == 'I\'m nested'234+ assert flask.render_template("nested/nested.txt") == "I'm nested"235 236 237 def test_default_static_cache_timeout(app):238 class MyBlueprint(flask.Blueprint):239 def get_send_file_max_age(self, filename):240 return 100241 235- blueprint = MyBlueprint('blueprint', __name__, static_folder='static')242+ blueprint = MyBlueprint("blueprint", __name__, static_folder="static")243 app.register_blueprint(blueprint)244 245 # try/finally, in case other tests use this app for Blueprint tests.239- max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']246+ max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]247 try:248 with app.test_request_context():249 unexpected_max_age = 3600243- if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:250+ if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == unexpected_max_age:251 unexpected_max_age = 7200245- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age246- rv = blueprint.send_static_file('index.html')247- cc = parse_cache_control_header(rv.headers['Cache-Control'])252+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = unexpected_max_age253+ rv = blueprint.send_static_file("index.html")254+ cc = parse_cache_control_header(rv.headers["Cache-Control"])255 assert cc.max_age == 100256 rv.close()257 finally:251- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default258+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default259 260 261 def test_templates_list(test_apps):262 from blueprintapp import app263+264 templates = sorted(app.jinja_env.list_templates())257- assert templates == ['admin/index.html', 'frontend/index.html']265+ assert templates == ["admin/index.html", "frontend/index.html"]266 267 268 def test_dotted_names(app, client):261- frontend = flask.Blueprint('myapp.frontend', __name__)262- backend = flask.Blueprint('myapp.backend', __name__)269+ frontend = flask.Blueprint("myapp.frontend", __name__)270+ backend = flask.Blueprint("myapp.backend", __name__)271 264- @frontend.route('/fe')272+ @frontend.route("/fe")273 def frontend_index():266- return flask.url_for('myapp.backend.backend_index')274+ return flask.url_for("myapp.backend.backend_index")275 268- @frontend.route('/fe2')276+ @frontend.route("/fe2")277 def frontend_page2():270- return flask.url_for('.frontend_index')278+ return flask.url_for(".frontend_index")279 272- @backend.route('/be')280+ @backend.route("/be")281 def backend_index():274- return flask.url_for('myapp.frontend.frontend_index')282+ return flask.url_for("myapp.frontend.frontend_index")283 284 app.register_blueprint(frontend)285 app.register_blueprint(backend)286 279- assert client.get('/fe').data.strip() == b'/be'280- assert client.get('/fe2').data.strip() == b'/fe'281- assert client.get('/be').data.strip() == b'/fe'287+ assert client.get("/fe").data.strip() == b"/be"288+ assert client.get("/fe2").data.strip() == b"/fe"289+ assert client.get("/be").data.strip() == b"/fe"290 291 292 def test_dotted_names_from_app(app, client):285- test = flask.Blueprint('test', __name__)293+ test = flask.Blueprint("test", __name__)294 287- @app.route('/')295+ @app.route("/")296 def app_index():289- return flask.url_for('test.index')297+ return flask.url_for("test.index")298 291- @test.route('/test/')299+ @test.route("/test/")300 def index():293- return flask.url_for('app_index')301+ return flask.url_for("app_index")302 303 app.register_blueprint(test)304 297- rv = client.get('/')298- assert rv.data == b'/test/'305+ rv = client.get("/")306+ assert rv.data == b"/test/"307 308 309 def test_empty_url_defaults(app, client):302- bp = flask.Blueprint('bp', __name__)310+ bp = flask.Blueprint("bp", __name__)311 304- @bp.route('/', defaults={'page': 1})305- @bp.route('/page/<int:page>')312+ @bp.route("/", defaults={"page": 1})313+ @bp.route("/page/<int:page>")314 def something(page):315 return str(page)316 317 app.register_blueprint(bp)318 311- assert client.get('/').data == b'1'312- assert client.get('/page/2').data == b'2'319+ assert client.get("/").data == b"1"320+ assert client.get("/page/2").data == b"2"321 322 323 def test_route_decorator_custom_endpoint(app, client):316- bp = flask.Blueprint('bp', __name__)324+ bp = flask.Blueprint("bp", __name__)325 318- @bp.route('/foo')326+ @bp.route("/foo")327 def foo():328 return flask.request.endpoint329 322- @bp.route('/bar', endpoint='bar')330+ @bp.route("/bar", endpoint="bar")331 def foo_bar():332 return flask.request.endpoint333 326- @bp.route('/bar/123', endpoint='123')334+ @bp.route("/bar/123", endpoint="123")335 def foo_bar_foo():336 return flask.request.endpoint337 330- @bp.route('/bar/foo')338+ @bp.route("/bar/foo")339 def bar_foo():340 return flask.request.endpoint341 334- app.register_blueprint(bp, url_prefix='/py')342+ app.register_blueprint(bp, url_prefix="/py")343 336- @app.route('/')344+ @app.route("/")345 def index():346 return flask.request.endpoint347 340- assert client.get('/').data == b'index'341- assert client.get('/py/foo').data == b'bp.foo'342- assert client.get('/py/bar').data == b'bp.bar'343- assert client.get('/py/bar/123').data == b'bp.123'344- assert client.get('/py/bar/foo').data == b'bp.bar_foo'348+ assert client.get("/").data == b"index"349+ assert client.get("/py/foo").data == b"bp.foo"350+ assert client.get("/py/bar").data == b"bp.bar"351+ assert client.get("/py/bar/123").data == b"bp.123"352+ assert client.get("/py/bar/foo").data == b"bp.bar_foo"353 354 355 def test_route_decorator_custom_endpoint_with_dots(app, client):348- bp = flask.Blueprint('bp', __name__)356+ bp = flask.Blueprint("bp", __name__)357 350- @bp.route('/foo')358+ @bp.route("/foo")359 def foo():360 return flask.request.endpoint361 362 try:355- @bp.route('/bar', endpoint='bar.bar')363+364+ @bp.route("/bar", endpoint="bar.bar")365 def foo_bar():366 return flask.request.endpoint367+368 except AssertionError:369 pass370 else:361- raise AssertionError('expected AssertionError not raised')371+ raise AssertionError("expected AssertionError not raised")372 373 try:364- @bp.route('/bar/123', endpoint='bar.123')374+375+ @bp.route("/bar/123", endpoint="bar.123")376 def foo_bar_foo():377 return flask.request.endpoint378+379 except AssertionError:380 pass381 else:370- raise AssertionError('expected AssertionError not raised')382+ raise AssertionError("expected AssertionError not raised")383 384 def foo_foo_foo():385 pass386 387 pytest.raises(388 AssertionError,377- lambda: bp.add_url_rule(378- '/bar/123', endpoint='bar.123', view_func=foo_foo_foo379- )389+ lambda: bp.add_url_rule("/bar/123", endpoint="bar.123", view_func=foo_foo_foo),390 )391 392 pytest.raises(383- AssertionError,384- bp.route('/bar/123', endpoint='bar.123'),385- lambda: None393+ AssertionError, bp.route("/bar/123", endpoint="bar.123"), lambda: None394 )395 388- foo_foo_foo.__name__ = 'bar.123'396+ foo_foo_foo.__name__ = "bar.123"397 398 pytest.raises(391- AssertionError,392- lambda: bp.add_url_rule(393- '/bar/123', view_func=foo_foo_foo394- )399+ AssertionError, lambda: bp.add_url_rule("/bar/123", view_func=foo_foo_foo)400 )401 397- bp.add_url_rule('/bar/456', endpoint='foofoofoo', view_func=functools.partial(foo_foo_foo))402+ bp.add_url_rule(403+ "/bar/456", endpoint="foofoofoo", view_func=functools.partial(foo_foo_foo)404+ )405 399- app.register_blueprint(bp, url_prefix='/py')406+ app.register_blueprint(bp, url_prefix="/py")407 401- assert client.get('/py/foo').data == b'bp.foo'408+ assert client.get("/py/foo").data == b"bp.foo"409 # The rule's didn't actually made it through403- rv = client.get('/py/bar')410+ rv = client.get("/py/bar")411 assert rv.status_code == 404405- rv = client.get('/py/bar/123')412+ rv = client.get("/py/bar/123")413 assert rv.status_code == 404414 415 416 def test_endpoint_decorator(app, client):417 from werkzeug.routing import Rule411- app.url_map.add(Rule('/foo', endpoint='bar'))418 413- bp = flask.Blueprint('bp', __name__)419+ app.url_map.add(Rule("/foo", endpoint="bar"))420 421+ bp = flask.Blueprint("bp", __name__)422+415- @bp.endpoint('bar')423+ @bp.endpoint("bar")424 def foobar():425 return flask.request.endpoint426 419- app.register_blueprint(bp, url_prefix='/bp_prefix')427+ app.register_blueprint(bp, url_prefix="/bp_prefix")428 421- assert client.get('/foo').data == b'bar'422- assert client.get('/bp_prefix/bar').status_code == 404429+ assert client.get("/foo").data == b"bar"430+ assert client.get("/bp_prefix/bar").status_code == 404431 432 433 def test_template_filter(app):426- bp = flask.Blueprint('bp', __name__)434+ bp = flask.Blueprint("bp", __name__)435 436 @bp.app_template_filter()437 def my_reverse(s):438 return s[::-1]439 432- app.register_blueprint(bp, url_prefix='/py')433- assert 'my_reverse' in app.jinja_env.filters.keys()434- assert app.jinja_env.filters['my_reverse'] == my_reverse435- assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'440+ app.register_blueprint(bp, url_prefix="/py")441+ assert "my_reverse" in app.jinja_env.filters.keys()442+ assert app.jinja_env.filters["my_reverse"] == my_reverse443+ assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"444 445 446 def test_add_template_filter(app):439- bp = flask.Blueprint('bp', __name__)447+ bp = flask.Blueprint("bp", __name__)448 449 def my_reverse(s):450 return s[::-1]451 452 bp.add_app_template_filter(my_reverse)445- app.register_blueprint(bp, url_prefix='/py')446- assert 'my_reverse' in app.jinja_env.filters.keys()447- assert app.jinja_env.filters['my_reverse'] == my_reverse448- assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'453+ app.register_blueprint(bp, url_prefix="/py")454+ assert "my_reverse" in app.jinja_env.filters.keys()455+ assert app.jinja_env.filters["my_reverse"] == my_reverse456+ assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"457 458 459 def test_template_filter_with_name(app):452- bp = flask.Blueprint('bp', __name__)460+ bp = flask.Blueprint("bp", __name__)461 454- @bp.app_template_filter('strrev')462+ @bp.app_template_filter("strrev")463 def my_reverse(s):464 return s[::-1]465 458- app.register_blueprint(bp, url_prefix='/py')459- assert 'strrev' in app.jinja_env.filters.keys()460- assert app.jinja_env.filters['strrev'] == my_reverse461- assert app.jinja_env.filters['strrev']('abcd') == 'dcba'466+ app.register_blueprint(bp, url_prefix="/py")467+ assert "strrev" in app.jinja_env.filters.keys()468+ assert app.jinja_env.filters["strrev"] == my_reverse469+ assert app.jinja_env.filters["strrev"]("abcd") == "dcba"470 471 472 def test_add_template_filter_with_name(app):465- bp = flask.Blueprint('bp', __name__)473+ bp = flask.Blueprint("bp", __name__)474 475 def my_reverse(s):476 return s[::-1]477 470- bp.add_app_template_filter(my_reverse, 'strrev')471- app.register_blueprint(bp, url_prefix='/py')472- assert 'strrev' in app.jinja_env.filters.keys()473- assert app.jinja_env.filters['strrev'] == my_reverse474- assert app.jinja_env.filters['strrev']('abcd') == 'dcba'478+ bp.add_app_template_filter(my_reverse, "strrev")479+ app.register_blueprint(bp, url_prefix="/py")480+ assert "strrev" in app.jinja_env.filters.keys()481+ assert app.jinja_env.filters["strrev"] == my_reverse482+ assert app.jinja_env.filters["strrev"]("abcd") == "dcba"483 484 485 def test_template_filter_with_template(app, client):478- bp = flask.Blueprint('bp', __name__)486+ bp = flask.Blueprint("bp", __name__)487 488 @bp.app_template_filter()489 def super_reverse(s):490 return s[::-1]491 484- app.register_blueprint(bp, url_prefix='/py')492+ app.register_blueprint(bp, url_prefix="/py")493 486- @app.route('/')494+ @app.route("/")495 def index():488- return flask.render_template('template_filter.html', value='abcd')496+ return flask.render_template("template_filter.html", value="abcd")497 490- rv = client.get('/')491- assert rv.data == b'dcba'498+ rv = client.get("/")499+ assert rv.data == b"dcba"500 501 502 def test_template_filter_after_route_with_template(app, client):495- @app.route('/')503+ @app.route("/")504 def index():497- return flask.render_template('template_filter.html', value='abcd')505+ return flask.render_template("template_filter.html", value="abcd")506 499- bp = flask.Blueprint('bp', __name__)507+ bp = flask.Blueprint("bp", __name__)508 509 @bp.app_template_filter()510 def super_reverse(s):511 return s[::-1]512 505- app.register_blueprint(bp, url_prefix='/py')506- rv = client.get('/')507- assert rv.data == b'dcba'513+ app.register_blueprint(bp, url_prefix="/py")514+ rv = client.get("/")515+ assert rv.data == b"dcba"516 517 518 def test_add_template_filter_with_template(app, client):511- bp = flask.Blueprint('bp', __name__)519+ bp = flask.Blueprint("bp", __name__)520 521 def super_reverse(s):522 return s[::-1]523 524 bp.add_app_template_filter(super_reverse)517- app.register_blueprint(bp, url_prefix='/py')525+ app.register_blueprint(bp, url_prefix="/py")526 519- @app.route('/')527+ @app.route("/")528 def index():521- return flask.render_template('template_filter.html', value='abcd')529+ return flask.render_template("template_filter.html", value="abcd")530 523- rv = client.get('/')524- assert rv.data == b'dcba'531+ rv = client.get("/")532+ assert rv.data == b"dcba"533 534 535 def test_template_filter_with_name_and_template(app, client):528- bp = flask.Blueprint('bp', __name__)536+ bp = flask.Blueprint("bp", __name__)537 530- @bp.app_template_filter('super_reverse')538+ @bp.app_template_filter("super_reverse")539 def my_reverse(s):540 return s[::-1]541 534- app.register_blueprint(bp, url_prefix='/py')542+ app.register_blueprint(bp, url_prefix="/py")543 536- @app.route('/')544+ @app.route("/")545 def index():538- return flask.render_template('template_filter.html', value='abcd')546+ return flask.render_template("template_filter.html", value="abcd")547 540- rv = client.get('/')541- assert rv.data == b'dcba'548+ rv = client.get("/")549+ assert rv.data == b"dcba"550 551 552 def test_add_template_filter_with_name_and_template(app, client):545- bp = flask.Blueprint('bp', __name__)553+ bp = flask.Blueprint("bp", __name__)554 555 def my_reverse(s):556 return s[::-1]557 550- bp.add_app_template_filter(my_reverse, 'super_reverse')551- app.register_blueprint(bp, url_prefix='/py')558+ bp.add_app_template_filter(my_reverse, "super_reverse")559+ app.register_blueprint(bp, url_prefix="/py")560 553- @app.route('/')561+ @app.route("/")562 def index():555- return flask.render_template('template_filter.html', value='abcd')563+ return flask.render_template("template_filter.html", value="abcd")564 557- rv = client.get('/')558- assert rv.data == b'dcba'565+ rv = client.get("/")566+ assert rv.data == b"dcba"567 568 569 def test_template_test(app):562- bp = flask.Blueprint('bp', __name__)570+ bp = flask.Blueprint("bp", __name__)571 572 @bp.app_template_test()573 def is_boolean(value):574 return isinstance(value, bool)575 568- app.register_blueprint(bp, url_prefix='/py')569- assert 'is_boolean' in app.jinja_env.tests.keys()570- assert app.jinja_env.tests['is_boolean'] == is_boolean571- assert app.jinja_env.tests['is_boolean'](False)576+ app.register_blueprint(bp, url_prefix="/py")577+ assert "is_boolean" in app.jinja_env.tests.keys()578+ assert app.jinja_env.tests["is_boolean"] == is_boolean579+ assert app.jinja_env.tests["is_boolean"](False)580 581 582 def test_add_template_test(app):575- bp = flask.Blueprint('bp', __name__)583+ bp = flask.Blueprint("bp", __name__)584 585 def is_boolean(value):586 return isinstance(value, bool)587 588 bp.add_app_template_test(is_boolean)581- app.register_blueprint(bp, url_prefix='/py')582- assert 'is_boolean' in app.jinja_env.tests.keys()583- assert app.jinja_env.tests['is_boolean'] == is_boolean584- assert app.jinja_env.tests['is_boolean'](False)589+ app.register_blueprint(bp, url_prefix="/py")590+ assert "is_boolean" in app.jinja_env.tests.keys()591+ assert app.jinja_env.tests["is_boolean"] == is_boolean592+ assert app.jinja_env.tests["is_boolean"](False)593 594 595 def test_template_test_with_name(app):588- bp = flask.Blueprint('bp', __name__)596+ bp = flask.Blueprint("bp", __name__)597 590- @bp.app_template_test('boolean')598+ @bp.app_template_test("boolean")599 def is_boolean(value):600 return isinstance(value, bool)601 594- app.register_blueprint(bp, url_prefix='/py')595- assert 'boolean' in app.jinja_env.tests.keys()596- assert app.jinja_env.tests['boolean'] == is_boolean597- assert app.jinja_env.tests['boolean'](False)602+ app.register_blueprint(bp, url_prefix="/py")603+ assert "boolean" in app.jinja_env.tests.keys()604+ assert app.jinja_env.tests["boolean"] == is_boolean605+ assert app.jinja_env.tests["boolean"](False)606 607 608 def test_add_template_test_with_name(app):601- bp = flask.Blueprint('bp', __name__)609+ bp = flask.Blueprint("bp", __name__)610 611 def is_boolean(value):612 return isinstance(value, bool)613 606- bp.add_app_template_test(is_boolean, 'boolean')607- app.register_blueprint(bp, url_prefix='/py')608- assert 'boolean' in app.jinja_env.tests.keys()609- assert app.jinja_env.tests['boolean'] == is_boolean610- assert app.jinja_env.tests['boolean'](False)614+ bp.add_app_template_test(is_boolean, "boolean")615+ app.register_blueprint(bp, url_prefix="/py")616+ assert "boolean" in app.jinja_env.tests.keys()617+ assert app.jinja_env.tests["boolean"] == is_boolean618+ assert app.jinja_env.tests["boolean"](False)619 620 621 def test_template_test_with_template(app, client):614- bp = flask.Blueprint('bp', __name__)622+ bp = flask.Blueprint("bp", __name__)623 624 @bp.app_template_test()625 def boolean(value):626 return isinstance(value, bool)627 620- app.register_blueprint(bp, url_prefix='/py')628+ app.register_blueprint(bp, url_prefix="/py")629 622- @app.route('/')630+ @app.route("/")631 def index():624- return flask.render_template('template_test.html', value=False)632+ return flask.render_template("template_test.html", value=False)633 626- rv = client.get('/')627- assert b'Success!' in rv.data634+ rv = client.get("/")635+ assert b"Success!" in rv.data636 637 638 def test_template_test_after_route_with_template(app, client):631- @app.route('/')639+ @app.route("/")640 def index():633- return flask.render_template('template_test.html', value=False)641+ return flask.render_template("template_test.html", value=False)642 635- bp = flask.Blueprint('bp', __name__)643+ bp = flask.Blueprint("bp", __name__)644 645 @bp.app_template_test()646 def boolean(value):647 return isinstance(value, bool)648 641- app.register_blueprint(bp, url_prefix='/py')642- rv = client.get('/')643- assert b'Success!' in rv.data649+ app.register_blueprint(bp, url_prefix="/py")650+ rv = client.get("/")651+ assert b"Success!" in rv.data652 653 654 def test_add_template_test_with_template(app, client):647- bp = flask.Blueprint('bp', __name__)655+ bp = flask.Blueprint("bp", __name__)656 657 def boolean(value):658 return isinstance(value, bool)659 660 bp.add_app_template_test(boolean)653- app.register_blueprint(bp, url_prefix='/py')661+ app.register_blueprint(bp, url_prefix="/py")662 655- @app.route('/')663+ @app.route("/")664 def index():657- return flask.render_template('template_test.html', value=False)665+ return flask.render_template("template_test.html", value=False)666 659- rv = client.get('/')660- assert b'Success!' in rv.data667+ rv = client.get("/")668+ assert b"Success!" in rv.data669 670 671 def test_template_test_with_name_and_template(app, client):664- bp = flask.Blueprint('bp', __name__)672+ bp = flask.Blueprint("bp", __name__)673 666- @bp.app_template_test('boolean')674+ @bp.app_template_test("boolean")675 def is_boolean(value):676 return isinstance(value, bool)677 670- app.register_blueprint(bp, url_prefix='/py')678+ app.register_blueprint(bp, url_prefix="/py")679 672- @app.route('/')680+ @app.route("/")681 def index():674- return flask.render_template('template_test.html', value=False)682+ return flask.render_template("template_test.html", value=False)683 676- rv = client.get('/')677- assert b'Success!' in rv.data684+ rv = client.get("/")685+ assert b"Success!" in rv.data686 687 688 def test_add_template_test_with_name_and_template(app, client):681- bp = flask.Blueprint('bp', __name__)689+ bp = flask.Blueprint("bp", __name__)690 691 def is_boolean(value):692 return isinstance(value, bool)693 686- bp.add_app_template_test(is_boolean, 'boolean')687- app.register_blueprint(bp, url_prefix='/py')694+ bp.add_app_template_test(is_boolean, "boolean")695+ app.register_blueprint(bp, url_prefix="/py")696 689- @app.route('/')697+ @app.route("/")698 def index():691- return flask.render_template('template_test.html', value=False)699+ return flask.render_template("template_test.html", value=False)700 693- rv = client.get('/')694- assert b'Success!' in rv.data701+ rv = client.get("/")702+ assert b"Success!" in rv.data703 704 705 def test_context_processing(app, client):698- answer_bp = flask.Blueprint('answer_bp', __name__)706+ answer_bp = flask.Blueprint("answer_bp", __name__)707 708 template_string = lambda: flask.render_template_string(701- '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'702- '{% if answer %}{{ answer }} is the answer.{% endif %}'709+ "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"710+ "{% if answer %}{{ answer }} is the answer.{% endif %}"711 )712 713 # App global context processor714 @answer_bp.app_context_processor715 def not_answer_context_processor():708- return {'notanswer': 43}716+ return {"notanswer": 43}717 718 # Blueprint local context processor719 @answer_bp.context_processor720 def answer_context_processor():713- return {'answer': 42}721+ return {"answer": 42}722 723 # Setup endpoints for testing716- @answer_bp.route('/bp')724+ @answer_bp.route("/bp")725 def bp_page():726 return template_string()727 720- @app.route('/')728+ @app.route("/")729 def app_page():730 return template_string()731 732 # Register the blueprint733 app.register_blueprint(answer_bp)734 727- app_page_bytes = client.get('/').data728- answer_page_bytes = client.get('/bp').data735+ app_page_bytes = client.get("/").data736+ answer_page_bytes = client.get("/bp").data737 730- assert b'43' in app_page_bytes731- assert b'42' not in app_page_bytes738+ assert b"43" in app_page_bytes739+ assert b"42" not in app_page_bytes740 733- assert b'42' in answer_page_bytes734- assert b'43' in answer_page_bytes741+ assert b"42" in answer_page_bytes742+ assert b"43" in answer_page_bytes743 744 745 def test_template_global(app):738- bp = flask.Blueprint('bp', __name__)746+ bp = flask.Blueprint("bp", __name__)747 748 @bp.app_template_global()749 def get_answer():750 return 42751 752 # Make sure the function is not in the jinja_env already745- assert 'get_answer' not in app.jinja_env.globals.keys()753+ assert "get_answer" not in app.jinja_env.globals.keys()754 app.register_blueprint(bp)755 756 # Tests749- assert 'get_answer' in app.jinja_env.globals.keys()750- assert app.jinja_env.globals['get_answer'] is get_answer751- assert app.jinja_env.globals['get_answer']() == 42757+ assert "get_answer" in app.jinja_env.globals.keys()758+ assert app.jinja_env.globals["get_answer"] is get_answer759+ assert app.jinja_env.globals["get_answer"]() == 42760 761 with app.app_context():754- rv = flask.render_template_string('{{ get_answer() }}')755- assert rv == '42'762+ rv = flask.render_template_string("{{ get_answer() }}")763+ assert rv == "42"764 765 766 def test_request_processing(app, client):759- bp = flask.Blueprint('bp', __name__)767+ bp = flask.Blueprint("bp", __name__)768 evts = []769 770 @bp.before_request771 def before_bp():764- evts.append('before')772+ evts.append("before")773 774 @bp.after_request775 def after_bp(response):768- response.data += b'|after'769- evts.append('after')776+ response.data += b"|after"777+ evts.append("after")778 return response779 780 @bp.teardown_request781 def teardown_bp(exc):774- evts.append('teardown')782+ evts.append("teardown")783 784 # Setup routes for testing777- @bp.route('/bp')785+ @bp.route("/bp")786 def bp_endpoint():779- return 'request'787+ return "request"788 789 app.register_blueprint(bp)790 791 assert evts == []784- rv = client.get('/bp')785- assert rv.data == b'request|after'786- assert evts == ['before', 'after', 'teardown']792+ rv = client.get("/bp")793+ assert rv.data == b"request|after"794+ assert evts == ["before", "after", "teardown"]795 796 797 def test_app_request_processing(app, client):790- bp = flask.Blueprint('bp', __name__)798+ bp = flask.Blueprint("bp", __name__)799 evts = []800 801 @bp.before_app_first_request802 def before_first_request():795- evts.append('first')803+ evts.append("first")804 805 @bp.before_app_request806 def before_app():799- evts.append('before')807+ evts.append("before")808 809 @bp.after_app_request810 def after_app(response):803- response.data += b'|after'804- evts.append('after')811+ response.data += b"|after"812+ evts.append("after")813 return response814 815 @bp.teardown_app_request816 def teardown_app(exc):809- evts.append('teardown')817+ evts.append("teardown")818 819 app.register_blueprint(bp)820 821 # Setup routes for testing814- @app.route('/')822+ @app.route("/")823 def bp_endpoint():816- return 'request'824+ return "request"825 826 # before first request827 assert evts == []828 829 # first request822- resp = client.get('/').data823- assert resp == b'request|after'824- assert evts == ['first', 'before', 'after', 'teardown']830+ resp = client.get("/").data831+ assert resp == b"request|after"832+ assert evts == ["first", "before", "after", "teardown"]833 834 # second request827- resp = client.get('/').data828- assert resp == b'request|after'829- assert evts == ['first'] + ['before', 'after', 'teardown'] * 2835+ resp = client.get("/").data836+ assert resp == b"request|after"837+ assert evts == ["first"] + ["before", "after", "teardown"] * 2838 839 840 def test_app_url_processors(app, client):833- bp = flask.Blueprint('bp', __name__)841+ bp = flask.Blueprint("bp", __name__)842 843 # Register app-wide url defaults and preprocessor on blueprint844 @bp.app_url_defaults845 def add_language_code(endpoint, values):838- values.setdefault('lang_code', flask.g.lang_code)846+ values.setdefault("lang_code", flask.g.lang_code)847 848 @bp.app_url_value_preprocessor849 def pull_lang_code(endpoint, values):842- flask.g.lang_code = values.pop('lang_code')850+ flask.g.lang_code = values.pop("lang_code")851 852 # Register route rules at the app level845- @app.route('/<lang_code>/')853+ @app.route("/<lang_code>/")854 def index():847- return flask.url_for('about')855+ return flask.url_for("about")856 849- @app.route('/<lang_code>/about')857+ @app.route("/<lang_code>/about")858 def about():851- return flask.url_for('index')859+ return flask.url_for("index")860 861 app.register_blueprint(bp)862 855- assert client.get('/de/').data == b'/de/about'856- assert client.get('/de/about').data == b'/de/'863+ assert client.get("/de/").data == b"/de/about"864+ assert client.get("/de/about").data == b"/de/"modified:tests/test_cli.py+182 added-167 removed
23 unmodified lines24 from click.testing import CliRunner25 26 from flask import Flask, current_app27 from flask.cli import (28- AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,29- get_version, load_dotenv, locate_app, prepare_import, run_command,30- with_appcontext28+ AppGroup,29+ FlaskGroup,30+ NoAppException,31+ ScriptInfo,32+ dotenv,33+ find_best_app,34+ get_version,35+ load_dotenv,36+ locate_app,37+ prepare_import,38+ run_command,39+ with_appcontext,40 )41 42 cwd = os.getcwd()34-test_path = os.path.abspath(os.path.join(35- os.path.dirname(__file__), 'test_apps'36-))43+test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))44 45 46 @pytest.fixture47 def runner():2 unmodified lines50 51 def test_cli_name(test_apps):52 """Make sure the CLI object's name is the app's name and not the app itself"""53 from cliapp.app import testapp54+55 assert testapp.cli.name == testapp.name56 57 58 def test_find_best_app(test_apps):59 """Test if `find_best_app` behaves as expected with different combinations of input."""60 script_info = ScriptInfo()61 62 class Module:55- app = Flask('appname')63+ app = Flask("appname")64 65 assert find_best_app(script_info, Module) == Module.app66 67 class Module:60- application = Flask('appname')68+ application = Flask("appname")69 70 assert find_best_app(script_info, Module) == Module.application71 72 class Module:65- myapp = Flask('appname')73+ myapp = Flask("appname")74 75 assert find_best_app(script_info, Module) == Module.myapp76 77 class Module:78 @staticmethod79 def create_app():72- return Flask('appname')80+ return Flask("appname")81 82 assert isinstance(find_best_app(script_info, Module), Flask)75- assert find_best_app(script_info, Module).name == 'appname'83+ assert find_best_app(script_info, Module).name == "appname"84 85 class Module:86 @staticmethod87 def create_app(foo):80- return Flask('appname')88+ return Flask("appname")89 90 assert isinstance(find_best_app(script_info, Module), Flask)83- assert find_best_app(script_info, Module).name == 'appname'91+ assert find_best_app(script_info, Module).name == "appname"92 93 class Module:94 @staticmethod95 def create_app(foo=None, script_info=None):88- return Flask('appname')96+ return Flask("appname")97 98 assert isinstance(find_best_app(script_info, Module), Flask)91- assert find_best_app(script_info, Module).name == 'appname'99+ assert find_best_app(script_info, Module).name == "appname"100 101 class Module:102 @staticmethod103 def make_app():96- return Flask('appname')104+ return Flask("appname")105 106 assert isinstance(find_best_app(script_info, Module), Flask)99- assert find_best_app(script_info, Module).name == 'appname'107+ assert find_best_app(script_info, Module).name == "appname"108 109 class Module:102- myapp = Flask('appname1')110+ myapp = Flask("appname1")111 112 @staticmethod113 def create_app():106- return Flask('appname2')114+ return Flask("appname2")115 116 assert find_best_app(script_info, Module) == Module.myapp117 118 class Module:111- myapp = Flask('appname1')119+ myapp = Flask("appname1")120 121 @staticmethod122 def create_app():115- return Flask('appname2')123+ return Flask("appname2")124 125 assert find_best_app(script_info, Module) == Module.myapp126 127 class Module:1 unmodified line129 130 pytest.raises(NoAppException, find_best_app, script_info, Module)131 132 class Module:125- myapp1 = Flask('appname1')126- myapp2 = Flask('appname2')133+ myapp1 = Flask("appname1")134+ myapp2 = Flask("appname2")135 136 pytest.raises(NoAppException, find_best_app, script_info, Module)137 138 class Module:139 @staticmethod140 def create_app(foo, bar):133- return Flask('appname2')141+ return Flask("appname2")142 143 pytest.raises(NoAppException, find_best_app, script_info, Module)144 145 class Module:146 @staticmethod147 def create_app():140- raise TypeError('bad bad factory!')148+ raise TypeError("bad bad factory!")149 150 pytest.raises(TypeError, find_best_app, script_info, Module)151 152 145-@pytest.mark.parametrize('value,path,result', (146- ('test', cwd, 'test'),147- ('test.py', cwd, 'test'),148- ('a/test', os.path.join(cwd, 'a'), 'test'),149- ('test/__init__.py', cwd, 'test'),150- ('test/__init__', cwd, 'test'),151- # nested package153+@pytest.mark.parametrize(154+ "value,path,result",155 (153- os.path.join(test_path, 'cliapp', 'inner1', '__init__'),154- test_path, 'cliapp.inner1'156+ ("test", cwd, "test"),157+ ("test.py", cwd, "test"),158+ ("a/test", os.path.join(cwd, "a"), "test"),159+ ("test/__init__.py", cwd, "test"),160+ ("test/__init__", cwd, "test"),161+ # nested package162+ (163+ os.path.join(test_path, "cliapp", "inner1", "__init__"),164+ test_path,165+ "cliapp.inner1",166+ ),167+ (168+ os.path.join(test_path, "cliapp", "inner1", "inner2"),169+ test_path,170+ "cliapp.inner1.inner2",171+ ),172+ # dotted name173+ ("test.a.b", cwd, "test.a.b"),174+ (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),175+ # not a Python file, will be caught during import176+ (177+ os.path.join(test_path, "cliapp", "message.txt"),178+ test_path,179+ "cliapp.message.txt",180+ ),181 ),156- (157- os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),158- test_path, 'cliapp.inner1.inner2'159- ),160- # dotted name161- ('test.a.b', cwd, 'test.a.b'),162- (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),163- # not a Python file, will be caught during import164- (165- os.path.join(test_path, 'cliapp', 'message.txt'),166- test_path, 'cliapp.message.txt'167- ),168-))182+)183 def test_prepare_import(request, value, path, result):184 """Expect the correct path to be set and the correct import and app names185 to be returned.186 11 unmodified lines198 assert prepare_import(value) == result199 assert sys.path[0] == path200 201 188-@pytest.mark.parametrize('iname,aname,result', (189- ('cliapp.app', None, 'testapp'),190- ('cliapp.app', 'testapp', 'testapp'),191- ('cliapp.factory', None, 'app'),192- ('cliapp.factory', 'create_app', 'app'),193- ('cliapp.factory', 'create_app()', 'app'),194- # no script_info195- ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),196- # trailing comma space197- ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),198- # takes script_info199- ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),200- # strip whitespace201- ('cliapp.factory', ' create_app () ', 'app'),202-))202+@pytest.mark.parametrize(203+ "iname,aname,result",204+ (205+ ("cliapp.app", None, "testapp"),206+ ("cliapp.app", "testapp", "testapp"),207+ ("cliapp.factory", None, "app"),208+ ("cliapp.factory", "create_app", "app"),209+ ("cliapp.factory", "create_app()", "app"),210+ # no script_info211+ ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),212+ # trailing comma space213+ ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),214+ # takes script_info215+ ("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),216+ # strip whitespace217+ ("cliapp.factory", " create_app () ", "app"),218+ ),219+)220 def test_locate_app(test_apps, iname, aname, result):221 info = ScriptInfo()205- info.data['test'] = 'spam'222+ info.data["test"] = "spam"223 assert locate_app(info, iname, aname).name == result224 225 209-@pytest.mark.parametrize('iname,aname', (210- ('notanapp.py', None),211- ('cliapp/app', None),212- ('cliapp.app', 'notanapp'),213- # not enough arguments214- ('cliapp.factory', 'create_app2("foo")'),215- # invalid identifier216- ('cliapp.factory', 'create_app('),217- # no app returned218- ('cliapp.factory', 'no_app'),219- # nested import error220- ('cliapp.importerrorapp', None),221- # not a Python file222- ('cliapp.message.txt', None),223-))226+@pytest.mark.parametrize(227+ "iname,aname",228+ (229+ ("notanapp.py", None),230+ ("cliapp/app", None),231+ ("cliapp.app", "notanapp"),232+ # not enough arguments233+ ("cliapp.factory", 'create_app2("foo")'),234+ # invalid identifier235+ ("cliapp.factory", "create_app("),236+ # no app returned237+ ("cliapp.factory", "no_app"),238+ # nested import error239+ ("cliapp.importerrorapp", None),240+ # not a Python file241+ ("cliapp.message.txt", None),242+ ),243+)244 def test_locate_app_raises(test_apps, iname, aname):245 info = ScriptInfo()246 247 with pytest.raises(NoAppException):1 unmodified line249 250 251 def test_locate_app_suppress_raise():252 info = ScriptInfo()233- app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)253+ app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)254 assert app is None255 256 # only direct import error is suppressed257 with pytest.raises(NoAppException):238- locate_app(239- info, 'cliapp.importerrorapp', None, raise_if_not_found=False240- )258+ locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)259 260 261 def test_get_version(test_apps, capsys):262 from flask import __version__ as flask_version3 unmodified lines266 class MockCtx(object):267 resilient_parsing = False268 color = None269 252- def exit(self): return270+ def exit(self):271+ return272 273 ctx = MockCtx()274 get_version(ctx, None, "test")275 out, err = capsys.readouterr()9 unmodified lines285 assert app.name == "testapp"286 assert obj.load_app() is app287 288 # import app with module's absolute path270- cli_app_path = os.path.abspath(os.path.join(271- os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))289+ cli_app_path = os.path.abspath(290+ os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")291+ )292 obj = ScriptInfo(app_import_path=cli_app_path)293 app = obj.load_app()274- assert app.name == 'testapp'294+ assert app.name == "testapp"295 assert obj.load_app() is app276- obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')296+ obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")297 app = obj.load_app()278- assert app.name == 'testapp'298+ assert app.name == "testapp"299 assert obj.load_app() is app300 301 def create_app(info):302 return Flask("createapp")6 unmodified lines309 obj = ScriptInfo()310 pytest.raises(NoAppException, obj.load_app)311 312 # import app from wsgi.py in current directory293- monkeypatch.chdir(os.path.abspath(os.path.join(294- os.path.dirname(__file__), 'test_apps', 'helloworld'295- )))313+ monkeypatch.chdir(314+ os.path.abspath(315+ os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")316+ )317+ )318 obj = ScriptInfo()319 app = obj.load_app()298- assert app.name == 'hello'320+ assert app.name == "hello"321 322 # import app from app.py in current directory301- monkeypatch.chdir(os.path.abspath(os.path.join(302- os.path.dirname(__file__), 'test_apps', 'cliapp'303- )))323+ monkeypatch.chdir(324+ os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))325+ )326 obj = ScriptInfo()327 app = obj.load_app()306- assert app.name == 'testapp'328+ assert app.name == "testapp"329 330 331 def test_with_appcontext(runner):332 """Test of with_appcontext."""6 unmodified lines339 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))340 341 result = runner.invoke(testcmd, obj=obj)342 assert result.exit_code == 0321- assert result.output == 'testapp\n'343+ assert result.output == "testapp\n"344 345 346 def test_appgroup(runner):347 """Test of with_appcontext."""15 unmodified lines363 click.echo(current_app.name)364 365 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))366 345- result = runner.invoke(cli, ['test'], obj=obj)367+ result = runner.invoke(cli, ["test"], obj=obj)368 assert result.exit_code == 0347- assert result.output == 'testappgroup\n'369+ assert result.output == "testappgroup\n"370 349- result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)371+ result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)372 assert result.exit_code == 0351- assert result.output == 'testappgroup\n'373+ assert result.output == "testappgroup\n"374 375 376 def test_flaskgroup(runner):377 """Test FlaskGroup."""8 unmodified lines386 @cli.command()387 def test():388 click.echo(current_app.name)389 368- result = runner.invoke(cli, ['test'])390+ result = runner.invoke(cli, ["test"])391 assert result.exit_code == 0370- assert result.output == 'flaskgroup\n'392+ assert result.output == "flaskgroup\n"393 394 373-@pytest.mark.parametrize('set_debug_flag', (True, False))395+@pytest.mark.parametrize("set_debug_flag", (True, False))396 def test_flaskgroup_debug(runner, set_debug_flag):397 """Test FlaskGroup debug flag behavior."""398 399 def create_app(info):8 unmodified lines408 @cli.command()409 def test():410 click.echo(str(current_app.debug))411 390- result = runner.invoke(cli, ['test'])412+ result = runner.invoke(cli, ["test"])413 assert result.exit_code == 0392- assert result.output == '%s\n' % str(not set_debug_flag)414+ assert result.output == "%s\n" % str(not set_debug_flag)415 416 417 def test_print_exceptions(runner):418 """Print the stacktrace if the CLI."""5 unmodified lines424 @click.group(cls=FlaskGroup, create_app=create_app)425 def cli(**params):426 pass427 406- result = runner.invoke(cli, ['--help'])428+ result = runner.invoke(cli, ["--help"])429 assert result.exit_code == 0408- assert 'Exception: oh no' in result.output409- assert 'Traceback' in result.output430+ assert "Exception: oh no" in result.output431+ assert "Traceback" in result.output432 433 434 class TestRoutes:435 @pytest.fixture1 unmodified line437 def create_app(info):438 app = Flask(__name__)439 app.testing = True440 419- @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])441+ @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])442 def yyy_get_post(x, y):443 pass444 423- @app.route('/zzz_post', methods=['POST'])445+ @app.route("/zzz_post", methods=["POST"])446 def aaa_post():447 pass448 449 return app15 unmodified lines465 def expect_order(self, order, output):466 # skip the header and match the start of each row467 for expect, line in zip(order, output.splitlines()[2:]):468 # do this instead of startswith for nicer pytest output447- assert line[:len(expect)] == expect469+ assert line[: len(expect)] == expect470 471 def test_simple(self, invoke):450- result = invoke(['routes'])472+ result = invoke(["routes"])473 assert result.exit_code == 0452- self.expect_order(453- ['aaa_post', 'static', 'yyy_get_post'],454- result.output455- )474+ self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)475 476 def test_sort(self, invoke):458- default_output = invoke(['routes']).output459- endpoint_output = invoke(['routes', '-s', 'endpoint']).output477+ default_output = invoke(["routes"]).output478+ endpoint_output = invoke(["routes", "-s", "endpoint"]).output479 assert default_output == endpoint_output480 self.expect_order(462- ['static', 'yyy_get_post', 'aaa_post'],463- invoke(['routes', '-s', 'methods']).output481+ ["static", "yyy_get_post", "aaa_post"],482+ invoke(["routes", "-s", "methods"]).output,483 )484 self.expect_order(466- ['yyy_get_post', 'static', 'aaa_post'],467- invoke(['routes', '-s', 'rule']).output485+ ["yyy_get_post", "static", "aaa_post"],486+ invoke(["routes", "-s", "rule"]).output,487 )488 self.expect_order(470- ['aaa_post', 'yyy_get_post', 'static'],471- invoke(['routes', '-s', 'match']).output489+ ["aaa_post", "yyy_get_post", "static"],490+ invoke(["routes", "-s", "match"]).output,491 )492 493 def test_all_methods(self, invoke):475- output = invoke(['routes']).output476- assert 'GET, HEAD, OPTIONS, POST' not in output477- output = invoke(['routes', '--all-methods']).output478- assert 'GET, HEAD, OPTIONS, POST' in output494+ output = invoke(["routes"]).output495+ assert "GET, HEAD, OPTIONS, POST" not in output496+ output = invoke(["routes", "--all-methods"]).output497+ assert "GET, HEAD, OPTIONS, POST" in output498 499 def test_no_routes(self, invoke_no_routes):481- result = invoke_no_routes(['routes'])500+ result = invoke_no_routes(["routes"])501 assert result.exit_code == 0483- assert 'No routes were registered.' in result.output502+ assert "No routes were registered." in result.output503 504 486-need_dotenv = pytest.mark.skipif(487- dotenv is None, reason='dotenv is not installed'488-)505+need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")506 507 508 @need_dotenv509 def test_load_dotenv(monkeypatch):510 # can't use monkeypatch.delitem since the keys don't exist yet494- for item in ('FOO', 'BAR', 'SPAM'):511+ for item in ("FOO", "BAR", "SPAM"):512 monkeypatch._setitem.append((os.environ, item, notset))513 497- monkeypatch.setenv('EGGS', '3')498- monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))514+ monkeypatch.setenv("EGGS", "3")515+ monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))516 load_dotenv()517 assert os.getcwd() == test_path518 # .flaskenv doesn't overwrite .env502- assert os.environ['FOO'] == 'env'519+ assert os.environ["FOO"] == "env"520 # set only in .flaskenv504- assert os.environ['BAR'] == 'bar'521+ assert os.environ["BAR"] == "bar"522 # set only in .env506- assert os.environ['SPAM'] == '1'523+ assert os.environ["SPAM"] == "1"524 # set manually, files don't overwrite508- assert os.environ['EGGS'] == '3'525+ assert os.environ["EGGS"] == "3"526 527 528 @need_dotenv529 def test_dotenv_path(monkeypatch):513- for item in ('FOO', 'BAR', 'EGGS'):530+ for item in ("FOO", "BAR", "EGGS"):531 monkeypatch._setitem.append((os.environ, item, notset))532 533 cwd = os.getcwd()517- load_dotenv(os.path.join(test_path, '.flaskenv'))534+ load_dotenv(os.path.join(test_path, ".flaskenv"))535 assert os.getcwd() == cwd519- assert 'FOO' in os.environ536+ assert "FOO" in os.environ537 538 539 def test_dotenv_optional(monkeypatch):523- monkeypatch.setattr('flask.cli.dotenv', None)540+ monkeypatch.setattr("flask.cli.dotenv", None)541 monkeypatch.chdir(test_path)542 load_dotenv()526- assert 'FOO' not in os.environ543+ assert "FOO" not in os.environ544 545 546 @need_dotenv547 def test_disable_dotenv_from_env(monkeypatch, runner):548 monkeypatch.chdir(test_path)532- monkeypatch.setitem(os.environ, 'FLASK_SKIP_DOTENV', '1')549+ monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")550 runner.invoke(FlaskGroup())534- assert 'FOO' not in os.environ551+ assert "FOO" not in os.environ552 553 554 def test_run_cert_path():555 # no key556 with pytest.raises(click.BadParameter):540- run_command.make_context('run', ['--cert', __file__])557+ run_command.make_context("run", ["--cert", __file__])558 559 # no cert560 with pytest.raises(click.BadParameter):544- run_command.make_context('run', ['--key', __file__])561+ run_command.make_context("run", ["--key", __file__])562 546- ctx = run_command.make_context(547- 'run', ['--cert', __file__, '--key', __file__])548- assert ctx.params['cert'] == (__file__, __file__)563+ ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])564+ assert ctx.params["cert"] == (__file__, __file__)565 566 567 def test_run_cert_adhoc(monkeypatch):552- monkeypatch.setitem(sys.modules, 'OpenSSL', None)568+ monkeypatch.setitem(sys.modules, "OpenSSL", None)569 570 # pyOpenSSL not installed571 with pytest.raises(click.BadParameter):556- run_command.make_context('run', ['--cert', 'adhoc'])572+ run_command.make_context("run", ["--cert", "adhoc"])573 574 # pyOpenSSL installed559- monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))560- ctx = run_command.make_context('run', ['--cert', 'adhoc'])561- assert ctx.params['cert'] == 'adhoc'575+ monkeypatch.setitem(sys.modules, "OpenSSL", types.ModuleType("OpenSSL"))576+ ctx = run_command.make_context("run", ["--cert", "adhoc"])577+ assert ctx.params["cert"] == "adhoc"578 579 # no key with adhoc580 with pytest.raises(click.BadParameter):565- run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])581+ run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])582 583 584 def test_run_cert_import(monkeypatch):569- monkeypatch.setitem(sys.modules, 'not_here', None)585+ monkeypatch.setitem(sys.modules, "not_here", None)586 587 # ImportError588 with pytest.raises(click.BadParameter):573- run_command.make_context('run', ['--cert', 'not_here'])589+ run_command.make_context("run", ["--cert", "not_here"])590 591 # not an SSLContext592 if sys.version_info >= (2, 7, 9):593 with pytest.raises(click.BadParameter):578- run_command.make_context('run', ['--cert', 'flask'])594+ run_command.make_context("run", ["--cert", "flask"])595 596 # SSLContext597 if sys.version_info < (2, 7, 9):598 ssl_context = object()599 else:600 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)601 586- monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)587- ctx = run_command.make_context('run', ['--cert', 'ssl_context'])588- assert ctx.params['cert'] is ssl_context602+ monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)603+ ctx = run_command.make_context("run", ["--cert", "ssl_context"])604+ assert ctx.params["cert"] is ssl_context605 606 # no --key with SSLContext607 with pytest.raises(click.BadParameter):592- run_command.make_context(593- 'run', ['--cert', 'ssl_context', '--key', __file__])608+ run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])modified:tests/test_config.py+68 added-66 removed
15 unmodified lines16 import pytest17 18 19 # config keys used for the TestConfig20-TEST_KEY = 'foo'21-SECRET_KEY = 'config'20+TEST_KEY = "foo"21+SECRET_KEY = "config"22 23 24 def common_object_test(app):25- assert app.secret_key == 'config'26- assert app.config['TEST_KEY'] == 'foo'27- assert 'TestConfig' not in app.config25+ assert app.secret_key == "config"26+ assert app.config["TEST_KEY"] == "foo"27+ assert "TestConfig" not in app.config28 29 30 def test_config_from_file():31 app = flask.Flask(__name__)32- app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')32+ app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")33 common_object_test(app)34 35 36 def test_config_from_object():4 unmodified lines41 42 def test_config_from_json():43 app = flask.Flask(__name__)44 current_dir = os.path.dirname(os.path.abspath(__file__))45- app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))45+ app.config.from_json(os.path.join(current_dir, "static", "config.json"))46 common_object_test(app)47 48 49 def test_config_from_mapping():50 app = flask.Flask(__name__)51- app.config.from_mapping({52- 'SECRET_KEY': 'config',53- 'TEST_KEY': 'foo'54- })51+ app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})52 common_object_test(app)53 54 app = flask.Flask(__name__)58- app.config.from_mapping([59- ('SECRET_KEY', 'config'),60- ('TEST_KEY', 'foo')61- ])55+ app.config.from_mapping([("SECRET_KEY", "config"), ("TEST_KEY", "foo")])56 common_object_test(app)57 58 app = flask.Flask(__name__)65- app.config.from_mapping(66- SECRET_KEY='config',67- TEST_KEY='foo'68- )59+ app.config.from_mapping(SECRET_KEY="config", TEST_KEY="foo")60 common_object_test(app)61 62 app = flask.Flask(__name__)63 with pytest.raises(TypeError):73- app.config.from_mapping(74- {}, {}75- )64+ app.config.from_mapping({}, {})65 66 67 def test_config_from_class():68 class Base(object):80- TEST_KEY = 'foo'69+ TEST_KEY = "foo"70 71 class Test(Base):83- SECRET_KEY = 'config'72+ SECRET_KEY = "config"73 74 app = flask.Flask(__name__)75 app.config.from_object(Test)76 common_object_test(app)4 unmodified lines81 try:82 os.environ = {}83 app = flask.Flask(__name__)84 with pytest.raises(RuntimeError) as e:96- app.config.from_envvar('FOO_SETTINGS')85+ app.config.from_envvar("FOO_SETTINGS")86 assert "'FOO_SETTINGS' is not set" in str(e.value)98- assert not app.config.from_envvar('FOO_SETTINGS', silent=True)87+ assert not app.config.from_envvar("FOO_SETTINGS", silent=True)88 100- os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}101- assert app.config.from_envvar('FOO_SETTINGS')89+ os.environ = {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}90+ assert app.config.from_envvar("FOO_SETTINGS")91 common_object_test(app)92 finally:93 os.environ = env94 95 96 def test_config_from_envvar_missing():97 env = os.environ98 try:110- os.environ = {'FOO_SETTINGS': 'missing.cfg'}99+ os.environ = {"FOO_SETTINGS": "missing.cfg"}100 with pytest.raises(IOError) as e:101 app = flask.Flask(__name__)113- app.config.from_envvar('FOO_SETTINGS')102+ app.config.from_envvar("FOO_SETTINGS")103 msg = str(e.value)115- assert msg.startswith('[Errno 2] Unable to load configuration '116- 'file (No such file or directory):')104+ assert msg.startswith(105+ "[Errno 2] Unable to load configuration "106+ "file (No such file or directory):"107+ )108 assert msg.endswith("missing.cfg'")118- assert not app.config.from_envvar('FOO_SETTINGS', silent=True)109+ assert not app.config.from_envvar("FOO_SETTINGS", silent=True)110 finally:111 os.environ = env112 113 114 def test_config_missing():115 app = flask.Flask(__name__)116 with pytest.raises(IOError) as e:126- app.config.from_pyfile('missing.cfg')117+ app.config.from_pyfile("missing.cfg")118 msg = str(e.value)128- assert msg.startswith('[Errno 2] Unable to load configuration '129- 'file (No such file or directory):')119+ assert msg.startswith(120+ "[Errno 2] Unable to load configuration " "file (No such file or directory):"121+ )122 assert msg.endswith("missing.cfg'")131- assert not app.config.from_pyfile('missing.cfg', silent=True)123+ assert not app.config.from_pyfile("missing.cfg", silent=True)124 125 126 def test_config_missing_json():127 app = flask.Flask(__name__)128 with pytest.raises(IOError) as e:137- app.config.from_json('missing.json')129+ app.config.from_json("missing.json")130 msg = str(e.value)139- assert msg.startswith('[Errno 2] Unable to load configuration '140- 'file (No such file or directory):')131+ assert msg.startswith(132+ "[Errno 2] Unable to load configuration " "file (No such file or directory):"133+ )134 assert msg.endswith("missing.json'")142- assert not app.config.from_json('missing.json', silent=True)135+ assert not app.config.from_json("missing.json", silent=True)136 137 138 def test_custom_config_class():139 class Config(flask.Config):140 pass141 142 class Flask(flask.Flask):143 config_class = Config144+145 app = Flask(__name__)146 assert isinstance(app.config, Config)147 app.config.from_object(__name__)148 common_object_test(app)149 150 151 def test_session_lifetime():152 app = flask.Flask(__name__)159- app.config['PERMANENT_SESSION_LIFETIME'] = 42153+ app.config["PERMANENT_SESSION_LIFETIME"] = 42154 assert app.permanent_session_lifetime.seconds == 42155 156 157 def test_send_file_max_age():158 app = flask.Flask(__name__)165- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600159+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600160 assert app.send_file_max_age_default.seconds == 3600167- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=2)161+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = timedelta(hours=2)162 assert app.send_file_max_age_default.seconds == 7200163 164 165 def test_get_namespace():166 app = flask.Flask(__name__)173- app.config['FOO_OPTION_1'] = 'foo option 1'174- app.config['FOO_OPTION_2'] = 'foo option 2'175- app.config['BAR_STUFF_1'] = 'bar stuff 1'176- app.config['BAR_STUFF_2'] = 'bar stuff 2'177- foo_options = app.config.get_namespace('FOO_')167+ app.config["FOO_OPTION_1"] = "foo option 1"168+ app.config["FOO_OPTION_2"] = "foo option 2"169+ app.config["BAR_STUFF_1"] = "bar stuff 1"170+ app.config["BAR_STUFF_2"] = "bar stuff 2"171+ foo_options = app.config.get_namespace("FOO_")172 assert 2 == len(foo_options)179- assert 'foo option 1' == foo_options['option_1']180- assert 'foo option 2' == foo_options['option_2']181- bar_options = app.config.get_namespace('BAR_', lowercase=False)173+ assert "foo option 1" == foo_options["option_1"]174+ assert "foo option 2" == foo_options["option_2"]175+ bar_options = app.config.get_namespace("BAR_", lowercase=False)176 assert 2 == len(bar_options)183- assert 'bar stuff 1' == bar_options['STUFF_1']184- assert 'bar stuff 2' == bar_options['STUFF_2']185- foo_options = app.config.get_namespace('FOO_', trim_namespace=False)177+ assert "bar stuff 1" == bar_options["STUFF_1"]178+ assert "bar stuff 2" == bar_options["STUFF_2"]179+ foo_options = app.config.get_namespace("FOO_", trim_namespace=False)180 assert 2 == len(foo_options)187- assert 'foo option 1' == foo_options['foo_option_1']188- assert 'foo option 2' == foo_options['foo_option_2']189- bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)181+ assert "foo option 1" == foo_options["foo_option_1"]182+ assert "foo option 2" == foo_options["foo_option_2"]183+ bar_options = app.config.get_namespace(184+ "BAR_", lowercase=False, trim_namespace=False185+ )186 assert 2 == len(bar_options)191- assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192- assert 'bar stuff 2' == bar_options['BAR_STUFF_2']187+ assert "bar stuff 1" == bar_options["BAR_STUFF_1"]188+ assert "bar stuff 2" == bar_options["BAR_STUFF_2"]189 190 195-@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])191+@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-15", "latin-1"])192 def test_from_pyfile_weird_encoding(tmpdir, encoding):197- f = tmpdir.join('my_config.py')198- f.write_binary(textwrap.dedent(u'''193+ f = tmpdir.join("my_config.py")194+ f.write_binary(195+ textwrap.dedent(196+ u"""197 # -*- coding: {0} -*-198 TEST_VALUE = "föö"201- '''.format(encoding)).encode(encoding))199+ """.format(200+ encoding201+ )202+ ).encode(encoding)203+ )204 app = flask.Flask(__name__)205 app.config.from_pyfile(str(f))204- value = app.config['TEST_VALUE']206+ value = app.config["TEST_VALUE"]207 if PY2:208 value = value.decode(encoding)207- assert value == u'föö'209+ assert value == u"föö"modified:tests/test_helpers.py+411 added-355 removed
15 unmodified lines16 17 import pytest18 from werkzeug.datastructures import Range19 from werkzeug.exceptions import BadRequest, NotFound20-from werkzeug.http import (21- http_date, parse_cache_control_header,22- parse_options_header23-)20+from werkzeug.http import http_date, parse_cache_control_header, parse_options_header21 22 import flask23 from flask import json24 from flask._compat import StringIO, text_type2 unmodified lines27 28 def has_encoding(name):29 try:30 import codecs31+32 codecs.lookup(name)33 return True34 except LookupError:35 return False4 unmodified lines40 41 This represents a ``pathlib.Path`` object in python 3.42 See: https://www.python.org/dev/peps/pep-0519/43 """44+45 def __init__(self, path):46 self.path = path47 48 def __fspath__(self):21 unmodified lines70 return datetime.timedelta()71 72 73 class TestJSON(object):75- @pytest.mark.parametrize('value', (76- 1, 't', True, False, None,77- [], [1, 2, 3],78- {}, {'foo': u'🐍'},79- ))80- @pytest.mark.parametrize('encoding', (81- 'utf-8', 'utf-8-sig',82- 'utf-16-le', 'utf-16-be', 'utf-16',83- 'utf-32-le', 'utf-32-be', 'utf-32',84- ))74+ @pytest.mark.parametrize(75+ "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"})76+ )77+ @pytest.mark.parametrize(78+ "encoding",79+ (80+ "utf-8",81+ "utf-8-sig",82+ "utf-16-le",83+ "utf-16-be",84+ "utf-16",85+ "utf-32-le",86+ "utf-32-be",87+ "utf-32",88+ ),89+ )90 def test_detect_encoding(self, value, encoding):91 data = json.dumps(value).encode(encoding)92 assert json.detect_encoding(data) == encoding93 assert json.loads(data) == value94 95 def test_ignore_cached_json(self, app):91- with app.test_request_context('/', method='POST', data='malformed',92- content_type='application/json'):96+ with app.test_request_context(97+ "/", method="POST", data="malformed", content_type="application/json"98+ ):99 assert flask.request.get_json(silent=True, cache=True) is None100 with pytest.raises(BadRequest):101 flask.request.get_json(silent=False, cache=False)102 103 def test_different_silent_on_bad_request(self, app):104 with app.test_request_context(99- '/', method='POST', data='malformed',100- content_type='application/json'):105+ "/", method="POST", data="malformed", content_type="application/json"106+ ):107 assert flask.request.get_json(silent=True) is None108 with pytest.raises(BadRequest):109 flask.request.get_json(silent=False)110 111 def test_different_silent_on_normal_request(self, app):106- with app.test_request_context('/', method='POST', json={'foo': 'bar'}):112+ with app.test_request_context("/", method="POST", json={"foo": "bar"}):113 silent_rv = flask.request.get_json(silent=True)114 normal_rv = flask.request.get_json(silent=False)115 assert silent_rv is normal_rv110- assert normal_rv['foo'] == 'bar'116+ assert normal_rv["foo"] == "bar"117 112- def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):113- app.config['DEBUG'] = True114- app.config['TRAP_BAD_REQUEST_ERRORS'] = False118+ def test_post_empty_json_adds_exception_to_response_content_in_debug(119+ self, app, client120+ ):121+ app.config["DEBUG"] = True122+ app.config["TRAP_BAD_REQUEST_ERRORS"] = False123 116- @app.route('/json', methods=['POST'])124+ @app.route("/json", methods=["POST"])125 def post_json():126 flask.request.get_json()127 return None128 121- rv = client.post('/json', data=None, content_type='application/json')129+ rv = client.post("/json", data=None, content_type="application/json")130 assert rv.status_code == 400123- assert b'Failed to decode JSON object' in rv.data131+ assert b"Failed to decode JSON object" in rv.data132 125- def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):126- app.config['DEBUG'] = False127- app.config['TRAP_BAD_REQUEST_ERRORS'] = False133+ def test_post_empty_json_wont_add_exception_to_response_if_no_debug(134+ self, app, client135+ ):136+ app.config["DEBUG"] = False137+ app.config["TRAP_BAD_REQUEST_ERRORS"] = False138 129- @app.route('/json', methods=['POST'])139+ @app.route("/json", methods=["POST"])140 def post_json():141 flask.request.get_json()142 return None143 134- rv = client.post('/json', data=None, content_type='application/json')144+ rv = client.post("/json", data=None, content_type="application/json")145 assert rv.status_code == 400136- assert b'Failed to decode JSON object' not in rv.data146+ assert b"Failed to decode JSON object" not in rv.data147 148 def test_json_bad_requests(self, app, client):139-140- @app.route('/json', methods=['POST'])149+ @app.route("/json", methods=["POST"])150 def return_json():151 return flask.jsonify(foo=text_type(flask.request.get_json()))152 144- rv = client.post('/json', data='malformed', content_type='application/json')153+ rv = client.post("/json", data="malformed", content_type="application/json")154 assert rv.status_code == 400155 156 def test_json_custom_mimetypes(self, app, client):148-149- @app.route('/json', methods=['POST'])157+ @app.route("/json", methods=["POST"])158 def return_json():159 return flask.request.get_json()160 153- rv = client.post('/json', data='"foo"', content_type='application/x+json')154- assert rv.data == b'foo'161+ rv = client.post("/json", data='"foo"', content_type="application/x+json")162+ assert rv.data == b"foo"163 156- @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])164+ @pytest.mark.parametrize(165+ "test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')]166+ )167 def test_json_as_unicode(self, test_value, expected, app, app_ctx):168 159- app.config['JSON_AS_ASCII'] = test_value160- rv = flask.json.dumps(u'\N{SNOWMAN}')169+ app.config["JSON_AS_ASCII"] = test_value170+ rv = flask.json.dumps(u"\N{SNOWMAN}")171 assert rv == expected172 173 def test_json_dump_to_file(self, app, app_ctx):164- test_data = {'name': 'Flask'}174+ test_data = {"name": "Flask"}175 out = StringIO()176 177 flask.json.dump(test_data, out)178 out.seek(0)179 rv = flask.json.load(out)180 assert rv == test_data181 172- @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])182+ @pytest.mark.parametrize(183+ "test_value", [0, -1, 1, 23, 3.14, "s", "longer string", True, False, None]184+ )185 def test_jsonify_basic_types(self, test_value, app, client):186 """Test jsonify with basic types."""187 176- url = '/jsonify_basic_types'188+ url = "/jsonify_basic_types"189 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))190 rv = client.get(url)179- assert rv.mimetype == 'application/json'191+ assert rv.mimetype == "application/json"192 assert flask.json.loads(rv.data) == test_value193 194 def test_jsonify_dicts(self, app, client):195 """Test jsonify with dicts and kwargs unpacking."""184- d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',185- 'e': 'Hi', 'f': True, 'g': False,186- 'h': ['test list', 10, False],187- 'i': {'test': 'dict'}}196+ d = {197+ "a": 0,198+ "b": 23,199+ "c": 3.14,200+ "d": "t",201+ "e": "Hi",202+ "f": True,203+ "g": False,204+ "h": ["test list", 10, False],205+ "i": {"test": "dict"},206+ }207 189- @app.route('/kw')208+ @app.route("/kw")209 def return_kwargs():210 return flask.jsonify(**d)211 193- @app.route('/dict')212+ @app.route("/dict")213 def return_dict():214 return flask.jsonify(d)215 197- for url in '/kw', '/dict':216+ for url in "/kw", "/dict":217 rv = client.get(url)199- assert rv.mimetype == 'application/json'218+ assert rv.mimetype == "application/json"219 assert flask.json.loads(rv.data) == d220 221 def test_jsonify_arrays(self, app, client):222 """Test jsonify of lists and args unpacking."""223 l = [205- 0, 42, 3.14, 't', 'hello', True, False,206- ['test list', 2, False],207- {'test': 'dict'}224+ 0,225+ 42,226+ 3.14,227+ "t",228+ "hello",229+ True,230+ False,231+ ["test list", 2, False],232+ {"test": "dict"},233 ]234 210- @app.route('/args_unpack')235+ @app.route("/args_unpack")236 def return_args_unpack():237 return flask.jsonify(*l)238 214- @app.route('/array')239+ @app.route("/array")240 def return_array():241 return flask.jsonify(l)242 218- for url in '/args_unpack', '/array':243+ for url in "/args_unpack", "/array":244 rv = client.get(url)220- assert rv.mimetype == 'application/json'245+ assert rv.mimetype == "application/json"246 assert flask.json.loads(rv.data) == l247 248 def test_jsonify_date_types(self, app, client):249 """Test jsonify with datetime.date and datetime.datetime types."""250 test_dates = (251 datetime.datetime(1973, 3, 11, 6, 30, 45),227- datetime.date(1975, 1, 5)252+ datetime.date(1975, 1, 5),253 )254 255 for i, d in enumerate(test_dates):231- url = '/datetest{0}'.format(i)256+ url = "/datetest{0}".format(i)257 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))258 rv = client.get(url)234- assert rv.mimetype == 'application/json'235- assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())259+ assert rv.mimetype == "application/json"260+ assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple())261 237- @pytest.mark.parametrize('tz', (('UTC', 0), ('PST', -8), ('KST', 9)))262+ @pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9)))263 def test_jsonify_aware_datetimes(self, tz):264 """Test if aware datetime.datetime objects are converted into GMT."""265 tzinfo = FixedOffset(hours=tz[1], name=tz[0])266 dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)242- gmt = FixedOffset(hours=0, name='GMT')267+ gmt = FixedOffset(hours=0, name="GMT")268 expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')269 assert flask.json.JSONEncoder().encode(dt) == expected270 271 def test_jsonify_uuid_types(self, app, client):272 """Test jsonify with uuid.UUID types"""273 249- test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)250- url = '/uuid_test'274+ test_uuid = uuid.UUID(bytes=b"\xDE\xAD\xBE\xEF" * 4)275+ url = "/uuid_test"276 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))277 278 rv = client.get(url)279 255- rv_x = flask.json.loads(rv.data)['x']280+ rv_x = flask.json.loads(rv.data)["x"]281 assert rv_x == str(test_uuid)282 rv_uuid = uuid.UUID(rv_x)283 assert rv_uuid == test_uuid284 285 def test_json_attr(self, app, client):261-262- @app.route('/add', methods=['POST'])286+ @app.route("/add", methods=["POST"])287 def add():288 json = flask.request.get_json()265- return text_type(json['a'] + json['b'])289+ return text_type(json["a"] + json["b"])290 267- rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),268- content_type='application/json')269- assert rv.data == b'3'291+ rv = client.post(292+ "/add",293+ data=flask.json.dumps({"a": 1, "b": 2}),294+ content_type="application/json",295+ )296+ assert rv.data == b"3"297 298 def test_template_escaping(self, app, req_ctx):299 render = flask.render_template_string273- rv = flask.json.htmlsafe_dumps('</script>')300+ rv = flask.json.htmlsafe_dumps("</script>")301 assert rv == u'"\\u003c/script\\u003e"'302 assert type(rv) == text_type303 rv = render('{{ "</script>"|tojson }}')304 assert rv == '"\\u003c/script\\u003e"'4 unmodified lines309 rv = render('{{ "&"|tojson }}')310 assert rv == '"\\u0026"'311 rv = render('{{ "\'"|tojson }}')312 assert rv == '"\\u0027"'286- rv = render("<a ng-data='{{ data|tojson }}'></a>",287- data={'x': ["foo", "bar", "baz'"]})313+ rv = render(314+ "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]}315+ )316 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'317 318 def test_json_customization(self, app, client):319 class X(object):2 unmodified lines322 323 class MyEncoder(flask.json.JSONEncoder):324 def default(self, o):325 if isinstance(o, X):298- return '<%d>' % o.val326+ return "<%d>" % o.val327 return flask.json.JSONEncoder.default(self, o)328 329 class MyDecoder(flask.json.JSONDecoder):330 def __init__(self, *args, **kwargs):303- kwargs.setdefault('object_hook', self.object_hook)331+ kwargs.setdefault("object_hook", self.object_hook)332 flask.json.JSONDecoder.__init__(self, *args, **kwargs)333 334 def object_hook(self, obj):307- if len(obj) == 1 and '_foo' in obj:308- return X(obj['_foo'])335+ if len(obj) == 1 and "_foo" in obj:336+ return X(obj["_foo"])337 return obj338 339 app.json_encoder = MyEncoder340 app.json_decoder = MyDecoder341 314- @app.route('/', methods=['POST'])342+ @app.route("/", methods=["POST"])343 def index():316- return flask.json.dumps(flask.request.get_json()['x'])344+ return flask.json.dumps(flask.request.get_json()["x"])345 318- rv = client.post('/', data=flask.json.dumps({319- 'x': {'_foo': 42}320- }), content_type='application/json')346+ rv = client.post(347+ "/",348+ data=flask.json.dumps({"x": {"_foo": 42}}),349+ content_type="application/json",350+ )351 assert rv.data == b'"<42>"'352 353 def test_blueprint_json_customization(self, app, client):354 class X(object):2 unmodified lines357 358 class MyEncoder(flask.json.JSONEncoder):359 def default(self, o):360 if isinstance(o, X):331- return '<%d>' % o.val361+ return "<%d>" % o.val362 363 return flask.json.JSONEncoder.default(self, o)364 365 class MyDecoder(flask.json.JSONDecoder):366 def __init__(self, *args, **kwargs):337- kwargs.setdefault('object_hook', self.object_hook)367+ kwargs.setdefault("object_hook", self.object_hook)368 flask.json.JSONDecoder.__init__(self, *args, **kwargs)369 370 def object_hook(self, obj):341- if len(obj) == 1 and '_foo' in obj:342- return X(obj['_foo'])371+ if len(obj) == 1 and "_foo" in obj:372+ return X(obj["_foo"])373 374 return obj375 346- bp = flask.Blueprint('bp', __name__)376+ bp = flask.Blueprint("bp", __name__)377 bp.json_encoder = MyEncoder378 bp.json_decoder = MyDecoder379 350- @bp.route('/bp', methods=['POST'])380+ @bp.route("/bp", methods=["POST"])381 def index():352- return flask.json.dumps(flask.request.get_json()['x'])382+ return flask.json.dumps(flask.request.get_json()["x"])383 384 app.register_blueprint(bp)385 356- rv = client.post('/bp', data=flask.json.dumps({357- 'x': {'_foo': 42}358- }), content_type='application/json')386+ rv = client.post(387+ "/bp",388+ data=flask.json.dumps({"x": {"_foo": 42}}),389+ content_type="application/json",390+ )391 assert rv.data == b'"<42>"'392 393 def test_modified_url_encoding(self, app, client):394 class ModifiedRequest(flask.Request):363- url_charset = 'euc-kr'395+ url_charset = "euc-kr"396 397 app.request_class = ModifiedRequest366- app.url_map.charset = 'euc-kr'398+ app.url_map.charset = "euc-kr"399 368- @app.route('/')400+ @app.route("/")401 def index():370- return flask.request.args['foo']402+ return flask.request.args["foo"]403 372- rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))404+ rv = client.get(u"/?foo=정상처리".encode("euc-kr"))405 assert rv.status_code == 200374- assert rv.data == u'정상처리'.encode('utf-8')406+ assert rv.data == u"정상처리".encode("utf-8")407 376- if not has_encoding('euc-kr'):408+ if not has_encoding("euc-kr"):409 test_modified_url_encoding = None410 411 def test_json_key_sorting(self, app, client):412 app.debug = True413 382- assert app.config['JSON_SORT_KEYS'] == True383- d = dict.fromkeys(range(20), 'foo')414+ assert app.config["JSON_SORT_KEYS"] == True415+ d = dict.fromkeys(range(20), "foo")416 385- @app.route('/')417+ @app.route("/")418 def index():419 return flask.jsonify(values=d)420 389- rv = client.get('/')390- lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]421+ rv = client.get("/")422+ lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()]423 sorted_by_str = [392- '{',424+ "{",425 '"values": {',426 '"0": "foo",',427 '"1": "foo",',428 '"10": "foo",',13 unmodified lines442 '"6": "foo",',443 '"7": "foo",',444 '"8": "foo",',445 '"9": "foo"',414- '}',415- '}'446+ "}",447+ "}",448 ]449 sorted_by_int = [418- '{',450+ "{",451 '"values": {',452 '"0": "foo",',453 '"1": "foo",',454 '"2": "foo",',13 unmodified lines468 '"16": "foo",',469 '"17": "foo",',470 '"18": "foo",',471 '"19": "foo"',440- '}',441- '}'472+ "}",473+ "}",474 ]475 476 try:477 assert lines == sorted_by_int2 unmodified lines480 481 482 class TestSendfile(object):483 def test_send_file_regular(self, app, req_ctx):452- rv = flask.send_file('static/index.html')484+ rv = flask.send_file("static/index.html")485 assert rv.direct_passthrough454- assert rv.mimetype == 'text/html'455- with app.open_resource('static/index.html') as f:486+ assert rv.mimetype == "text/html"487+ with app.open_resource("static/index.html") as f:488 rv.direct_passthrough = False489 assert rv.data == f.read()490 rv.close()491 492 def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):493 app.use_x_sendfile = True462- rv = flask.send_file('static/index.html')494+ rv = flask.send_file("static/index.html")495 assert rv.direct_passthrough464- assert 'x-sendfile' in rv.headers465- assert rv.headers['x-sendfile'] == \466- os.path.join(app.root_path, 'static/index.html')467- assert rv.mimetype == 'text/html'496+ assert "x-sendfile" in rv.headers497+ assert rv.headers["x-sendfile"] == os.path.join(498+ app.root_path, "static/index.html"499+ )500+ assert rv.mimetype == "text/html"501 rv.close()502 503 def test_send_file_last_modified(self, app, client):504 last_modified = datetime.datetime(1999, 1, 1)505 473- @app.route('/')506+ @app.route("/")507 def index():475- return flask.send_file(StringIO("party like it's"),476- last_modified=last_modified,477- mimetype='text/plain')508+ return flask.send_file(509+ StringIO("party like it's"),510+ last_modified=last_modified,511+ mimetype="text/plain",512+ )513 479- rv = client.get('/')514+ rv = client.get("/")515 assert rv.last_modified == last_modified516 517 def test_send_file_object_without_mimetype(self, app, req_ctx):518 with pytest.raises(ValueError) as excinfo:519 flask.send_file(StringIO("LOL"))485- assert 'Unable to infer MIME-type' in str(excinfo)486- assert 'no filename is available' in str(excinfo)520+ assert "Unable to infer MIME-type" in str(excinfo)521+ assert "no filename is available" in str(excinfo)522 488- flask.send_file(StringIO("LOL"), attachment_filename='filename')523+ flask.send_file(StringIO("LOL"), attachment_filename="filename")524 525 def test_send_file_object(self, app, req_ctx):491- with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:492- rv = flask.send_file(f, mimetype='text/html')526+ with open(os.path.join(app.root_path, "static/index.html"), mode="rb") as f:527+ rv = flask.send_file(f, mimetype="text/html")528 rv.direct_passthrough = False494- with app.open_resource('static/index.html') as f:529+ with app.open_resource("static/index.html") as f:530 assert rv.data == f.read()496- assert rv.mimetype == 'text/html'531+ assert rv.mimetype == "text/html"532 rv.close()533 534 app.use_x_sendfile = True535 501- with open(os.path.join(app.root_path, 'static/index.html')) as f:502- rv = flask.send_file(f, mimetype='text/html')503- assert rv.mimetype == 'text/html'504- assert 'x-sendfile' not in rv.headers536+ with open(os.path.join(app.root_path, "static/index.html")) as f:537+ rv = flask.send_file(f, mimetype="text/html")538+ assert rv.mimetype == "text/html"539+ assert "x-sendfile" not in rv.headers540 rv.close()541 542 app.use_x_sendfile = False508- f = StringIO('Test')509- rv = flask.send_file(f, mimetype='application/octet-stream')543+ f = StringIO("Test")544+ rv = flask.send_file(f, mimetype="application/octet-stream")545 rv.direct_passthrough = False511- assert rv.data == b'Test'512- assert rv.mimetype == 'application/octet-stream'546+ assert rv.data == b"Test"547+ assert rv.mimetype == "application/octet-stream"548 rv.close()549 550 class PyStringIO(object):551 def __init__(self, *args, **kwargs):1 unmodified line553 554 def __getattr__(self, name):555 return getattr(self._io, name)556 522- f = PyStringIO('Test')523- f.name = 'test.txt'557+ f = PyStringIO("Test")558+ f.name = "test.txt"559 rv = flask.send_file(f, attachment_filename=f.name)560 rv.direct_passthrough = False526- assert rv.data == b'Test'527- assert rv.mimetype == 'text/plain'561+ assert rv.data == b"Test"562+ assert rv.mimetype == "text/plain"563 rv.close()564 530- f = StringIO('Test')531- rv = flask.send_file(f, mimetype='text/plain')565+ f = StringIO("Test")566+ rv = flask.send_file(f, mimetype="text/plain")567 rv.direct_passthrough = False533- assert rv.data == b'Test'534- assert rv.mimetype == 'text/plain'568+ assert rv.data == b"Test"569+ assert rv.mimetype == "text/plain"570 rv.close()571 572 app.use_x_sendfile = True573 539- f = StringIO('Test')540- rv = flask.send_file(f, mimetype='text/html')541- assert 'x-sendfile' not in rv.headers574+ f = StringIO("Test")575+ rv = flask.send_file(f, mimetype="text/html")576+ assert "x-sendfile" not in rv.headers577 rv.close()578 579 def test_send_file_pathlike(self, app, req_ctx):545- rv = flask.send_file(FakePath('static/index.html'))580+ rv = flask.send_file(FakePath("static/index.html"))581 assert rv.direct_passthrough547- assert rv.mimetype == 'text/html'548- with app.open_resource('static/index.html') as f:582+ assert rv.mimetype == "text/html"583+ with app.open_resource("static/index.html") as f:584 rv.direct_passthrough = False585 assert rv.data == f.read()586 rv.close()587 588 @pytest.mark.skipif(554- not callable(getattr(Range, 'to_content_range_header', None)),555- reason="not implemented within werkzeug"589+ not callable(getattr(Range, "to_content_range_header", None)),590+ reason="not implemented within werkzeug",591 )592 def test_send_file_range_request(self, app, client):558- @app.route('/')593+ @app.route("/")594 def index():560- return flask.send_file('static/index.html', conditional=True)595+ return flask.send_file("static/index.html", conditional=True)596 562- rv = client.get('/', headers={'Range': 'bytes=4-15'})597+ rv = client.get("/", headers={"Range": "bytes=4-15"})598 assert rv.status_code == 206564- with app.open_resource('static/index.html') as f:599+ with app.open_resource("static/index.html") as f:600 assert rv.data == f.read()[4:16]601 rv.close()602 568- rv = client.get('/', headers={'Range': 'bytes=4-'})603+ rv = client.get("/", headers={"Range": "bytes=4-"})604 assert rv.status_code == 206570- with app.open_resource('static/index.html') as f:605+ with app.open_resource("static/index.html") as f:606 assert rv.data == f.read()[4:]607 rv.close()608 574- rv = client.get('/', headers={'Range': 'bytes=4-1000'})609+ rv = client.get("/", headers={"Range": "bytes=4-1000"})610 assert rv.status_code == 206576- with app.open_resource('static/index.html') as f:611+ with app.open_resource("static/index.html") as f:612 assert rv.data == f.read()[4:]613 rv.close()614 580- rv = client.get('/', headers={'Range': 'bytes=-10'})615+ rv = client.get("/", headers={"Range": "bytes=-10"})616 assert rv.status_code == 206582- with app.open_resource('static/index.html') as f:617+ with app.open_resource("static/index.html") as f:618 assert rv.data == f.read()[-10:]619 rv.close()620 586- rv = client.get('/', headers={'Range': 'bytes=1000-'})621+ rv = client.get("/", headers={"Range": "bytes=1000-"})622 assert rv.status_code == 416623 rv.close()624 590- rv = client.get('/', headers={'Range': 'bytes=-'})625+ rv = client.get("/", headers={"Range": "bytes=-"})626 assert rv.status_code == 416627 rv.close()628 594- rv = client.get('/', headers={'Range': 'somethingsomething'})629+ rv = client.get("/", headers={"Range": "somethingsomething"})630 assert rv.status_code == 416631 rv.close()632 598- last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(599- os.path.join(app.root_path, 'static/index.html'))).replace(600- microsecond=0)633+ last_modified = datetime.datetime.utcfromtimestamp(634+ os.path.getmtime(os.path.join(app.root_path, "static/index.html"))635+ ).replace(microsecond=0)636 602- rv = client.get('/', headers={'Range': 'bytes=4-15',603- 'If-Range': http_date(last_modified)})637+ rv = client.get(638+ "/", headers={"Range": "bytes=4-15", "If-Range": http_date(last_modified)}639+ )640 assert rv.status_code == 206641 rv.close()642 607- rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(608- datetime.datetime(1999, 1, 1))})643+ rv = client.get(644+ "/",645+ headers={646+ "Range": "bytes=4-15",647+ "If-Range": http_date(datetime.datetime(1999, 1, 1)),648+ },649+ )650 assert rv.status_code == 200651 rv.close()652 653 def test_send_file_range_request_bytesio(self, app, client):613- @app.route('/')654+ @app.route("/")655 def index():615- file = io.BytesIO(b'somethingsomething')656+ file = io.BytesIO(b"somethingsomething")657 return flask.send_file(617- file, attachment_filename='filename', conditional=True658+ file, attachment_filename="filename", conditional=True659 )660 620- rv = client.get('/', headers={'Range': 'bytes=4-15'})661+ rv = client.get("/", headers={"Range": "bytes=4-15"})662 assert rv.status_code == 206622- assert rv.data == b'somethingsomething'[4:16]663+ assert rv.data == b"somethingsomething"[4:16]664 rv.close()665 666 @pytest.mark.skipif(626- not callable(getattr(Range, 'to_content_range_header', None)),627- reason="not implemented within werkzeug"667+ not callable(getattr(Range, "to_content_range_header", None)),668+ reason="not implemented within werkzeug",669 )670 def test_send_file_range_request_xsendfile_invalid(self, app, client):671 # https://github.com/pallets/flask/issues/2526672 app.use_x_sendfile = True673 633- @app.route('/')674+ @app.route("/")675 def index():635- return flask.send_file('static/index.html', conditional=True)676+ return flask.send_file("static/index.html", conditional=True)677 637- rv = client.get('/', headers={'Range': 'bytes=1000-'})678+ rv = client.get("/", headers={"Range": "bytes=1000-"})679 assert rv.status_code == 416680 rv.close()681 682 def test_attachment(self, app, req_ctx):683 app = flask.Flask(__name__)684 with app.test_request_context():644- with open(os.path.join(app.root_path, 'static/index.html')) as f:645- rv = flask.send_file(f, as_attachment=True,646- attachment_filename='index.html')647- value, options = \648- parse_options_header(rv.headers['Content-Disposition'])649- assert value == 'attachment'685+ with open(os.path.join(app.root_path, "static/index.html")) as f:686+ rv = flask.send_file(687+ f, as_attachment=True, attachment_filename="index.html"688+ )689+ value, options = parse_options_header(rv.headers["Content-Disposition"])690+ assert value == "attachment"691 rv.close()692 652- with open(os.path.join(app.root_path, 'static/index.html')) as f:653- rv = flask.send_file(f, as_attachment=True,654- attachment_filename='index.html')655- value, options = \656- parse_options_header(rv.headers['Content-Disposition'])657- assert value == 'attachment'658- assert options['filename'] == 'index.html'659- assert 'filename*' not in rv.headers['Content-Disposition']693+ with open(os.path.join(app.root_path, "static/index.html")) as f:694+ rv = flask.send_file(695+ f, as_attachment=True, attachment_filename="index.html"696+ )697+ value, options = parse_options_header(rv.headers["Content-Disposition"])698+ assert value == "attachment"699+ assert options["filename"] == "index.html"700+ assert "filename*" not in rv.headers["Content-Disposition"]701 rv.close()702 662- rv = flask.send_file('static/index.html', as_attachment=True)663- value, options = parse_options_header(rv.headers['Content-Disposition'])664- assert value == 'attachment'665- assert options['filename'] == 'index.html'703+ rv = flask.send_file("static/index.html", as_attachment=True)704+ value, options = parse_options_header(rv.headers["Content-Disposition"])705+ assert value == "attachment"706+ assert options["filename"] == "index.html"707 rv.close()708 668- rv = flask.send_file(StringIO('Test'), as_attachment=True,669- attachment_filename='index.txt',670- add_etags=False)671- assert rv.mimetype == 'text/plain'672- value, options = parse_options_header(rv.headers['Content-Disposition'])673- assert value == 'attachment'674- assert options['filename'] == 'index.txt'709+ rv = flask.send_file(710+ StringIO("Test"),711+ as_attachment=True,712+ attachment_filename="index.txt",713+ add_etags=False,714+ )715+ assert rv.mimetype == "text/plain"716+ value, options = parse_options_header(rv.headers["Content-Disposition"])717+ assert value == "attachment"718+ assert options["filename"] == "index.txt"719 rv.close()720 677- @pytest.mark.usefixtures('req_ctx')678- @pytest.mark.parametrize(('filename', 'ascii', 'utf8'), (679- ('index.html', 'index.html', False),680- (u'Ñandú/pingüino.txt', '"Nandu/pinguino.txt"',681- '%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt'),682- (u'Vögel.txt', 'Vogel.txt', 'V%C3%B6gel.txt'),683- # Native string not marked as Unicode on Python 2684- ('tést.txt', 'test.txt', 't%C3%A9st.txt'),685- ))721+ @pytest.mark.usefixtures("req_ctx")722+ @pytest.mark.parametrize(723+ ("filename", "ascii", "utf8"),724+ (725+ ("index.html", "index.html", False),726+ (727+ u"Ñandú/pingüino.txt",728+ '"Nandu/pinguino.txt"',729+ "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",730+ ),731+ (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),732+ # Native string not marked as Unicode on Python 2733+ ("tést.txt", "test.txt", "t%C3%A9st.txt"),734+ ),735+ )736 def test_attachment_filename_encoding(self, filename, ascii, utf8):687- rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=filename)737+ rv = flask.send_file(738+ "static/index.html", as_attachment=True, attachment_filename=filename739+ )740 rv.close()689- content_disposition = rv.headers['Content-Disposition']690- assert 'filename=%s' % ascii in content_disposition741+ content_disposition = rv.headers["Content-Disposition"]742+ assert "filename=%s" % ascii in content_disposition743 if utf8:744 assert "filename*=UTF-8''" + utf8 in content_disposition745 else:746 assert "filename*=UTF-8''" not in content_disposition1 unmodified line748 def test_static_file(self, app, req_ctx):749 # default cache timeout is 12 hours750 751 # Test with static file handler.700- rv = app.send_static_file('index.html')701- cc = parse_cache_control_header(rv.headers['Cache-Control'])752+ rv = app.send_static_file("index.html")753+ cc = parse_cache_control_header(rv.headers["Cache-Control"])754 assert cc.max_age == 12 * 60 * 60755 rv.close()756 # Test again with direct use of send_file utility.705- rv = flask.send_file('static/index.html')706- cc = parse_cache_control_header(rv.headers['Cache-Control'])757+ rv = flask.send_file("static/index.html")758+ cc = parse_cache_control_header(rv.headers["Cache-Control"])759 assert cc.max_age == 12 * 60 * 60760 rv.close()709- app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600761+ app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600762 763 # Test with static file handler.712- rv = app.send_static_file('index.html')713- cc = parse_cache_control_header(rv.headers['Cache-Control'])764+ rv = app.send_static_file("index.html")765+ cc = parse_cache_control_header(rv.headers["Cache-Control"])766 assert cc.max_age == 3600767 rv.close()768 # Test again with direct use of send_file utility.717- rv = flask.send_file('static/index.html')718- cc = parse_cache_control_header(rv.headers['Cache-Control'])769+ rv = flask.send_file("static/index.html")770+ cc = parse_cache_control_header(rv.headers["Cache-Control"])771 assert cc.max_age == 3600772 rv.close()773 774 # Test with static file handler.723- rv = app.send_static_file(FakePath('index.html'))724- cc = parse_cache_control_header(rv.headers['Cache-Control'])775+ rv = app.send_static_file(FakePath("index.html"))776+ cc = parse_cache_control_header(rv.headers["Cache-Control"])777 assert cc.max_age == 3600778 rv.close()779 780 class StaticFileApp(flask.Flask):2 unmodified lines783 784 app = StaticFileApp(__name__)785 with app.test_request_context():786 # Test with static file handler.735- rv = app.send_static_file('index.html')736- cc = parse_cache_control_header(rv.headers['Cache-Control'])787+ rv = app.send_static_file("index.html")788+ cc = parse_cache_control_header(rv.headers["Cache-Control"])789 assert cc.max_age == 10790 rv.close()791 # Test again with direct use of send_file utility.740- rv = flask.send_file('static/index.html')741- cc = parse_cache_control_header(rv.headers['Cache-Control'])792+ rv = flask.send_file("static/index.html")793+ cc = parse_cache_control_header(rv.headers["Cache-Control"])794 assert cc.max_age == 10795 rv.close()796 797 def test_send_from_directory(self, app, req_ctx):746- app.root_path = os.path.join(os.path.dirname(__file__),747- 'test_apps', 'subdomaintestmodule')748- rv = flask.send_from_directory('static', 'hello.txt')798+ app.root_path = os.path.join(799+ os.path.dirname(__file__), "test_apps", "subdomaintestmodule"800+ )801+ rv = flask.send_from_directory("static", "hello.txt")802 rv.direct_passthrough = False750- assert rv.data.strip() == b'Hello Subdomain'803+ assert rv.data.strip() == b"Hello Subdomain"804 rv.close()805 806 def test_send_from_directory_pathlike(self, app, req_ctx):754- app.root_path = os.path.join(os.path.dirname(__file__),755- 'test_apps', 'subdomaintestmodule')756- rv = flask.send_from_directory(FakePath('static'), FakePath('hello.txt'))807+ app.root_path = os.path.join(808+ os.path.dirname(__file__), "test_apps", "subdomaintestmodule"809+ )810+ rv = flask.send_from_directory(FakePath("static"), FakePath("hello.txt"))811 rv.direct_passthrough = False758- assert rv.data.strip() == b'Hello Subdomain'812+ assert rv.data.strip() == b"Hello Subdomain"813 rv.close()814 815 def test_send_from_directory_bad_request(self, app, req_ctx):762- app.root_path = os.path.join(os.path.dirname(__file__),763- 'test_apps', 'subdomaintestmodule')816+ app.root_path = os.path.join(817+ os.path.dirname(__file__), "test_apps", "subdomaintestmodule"818+ )819 820 with pytest.raises(BadRequest):766- flask.send_from_directory('static', 'bad\x00')821+ flask.send_from_directory("static", "bad\x00")822 823 824 class TestUrlFor(object):825 def test_url_for_with_anchor(self, app, req_ctx):771-772- @app.route('/')826+ @app.route("/")827 def index():774- return '42'828+ return "42"829 776- assert flask.url_for('index', _anchor='x y') == '/#x%20y'830+ assert flask.url_for("index", _anchor="x y") == "/#x%20y"831 832 def test_url_for_with_scheme(self, app, req_ctx):779-780- @app.route('/')833+ @app.route("/")834 def index():782- return '42'835+ return "42"836 784- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'837+ assert (838+ flask.url_for("index", _external=True, _scheme="https")839+ == "https://localhost/"840+ )841 842 def test_url_for_with_scheme_not_external(self, app, req_ctx):787-788- @app.route('/')843+ @app.route("/")844 def index():790- return '42'845+ return "42"846 792- pytest.raises(ValueError,793- flask.url_for,794- 'index',795- _scheme='https')847+ pytest.raises(ValueError, flask.url_for, "index", _scheme="https")848 849 def test_url_for_with_alternating_schemes(self, app, req_ctx):798-799- @app.route('/')850+ @app.route("/")851 def index():801- return '42'852+ return "42"853 803- assert flask.url_for('index', _external=True) == 'http://localhost/'804- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'805- assert flask.url_for('index', _external=True) == 'http://localhost/'854+ assert flask.url_for("index", _external=True) == "http://localhost/"855+ assert (856+ flask.url_for("index", _external=True, _scheme="https")857+ == "https://localhost/"858+ )859+ assert flask.url_for("index", _external=True) == "http://localhost/"860 861 def test_url_with_method(self, app, req_ctx):862 from flask.views import MethodView863 864 class MyView(MethodView):865 def get(self, id=None):866 if id is None:813- return 'List'814- return 'Get %d' % id867+ return "List"868+ return "Get %d" % id869 870 def post(self):817- return 'Create'871+ return "Create"872 819- myview = MyView.as_view('myview')820- app.add_url_rule('/myview/', methods=['GET'],821- view_func=myview)822- app.add_url_rule('/myview/<int:id>', methods=['GET'],823- view_func=myview)824- app.add_url_rule('/myview/create', methods=['POST'],825- view_func=myview)873+ myview = MyView.as_view("myview")874+ app.add_url_rule("/myview/", methods=["GET"], view_func=myview)875+ app.add_url_rule("/myview/<int:id>", methods=["GET"], view_func=myview)876+ app.add_url_rule("/myview/create", methods=["POST"], view_func=myview)877 827- assert flask.url_for('myview', _method='GET') == '/myview/'828- assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'829- assert flask.url_for('myview', _method='POST') == '/myview/create'878+ assert flask.url_for("myview", _method="GET") == "/myview/"879+ assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"880+ assert flask.url_for("myview", _method="POST") == "/myview/create"881 882 883 class TestNoImports(object):884 """Test Flasks are created without import.6 unmodified lines891 imp modules in the Python standard library.892 """893 894 def test_name_with_import_error(self, modules_tmpdir):844- modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')895+ modules_tmpdir.join("importerror.py").write("raise NotImplementedError()")896 try:846- flask.Flask('importerror')897+ flask.Flask("importerror")898 except NotImplementedError:848- assert False, 'Flask(import_name) is importing import_name.'899+ assert False, "Flask(import_name) is importing import_name."900 901 902 class TestStreaming(object):903 def test_streaming_with_context(self, app, client):853-854- @app.route('/')904+ @app.route("/")905 def index():906 def generate():857- yield 'Hello '858- yield flask.request.args['name']859- yield '!'907+ yield "Hello "908+ yield flask.request.args["name"]909+ yield "!"910 911 return flask.Response(flask.stream_with_context(generate()))912 863- rv = client.get('/?name=World')864- assert rv.data == b'Hello World!'913+ rv = client.get("/?name=World")914+ assert rv.data == b"Hello World!"915 916 def test_streaming_with_context_as_decorator(self, app, client):867-868- @app.route('/')917+ @app.route("/")918 def index():919 @flask.stream_with_context920 def generate(hello):921 yield hello873- yield flask.request.args['name']874- yield '!'922+ yield flask.request.args["name"]923+ yield "!"924 876- return flask.Response(generate('Hello '))925+ return flask.Response(generate("Hello "))926 878- rv = client.get('/?name=World')879- assert rv.data == b'Hello World!'927+ rv = client.get("/?name=World")928+ assert rv.data == b"Hello World!"929 930 def test_streaming_with_context_and_custom_close(self, app, client):931 called = []932 11 unmodified lines944 return next(self._gen)945 946 next = __next__947 899- @app.route('/')948+ @app.route("/")949 def index():950 def generate():902- yield 'Hello '903- yield flask.request.args['name']904- yield '!'951+ yield "Hello "952+ yield flask.request.args["name"]953+ yield "!"954 906- return flask.Response(flask.stream_with_context(907- Wrapper(generate())))955+ return flask.Response(flask.stream_with_context(Wrapper(generate())))956 909- rv = client.get('/?name=World')910- assert rv.data == b'Hello World!'957+ rv = client.get("/?name=World")958+ assert rv.data == b"Hello World!"959 assert called == [42]960 961 def test_stream_keeps_session(self, app, client):914- @app.route('/')962+ @app.route("/")963 def index():916- flask.session['test'] = 'flask'964+ flask.session["test"] = "flask"965 966 @flask.stream_with_context967 def gen():920- yield flask.session['test']968+ yield flask.session["test"]969 970 return flask.Response(gen())971 924- rv = client.get('/')925- assert rv.data == b'flask'972+ rv = client.get("/")973+ assert rv.data == b"flask"974 975 976 class TestSafeJoin(object):977 def test_safe_join(self):978 # Valid combinations of *args and expected joined paths.979 passing = (932- (('a/b/c',), 'a/b/c'),933- (('/', 'a/', 'b/', 'c/'), '/a/b/c'),934- (('a', 'b', 'c'), 'a/b/c'),935- (('/a', 'b/c'), '/a/b/c'),936- (('a/b', 'X/../c'), 'a/b/c'),937- (('/a/b', 'c/X/..'), '/a/b/c'),980+ (("a/b/c",), "a/b/c"),981+ (("/", "a/", "b/", "c/"), "/a/b/c"),982+ (("a", "b", "c"), "a/b/c"),983+ (("/a", "b/c"), "/a/b/c"),984+ (("a/b", "X/../c"), "a/b/c"),985+ (("/a/b", "c/X/.."), "/a/b/c"),986 # If last path is '' add a slash939- (('/a/b/c', ''), '/a/b/c/'),987+ (("/a/b/c", ""), "/a/b/c/"),988 # Preserve dot slash941- (('/a/b/c', './'), '/a/b/c/.'),942- (('a/b/c', 'X/..'), 'a/b/c/.'),989+ (("/a/b/c", "./"), "/a/b/c/."),990+ (("a/b/c", "X/.."), "a/b/c/."),991 # Base directory is always considered safe944- (('../', 'a/b/c'), '../a/b/c'),945- (('/..',), '/..'),992+ (("../", "a/b/c"), "../a/b/c"),993+ (("/..",), "/.."),994 )995 996 for args, expected in passing:997 assert flask.safe_join(*args) == expected1 unmodified line999 def test_safe_join_exceptions(self):1000 # Should raise werkzeug.exceptions.NotFound on unsafe joins.1001 failing = (1002 # path.isabs and ``..'' checks955- ('/a', 'b', '/c'),956- ('/a', '../b/c'),957- ('/a', '..', 'b/c'),1003+ ("/a", "b", "/c"),1004+ ("/a", "../b/c"),1005+ ("/a", "..", "b/c"),1006 # Boundaries violations after path normalization959- ('/a', 'b/../b/../../c'),960- ('/a', 'b', 'c/../..'),961- ('/a', 'b/../../c'),1007+ ("/a", "b/../b/../../c"),1008+ ("/a", "b", "c/../.."),1009+ ("/a", "b/../../c"),1010 )1011 1012 for args in failing:1013 with pytest.raises(NotFound):1014 print(flask.safe_join(*args))1015 968-class TestHelpers(object):1016 970- @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [971- ('', False, False),972- ('0', False, False),973- ('False', False, False),974- ('No', False, False),975- ('True', True, True)976- ])977- def test_get_debug_flag(self, monkeypatch, debug, expected_flag, expected_default_flag):978- monkeypatch.setenv('FLASK_DEBUG', debug)1017+class TestHelpers(object):1018+ @pytest.mark.parametrize(1019+ "debug, expected_flag, expected_default_flag",1020+ [1021+ ("", False, False),1022+ ("0", False, False),1023+ ("False", False, False),1024+ ("No", False, False),1025+ ("True", True, True),1026+ ],1027+ )1028+ def test_get_debug_flag(1029+ self, monkeypatch, debug, expected_flag, expected_default_flag1030+ ):1031+ monkeypatch.setenv("FLASK_DEBUG", debug)1032 if expected_flag is None:1033 assert get_debug_flag() is None1034 else:1035 assert get_debug_flag() == expected_flag1036 assert get_debug_flag() == expected_default_flag1037 985- @pytest.mark.parametrize('env, ref_env, debug', [986- ('', 'production', False),987- ('production', 'production', False),988- ('development', 'development', True),989- ('other', 'other', False),990- ])1038+ @pytest.mark.parametrize(1039+ "env, ref_env, debug",1040+ [1041+ ("", "production", False),1042+ ("production", "production", False),1043+ ("development", "development", True),1044+ ("other", "other", False),1045+ ],1046+ )1047 def test_get_env(self, monkeypatch, env, ref_env, debug):992- monkeypatch.setenv('FLASK_ENV', env)1048+ monkeypatch.setenv("FLASK_ENV", env)1049 assert get_debug_flag() == debug1050 assert get_env() == ref_env1051 1052 def test_make_response(self):1053 app = flask.Flask(__name__)1054 with app.test_request_context():1055 rv = flask.helpers.make_response()1056 assert rv.status_code == 2001001- assert rv.mimetype == 'text/html'1057+ assert rv.mimetype == "text/html"1058 1003- rv = flask.helpers.make_response('Hello')1059+ rv = flask.helpers.make_response("Hello")1060 assert rv.status_code == 2001005- assert rv.data == b'Hello'1006- assert rv.mimetype == 'text/html'1061+ assert rv.data == b"Hello"1062+ assert rv.mimetype == "text/html"modified:tests/test_instance_config.py+67 added-59 removed
15 unmodified lines16 17 18 def test_explicit_instance_paths(modules_tmpdir):19 with pytest.raises(ValueError) as excinfo:20- flask.Flask(__name__, instance_path='instance')21- assert 'must be absolute' in str(excinfo.value)20+ flask.Flask(__name__, instance_path="instance")21+ assert "must be absolute" in str(excinfo.value)22 23 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))24 assert app.instance_path == str(modules_tmpdir)25 26 27 def test_main_module_paths(modules_tmpdir, purge_module):28- app = modules_tmpdir.join('main_app.py')28+ app = modules_tmpdir.join("main_app.py")29 app.write('import flask\n\napp = flask.Flask("__main__")')30- purge_module('main_app')30+ purge_module("main_app")31 32 from main_app import app33+34 here = os.path.abspath(os.getcwd())34- assert app.instance_path == os.path.join(here, 'instance')35+ assert app.instance_path == os.path.join(here, "instance")36 37 38 def test_uninstalled_module_paths(modules_tmpdir, purge_module):38- app = modules_tmpdir.join('config_module_app.py').write(39- 'import os\n'40- 'import flask\n'41- 'here = os.path.abspath(os.path.dirname(__file__))\n'42- 'app = flask.Flask(__name__)\n'39+ app = modules_tmpdir.join("config_module_app.py").write(40+ "import os\n"41+ "import flask\n"42+ "here = os.path.abspath(os.path.dirname(__file__))\n"43+ "app = flask.Flask(__name__)\n"44 )44- purge_module('config_module_app')45+ purge_module("config_module_app")46 47 from config_module_app import app47- assert app.instance_path == str(modules_tmpdir.join('instance'))48 49+ assert app.instance_path == str(modules_tmpdir.join("instance"))50 51+52 def test_uninstalled_package_paths(modules_tmpdir, purge_module):51- app = modules_tmpdir.mkdir('config_package_app')52- init = app.join('__init__.py')53+ app = modules_tmpdir.mkdir("config_package_app")54+ init = app.join("__init__.py")55 init.write(54- 'import os\n'55- 'import flask\n'56- 'here = os.path.abspath(os.path.dirname(__file__))\n'57- 'app = flask.Flask(__name__)\n'56+ "import os\n"57+ "import flask\n"58+ "here = os.path.abspath(os.path.dirname(__file__))\n"59+ "app = flask.Flask(__name__)\n"60 )59- purge_module('config_package_app')61+ purge_module("config_package_app")62 63 from config_package_app import app62- assert app.instance_path == str(modules_tmpdir.join('instance'))64 65+ assert app.instance_path == str(modules_tmpdir.join("instance"))66 65-def test_installed_module_paths(modules_tmpdir, modules_tmpdir_prefix,66- purge_module, site_packages, limit_loader):67- site_packages.join('site_app.py').write(68- 'import flask\n'69- 'app = flask.Flask(__name__)\n'67+68+def test_installed_module_paths(69+ modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader70+):71+ site_packages.join("site_app.py").write(72+ "import flask\n" "app = flask.Flask(__name__)\n"73 )71- purge_module('site_app')74+ purge_module("site_app")75 76 from site_app import app74- assert app.instance_path == \75- modules_tmpdir.join('var').join('site_app-instance')77 78+ assert app.instance_path == modules_tmpdir.join("var").join("site_app-instance")79 78-def test_installed_package_paths(limit_loader, modules_tmpdir,79- modules_tmpdir_prefix, purge_module,80- monkeypatch):81- installed_path = modules_tmpdir.mkdir('path')80+81+def test_installed_package_paths(82+ limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, monkeypatch83+):84+ installed_path = modules_tmpdir.mkdir("path")85 monkeypatch.syspath_prepend(installed_path)86 84- app = installed_path.mkdir('installed_package')85- init = app.join('__init__.py')86- init.write('import flask\napp = flask.Flask(__name__)')87- purge_module('installed_package')87+ app = installed_path.mkdir("installed_package")88+ init = app.join("__init__.py")89+ init.write("import flask\napp = flask.Flask(__name__)")90+ purge_module("installed_package")91 92 from installed_package import app90- assert app.instance_path == \91- modules_tmpdir.join('var').join('installed_package-instance')93 94+ assert app.instance_path == modules_tmpdir.join("var").join(95+ "installed_package-instance"96+ )97 94-def test_prefix_package_paths(limit_loader, modules_tmpdir,95- modules_tmpdir_prefix, purge_module,96- site_packages):97- app = site_packages.mkdir('site_package')98- init = app.join('__init__.py')99- init.write('import flask\napp = flask.Flask(__name__)')100- purge_module('site_package')98 99+def test_prefix_package_paths(100+ limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages101+):102+ app = site_packages.mkdir("site_package")103+ init = app.join("__init__.py")104+ init.write("import flask\napp = flask.Flask(__name__)")105+ purge_module("site_package")106+107 import site_package103- assert site_package.app.instance_path == \104- modules_tmpdir.join('var').join('site_package-instance')108 109+ assert site_package.app.instance_path == modules_tmpdir.join("var").join(110+ "site_package-instance"111+ )112 107-def test_egg_installed_paths(install_egg, modules_tmpdir,108- modules_tmpdir_prefix):109- modules_tmpdir.mkdir('site_egg').join('__init__.py').write(110- 'import flask\n\napp = flask.Flask(__name__)'113+114+def test_egg_installed_paths(install_egg, modules_tmpdir, modules_tmpdir_prefix):115+ modules_tmpdir.mkdir("site_egg").join("__init__.py").write(116+ "import flask\n\napp = flask.Flask(__name__)"117 )112- install_egg('site_egg')118+ install_egg("site_egg")119 try:120 import site_egg115- assert site_egg.app.instance_path == \116- str(modules_tmpdir.join('var/').join('site_egg-instance'))121+122+ assert site_egg.app.instance_path == str(123+ modules_tmpdir.join("var/").join("site_egg-instance")124+ )125 finally:118- if 'site_egg' in sys.modules:119- del sys.modules['site_egg']126+ if "site_egg" in sys.modules:127+ del sys.modules["site_egg"]128 129 122-@pytest.mark.skipif(not PY2, reason='This only works under Python 2.')130+@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")131 def test_meta_path_loader_without_is_package(request, modules_tmpdir):124- app = modules_tmpdir.join('unimportable.py')125- app.write('import flask\napp = flask.Flask(__name__)')132+ app = modules_tmpdir.join("unimportable.py")133+ app.write("import flask\napp = flask.Flask(__name__)")134 135 class Loader(object):136 def find_module(self, name, path=None):137 return self6 unmodified linesmodified:tests/test_json_tag.py+21 added-18 removed
14 unmodified lines15 from flask import Markup16 from flask.json.tag import TaggedJSONSerializer, JSONTag17 18 19-@pytest.mark.parametrize("data", (20- {' t': (1, 2, 3)},21- {' t__': b'a'},22- {' di': ' di'},23- {'x': (1, 2, 3), 'y': 4},24- (1, 2, 3),25- [(1, 2, 3)],26- b'\xff',27- Markup('<html>'),28- uuid4(),29- datetime.utcnow().replace(microsecond=0),30-))19+@pytest.mark.parametrize(20+ "data",21+ (22+ {" t": (1, 2, 3)},23+ {" t__": b"a"},24+ {" di": " di"},25+ {"x": (1, 2, 3), "y": 4},26+ (1, 2, 3),27+ [(1, 2, 3)],28+ b"\xff",29+ Markup("<html>"),30+ uuid4(),31+ datetime.utcnow().replace(microsecond=0),32+ ),33+)34 def test_dump_load_unchanged(data):35 s = TaggedJSONSerializer()36 assert s.loads(s.dumps(data)) == data37 38 39 def test_duplicate_tag():40 class TagDict(JSONTag):38- key = ' d'41+ key = " d"42 43 s = TaggedJSONSerializer()44 pytest.raises(KeyError, s.register, TagDict)45 s.register(TagDict, force=True, index=0)43- assert isinstance(s.tags[' d'], TagDict)46+ assert isinstance(s.tags[" d"], TagDict)47 assert isinstance(s.order[0], TagDict)48 49 50 def test_custom_tag():2 unmodified lines53 self.data = data54 55 class TagFoo(JSONTag):56 __slots__ = ()54- key = ' f'57+ key = " f"58 59 def check(self, value):60 return isinstance(value, Foo)61 4 unmodified lines66 return Foo(value)67 68 s = TaggedJSONSerializer()69 s.register(TagFoo)67- assert s.loads(s.dumps(Foo('bar'))).data == 'bar'70+ assert s.loads(s.dumps(Foo("bar"))).data == "bar"71 72 73 def test_tag_interface():74 t = JSONTag(None)3 unmodified lines78 79 80 def test_tag_order():81 class Tag1(JSONTag):79- key = ' 1'82+ key = " 1"83 84 class Tag2(JSONTag):82- key = ' 2'85+ key = " 2"86 87 s = TaggedJSONSerializer()88 89 s.register(Tag1, index=-1)4 unmodified linesmodified:tests/test_logging.py+16 added-18 removed
11 unmodified lines12 13 import pytest14 15 from flask._compat import StringIO16-from flask.logging import default_handler, has_level_handler, \17- wsgi_errors_stream16+from flask.logging import default_handler, has_level_handler, wsgi_errors_stream17 18 19 @pytest.fixture(autouse=True)20 def reset_logging(pytestconfig):21 root_handlers = logging.root.handlers[:]22 logging.root.handlers = []23 root_level = logging.root.level24 26- logger = logging.getLogger('flask.app')25+ logger = logging.getLogger("flask.app")26 logger.handlers = []27 logger.setLevel(logging.NOTSET)28 30- logging_plugin = pytestconfig.pluginmanager.unregister(31- name='logging-plugin')29+ logging_plugin = pytestconfig.pluginmanager.unregister(name="logging-plugin")30 31 yield32 33 logging.root.handlers[:] = root_handlers2 unmodified lines36 logger.handlers = []37 logger.setLevel(logging.NOTSET)38 39 if logging_plugin:42- pytestconfig.pluginmanager.register(logging_plugin, 'logging-plugin')40+ pytestconfig.pluginmanager.register(logging_plugin, "logging-plugin")41 42 43 def test_logger(app):46- assert app.logger.name == 'flask.app'44+ assert app.logger.name == "flask.app"45 assert app.logger.level == logging.NOTSET46 assert app.logger.handlers == [default_handler]47 48 9 unmodified lines58 assert not app.logger.handlers59 60 61 def test_wsgi_errors_stream(app, client):64- @app.route('/')62+ @app.route("/")63 def index():66- app.logger.error('test')67- return ''64+ app.logger.error("test")65+ return ""66 67 stream = StringIO()70- client.get('/', errors_stream=stream)71- assert 'ERROR in test_logging: test' in stream.getvalue()68+ client.get("/", errors_stream=stream)69+ assert "ERROR in test_logging: test" in stream.getvalue()70 71 assert wsgi_errors_stream._get_current_object() is sys.stderr72 73 with app.test_request_context(errors_stream=stream):74 assert wsgi_errors_stream._get_current_object() is stream75 76 77 def test_has_level_handler():80- logger = logging.getLogger('flask.app')78+ logger = logging.getLogger("flask.app")79 assert not has_level_handler(logger)80 81 handler = logging.StreamHandler()82 logging.root.addHandler(handler)7 unmodified lines90 assert not has_level_handler(logger)91 92 93 def test_log_view_exception(app, client):96- @app.route('/')94+ @app.route("/")95 def index():98- raise Exception('test')96+ raise Exception("test")97 98 app.testing = False99 stream = StringIO()102- rv = client.get('/', errors_stream=stream)100+ rv = client.get("/", errors_stream=stream)101 assert rv.status_code == 500102 assert rv.data103 err = stream.getvalue()106- assert 'Exception on / [GET]' in err107- assert 'Exception: test' in err104+ assert "Exception on / [GET]" in err105+ assert "Exception: test" in errmodified:tests/test_regression.py+16 added-17 removed
20 unmodified lines21 _gc_lock = threading.Lock()22 23 24 class assert_no_leak(object):25-25 def __enter__(self):26 gc.disable()27 _gc_lock.acquire()28 loc = flask._request_ctx_stack._local1 unmodified line30 # Force Python to track this dictionary at all times.31 # This is necessary since Python only starts tracking32 # dicts if they contain mutable objects. It's a horrible,33 # horrible hack but makes this kinda testable.35- loc.__storage__['FOOO'] = [1, 2, 3]34+ loc.__storage__["FOOO"] = [1, 2, 3]35 36 gc.collect()37 self.old_objects = len(gc.get_objects())38 39 def __exit__(self, exc_type, exc_value, tb):40 gc.collect()41 new_objects = len(gc.get_objects())42 if new_objects > self.old_objects:44- pytest.fail('Example code leaked')43+ pytest.fail("Example code leaked")44 _gc_lock.release()45 gc.enable()46 47 48 def test_memory_consumption():49 app = flask.Flask(__name__)50 52- @app.route('/')51+ @app.route("/")52 def index():54- return flask.render_template('simple_template.html', whiskey=42)53+ return flask.render_template("simple_template.html", whiskey=42)54 55 def fire():56 with app.test_client() as c:58- rv = c.get('/')57+ rv = c.get("/")58 assert rv.status_code == 20060- assert rv.data == b'<h1>42</h1>'59+ assert rv.data == b"<h1>42</h1>"60 61 # Trigger caches62 fire()63 64 # This test only works on CPython 2.7.66- if sys.version_info >= (2, 7) and \67- not hasattr(sys, 'pypy_translation_info'):65+ if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"):66 with assert_no_leak():67 for x in range(10):68 fire()69 70 71 def test_safe_join_toplevel_pardir():72 from flask.helpers import safe_join73+74 with pytest.raises(NotFound):76- safe_join('/foo', '..')75+ safe_join("/foo", "..")76 77 78 def test_aborting(app):79 class Foo(Exception):2 unmodified lines82 @app.errorhandler(Foo)83 def handle_foo(e):84 return str(e.whatever)85 87- @app.route('/')86+ @app.route("/")87 def index():89- raise flask.abort(flask.redirect(flask.url_for('test')))88+ raise flask.abort(flask.redirect(flask.url_for("test")))89 91- @app.route('/test')90+ @app.route("/test")91 def test():92 raise Foo()93 94 with app.test_client() as c:96- rv = c.get('/')97- assert rv.headers['Location'] == 'http://localhost/test'98- rv = c.get('/test')99- assert rv.data == b'42'95+ rv = c.get("/")96+ assert rv.headers["Location"] == "http://localhost/test"97+ rv = c.get("/test")98+ assert rv.data == b"42"modified:tests/test_reqctx.py+63 added-56 removed
40 unmodified lines41 def end_of_request(exception):42 buffer.append(exception)43 44 try:45- raise Exception('dummy')45+ raise Exception("dummy")46 except Exception:47 pass48 49 with app.test_request_context():10 unmodified lines60 61 with app.test_request_context():62 assert buffer == []63 try:64- raise Exception('dummy')64+ raise Exception("dummy")65 except Exception:66 pass67 assert buffer == [None]68 69 70 def test_proper_test_request_context(app):71- app.config.update(72- SERVER_NAME='localhost.localdomain:5000'73- )71+ app.config.update(SERVER_NAME="localhost.localdomain:5000")72 75- @app.route('/')73+ @app.route("/")74 def index():75 return None76 79- @app.route('/', subdomain='foo')77+ @app.route("/", subdomain="foo")78 def sub():79 return None80 83- with app.test_request_context('/'):84- assert flask.url_for('index', _external=True) == \85- 'http://localhost.localdomain:5000/'81+ with app.test_request_context("/"):82+ assert (83+ flask.url_for("index", _external=True)84+ == "http://localhost.localdomain:5000/"85+ )86 87- with app.test_request_context('/'):88- assert flask.url_for('sub', _external=True) == \89- 'http://foo.localhost.localdomain:5000/'87+ with app.test_request_context("/"):88+ assert (89+ flask.url_for("sub", _external=True)90+ == "http://foo.localhost.localdomain:5000/"91+ )92 93 try:92- with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):94+ with app.test_request_context(95+ "/", environ_overrides={"HTTP_HOST": "localhost"}96+ ):97 pass98 except ValueError as e:99 assert str(e) == (100 "the server name provided "101 "('localhost.localdomain:5000') does not match the "102 "server name from the WSGI environment ('localhost')"103 )104 101- app.config.update(SERVER_NAME='localhost')102- with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):105+ app.config.update(SERVER_NAME="localhost")106+ with app.test_request_context("/", environ_overrides={"SERVER_NAME": "localhost"}):107 pass108 105- app.config.update(SERVER_NAME='localhost:80')106- with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):109+ app.config.update(SERVER_NAME="localhost:80")110+ with app.test_request_context(111+ "/", environ_overrides={"SERVER_NAME": "localhost:80"}112+ ):113 pass114 115 116 def test_context_binding(app):111- @app.route('/')117+ @app.route("/")118 def index():113- return 'Hello %s!' % flask.request.args['name']119+ return "Hello %s!" % flask.request.args["name"]120 115- @app.route('/meh')121+ @app.route("/meh")122 def meh():123 return flask.request.url124 119- with app.test_request_context('/?name=World'):120- assert index() == 'Hello World!'121- with app.test_request_context('/meh'):122- assert meh() == 'http://localhost/meh'125+ with app.test_request_context("/?name=World"):126+ assert index() == "Hello World!"127+ with app.test_request_context("/meh"):128+ assert meh() == "http://localhost/meh"129 assert flask._request_ctx_stack.top is None130 131 132 def test_context_test(app):8 unmodified lines141 ctx.pop()142 143 144 def test_manual_context_binding(app):139- @app.route('/')145+ @app.route("/")146 def index():141- return 'Hello %s!' % flask.request.args['name']147+ return "Hello %s!" % flask.request.args["name"]148 143- ctx = app.test_request_context('/?name=World')149+ ctx = app.test_request_context("/?name=World")150 ctx.push()145- assert index() == 'Hello World!'151+ assert index() == "Hello World!"152 ctx.pop()153 with pytest.raises(RuntimeError):154 index()155 156 151-@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')157+@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")158 class TestGreenletContextCopying(object):153-159 def test_greenlet_context_copying(self, app, client):160 greenlets = []161 157- @app.route('/')162+ @app.route("/")163 def index():159- flask.session['fizz'] = 'buzz'164+ flask.session["fizz"] = "buzz"165 reqctx = flask._request_ctx_stack.top.copy()166 167 def g():168 assert not flask.request169 assert not flask.current_app170 with reqctx:171 assert flask.request172 assert flask.current_app == app168- assert flask.request.path == '/'169- assert flask.request.args['foo'] == 'bar'170- assert flask.session.get('fizz') == 'buzz'173+ assert flask.request.path == "/"174+ assert flask.request.args["foo"] == "bar"175+ assert flask.session.get("fizz") == "buzz"176 assert not flask.request177 return 42178 179 greenlets.append(greenlet(g))175- return 'Hello World!'180+ return "Hello World!"181 177- rv = client.get('/?foo=bar')178- assert rv.data == b'Hello World!'182+ rv = client.get("/?foo=bar")183+ assert rv.data == b"Hello World!"184 185 result = greenlets[0].run()186 assert result == 42187 188 def test_greenlet_context_copying_api(self, app, client):189 greenlets = []190 186- @app.route('/')191+ @app.route("/")192 def index():188- flask.session['fizz'] = 'buzz'193+ flask.session["fizz"] = "buzz"194 reqctx = flask._request_ctx_stack.top.copy()195 196 @flask.copy_current_request_context197 def g():198 assert flask.request199 assert flask.current_app == app195- assert flask.request.path == '/'196- assert flask.request.args['foo'] == 'bar'197- assert flask.session.get('fizz') == 'buzz'200+ assert flask.request.path == "/"201+ assert flask.request.args["foo"] == "bar"202+ assert flask.session.get("fizz") == "buzz"203 return 42204 205 greenlets.append(greenlet(g))201- return 'Hello World!'206+ return "Hello World!"207 203- rv = client.get('/?foo=bar')204- assert rv.data == b'Hello World!'208+ rv = client.get("/?foo=bar")209+ assert rv.data == b"Hello World!"210 211 result = greenlets[0].run()212 assert result == 42213 10 unmodified lines224 session_interface = FailingSessionInterface()225 226 app = CustomFlask(__name__)227 223- @app.route('/')228+ @app.route("/")229 def index():230 # shouldn't get here231 assert False232 228- response = app.test_client().get('/')233+ response = app.test_client().get("/")234 assert response.status_code == 500235 assert not flask.request236 assert not flask.current_app237 5 unmodified lines243 # because werkzeug enforces latin1 on Python 2.244 # However it works when actually passed to the server.245 246 from flask.testing import make_test_environ_builder247+248 builder = make_test_environ_builder(app)249 environ = builder.get_environ()250 251 # use a non-printable character in the Host - this is key to this test246- environ['HTTP_HOST'] = u'\x8a'252+ environ["HTTP_HOST"] = u"\x8a"253 254 with app.request_context(environ):255 response = app.full_dispatch_request()256 assert response.status_code == 4001 unmodified line258 259 def test_environ_for_valid_idna_completes():260 app = flask.Flask(__name__)261 256- @app.route('/')262+ @app.route("/")263 def index():258- return 'Hello World!'264+ return "Hello World!"265 266 # We cannot use app.test_client() for the Unicode-rich Host header,267 # because werkzeug enforces latin1 on Python 2.268 # However it works when actually passed to the server.269 270 from flask.testing import make_test_environ_builder271+272 builder = make_test_environ_builder(app)273 environ = builder.get_environ()274 275 # these characters are all IDNA-compatible269- environ['HTTP_HOST'] = u'ąśźäüжŠßя.com'276+ environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"277 278 with app.request_context(environ):279 response = app.full_dispatch_request()280 2 unmodified lines283 284 def test_normal_environ_completes():285 app = flask.Flask(__name__)286 280- @app.route('/')287+ @app.route("/")288 def index():282- return 'Hello World!'289+ return "Hello World!"290 284- response = app.test_client().get('/', headers={'host': 'xn--on-0ia.com'})291+ response = app.test_client().get("/", headers={"host": "xn--on-0ia.com"})292 assert response.status_code == 200modified:tests/test_signals.py+51 added-47 removed
17 unmodified lines18 19 import flask20 21 pytestmark = pytest.mark.skipif(22- blinker is None,23- reason='Signals require the blinker library.'22+ blinker is None, reason="Signals require the blinker library."23 )24 25 26 def test_template_rendered(app, client):28- @app.route('/')27+ @app.route("/")28 def index():30- return flask.render_template('simple_template.html', whiskey=42)29+ return flask.render_template("simple_template.html", whiskey=42)30 31 recorded = []32 33 def record(sender, template, context):34 recorded.append((template, context))35 36 flask.template_rendered.connect(record, app)37 try:39- client.get('/')38+ client.get("/")39 assert len(recorded) == 140 template, context = recorded[0]42- assert template.name == 'simple_template.html'43- assert context['whiskey'] == 4241+ assert template.name == "simple_template.html"42+ assert context["whiskey"] == 4243 finally:44 flask.template_rendered.disconnect(record, app)45 46 47 def test_before_render_template():48 app = flask.Flask(__name__)49 51- @app.route('/')50+ @app.route("/")51 def index():53- return flask.render_template('simple_template.html', whiskey=42)52+ return flask.render_template("simple_template.html", whiskey=42)53 54 recorded = []55 56 def record(sender, template, context):58- context['whiskey'] = 4357+ context["whiskey"] = 4358 recorded.append((template, context))59 60 flask.before_render_template.connect(record, app)61 try:63- rv = app.test_client().get('/')62+ rv = app.test_client().get("/")63 assert len(recorded) == 164 template, context = recorded[0]66- assert template.name == 'simple_template.html'67- assert context['whiskey'] == 4368- assert rv.data == b'<h1>43</h1>'65+ assert template.name == "simple_template.html"66+ assert context["whiskey"] == 4367+ assert rv.data == b"<h1>43</h1>"68 finally:69 flask.before_render_template.disconnect(record, app)70 71 1 unmodified line73 app = flask.Flask(__name__)74 calls = []75 76 def before_request_signal(sender):78- calls.append('before-signal')77+ calls.append("before-signal")78 79 def after_request_signal(sender, response):81- assert response.data == b'stuff'82- calls.append('after-signal')80+ assert response.data == b"stuff"81+ calls.append("after-signal")82 83 @app.before_request84 def before_request_handler():86- calls.append('before-handler')85+ calls.append("before-handler")86 87 @app.after_request88 def after_request_handler(response):90- calls.append('after-handler')91- response.data = 'stuff'89+ calls.append("after-handler")90+ response.data = "stuff"91 return response92 94- @app.route('/')93+ @app.route("/")94 def index():96- calls.append('handler')97- return 'ignored anyway'95+ calls.append("handler")96+ return "ignored anyway"97 98 flask.request_started.connect(before_request_signal, app)99 flask.request_finished.connect(after_request_signal, app)100 101 try:103- rv = app.test_client().get('/')104- assert rv.data == b'stuff'102+ rv = app.test_client().get("/")103+ assert rv.data == b"stuff"104 106- assert calls == ['before-signal', 'before-handler', 'handler',107- 'after-handler', 'after-signal']105+ assert calls == [106+ "before-signal",107+ "before-handler",108+ "handler",109+ "after-handler",110+ "after-signal",111+ ]112 finally:113 flask.request_started.disconnect(before_request_signal, app)114 flask.request_finished.disconnect(after_request_signal, app)115 1 unmodified line117 def test_request_exception_signal():118 app = flask.Flask(__name__)119 recorded = []120 117- @app.route('/')121+ @app.route("/")122 def index():123 1 // 0124 125 def record(sender, exception):126 recorded.append(exception)127 128 flask.got_request_exception.connect(record, app)129 try:126- assert app.test_client().get('/').status_code == 500130+ assert app.test_client().get("/").status_code == 500131 assert len(recorded) == 1132 assert isinstance(recorded[0], ZeroDivisionError)133 finally:134 flask.got_request_exception.disconnect(record, app)3 unmodified lines138 app = flask.Flask(__name__)139 recorded = []140 141 def record_push(sender, **kwargs):138- recorded.append('push')142+ recorded.append("push")143 144 def record_pop(sender, **kwargs):141- recorded.append('pop')145+ recorded.append("pop")146 143- @app.route('/')147+ @app.route("/")148 def index():145- return 'Hello'149+ return "Hello"150 151 flask.appcontext_pushed.connect(record_push, app)152 flask.appcontext_popped.connect(record_pop, app)153 try:154 with app.test_client() as c:151- rv = c.get('/')152- assert rv.data == b'Hello'153- assert recorded == ['push']154- assert recorded == ['push', 'pop']155+ rv = c.get("/")156+ assert rv.data == b"Hello"157+ assert recorded == ["push"]158+ assert recorded == ["push", "pop"]159 finally:160 flask.appcontext_pushed.disconnect(record_push, app)161 flask.appcontext_popped.disconnect(record_pop, app)162 163 164 def test_flash_signal(app):161- @app.route('/')165+ @app.route("/")166 def index():163- flask.flash('This is a flash message', category='notice')164- return flask.redirect('/other')167+ flask.flash("This is a flash message", category="notice")168+ return flask.redirect("/other")169 170 recorded = []171 172 def record(sender, message, category):2 unmodified lines175 flask.message_flashed.connect(record, app)176 try:177 client = app.test_client()178 with client.session_transaction():175- client.get('/')179+ client.get("/")180 assert len(recorded) == 1181 message, category = recorded[0]178- assert message == 'This is a flash message'179- assert category == 'notice'182+ assert message == "This is a flash message"183+ assert category == "notice"184 finally:185 flask.message_flashed.disconnect(record, app)186 187 1 unmodified line189 app = flask.Flask(__name__)190 recorded = []191 192 def record_teardown(sender, **kwargs):189- recorded.append(('tear_down', kwargs))193+ recorded.append(("tear_down", kwargs))194 191- @app.route('/')195+ @app.route("/")196 def index():197 1 // 0198 199 flask.appcontext_tearing_down.connect(record_teardown, app)200 try:201 with app.test_client() as c:198- rv = c.get('/')202+ rv = c.get("/")203 assert rv.status_code == 500204 assert recorded == []201- assert recorded == [('tear_down', {'exc': None})]205+ assert recorded == [("tear_down", {"exc": None})]206 finally:207 flask.appcontext_tearing_down.disconnect(record_teardown, app)modified:tests/test_subclassing.py+4 added-4 removed
21 unmodified lines22 23 out = StringIO()24 app = SuppressedFlask(__name__)25 26- @app.route('/')26+ @app.route("/")27 def index():28- raise Exception('test')28+ raise Exception("test")29 30- rv = app.test_client().get('/', errors_stream=out)30+ rv = app.test_client().get("/", errors_stream=out)31 assert rv.status_code == 50032- assert b'Internal Server Error' in rv.data32+ assert b"Internal Server Error" in rv.data33 assert not out.getvalue()modified:tests/test_templating.py+162 added-154 removed
18 unmodified lines19 20 def test_context_processing(app, client):21 @app.context_processor22 def context_processor():23- return {'injected_value': 42}23+ return {"injected_value": 42}24 25- @app.route('/')25+ @app.route("/")26 def index():27- return flask.render_template('context_template.html', value=23)27+ return flask.render_template("context_template.html", value=23)28 29- rv = client.get('/')30- assert rv.data == b'<p>23|42'29+ rv = client.get("/")30+ assert rv.data == b"<p>23|42"31 32 33 def test_original_win(app, client):34- @app.route('/')34+ @app.route("/")35 def index():36- return flask.render_template_string('{{ config }}', config=42)36+ return flask.render_template_string("{{ config }}", config=42)37 38- rv = client.get('/')39- assert rv.data == b'42'38+ rv = client.get("/")39+ assert rv.data == b"42"40 41 42 def test_request_less_rendering(app, app_ctx):43- app.config['WORLD_NAME'] = 'Special World'43+ app.config["WORLD_NAME"] = "Special World"44 45 @app.context_processor46 def context_processor():47 return dict(foo=42)48 49- rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '50- '{{ foo }}')51- assert rv == 'Hello Special World 42'49+ rv = flask.render_template_string("Hello {{ config.WORLD_NAME }} " "{{ foo }}")50+ assert rv == "Hello Special World 42"51 52 53 def test_standard_context(app, client):55- @app.route('/')54+ @app.route("/")55 def index():56 flask.g.foo = 2358- flask.session['test'] = 'aha'59- return flask.render_template_string('''57+ flask.session["test"] = "aha"58+ return flask.render_template_string(59+ """60 {{ request.args.foo }}61 {{ g.foo }}62 {{ config.DEBUG }}63 {{ session.test }}64- ''')64+ """65+ )66 66- rv = client.get('/?foo=42')67- assert rv.data.split() == [b'42', b'23', b'False', b'aha']67+ rv = client.get("/?foo=42")68+ assert rv.data.split() == [b"42", b"23", b"False", b"aha"]69 70 71 def test_escaping(app, client):71- text = '<p>Hello World!'72+ text = "<p>Hello World!"73 73- @app.route('/')74+ @app.route("/")75 def index():75- return flask.render_template('escaping_template.html', text=text,76- html=flask.Markup(text))76+ return flask.render_template(77+ "escaping_template.html", text=text, html=flask.Markup(text)78+ )79 78- lines = client.get('/').data.splitlines()80+ lines = client.get("/").data.splitlines()81 assert lines == [80- b'<p>Hello World!',81- b'<p>Hello World!',82- b'<p>Hello World!',83- b'<p>Hello World!',84- b'<p>Hello World!',85- b'<p>Hello World!'82+ b"<p>Hello World!",83+ b"<p>Hello World!",84+ b"<p>Hello World!",85+ b"<p>Hello World!",86+ b"<p>Hello World!",87+ b"<p>Hello World!",88 ]89 90 91 def test_no_escaping(app, client):90- text = '<p>Hello World!'92+ text = "<p>Hello World!"93 92- @app.route('/')94+ @app.route("/")95 def index():94- return flask.render_template('non_escaping_template.txt', text=text,95- html=flask.Markup(text))96+ return flask.render_template(97+ "non_escaping_template.txt", text=text, html=flask.Markup(text)98+ )99 97- lines = client.get('/').data.splitlines()100+ lines = client.get("/").data.splitlines()101 assert lines == [99- b'<p>Hello World!',100- b'<p>Hello World!',101- b'<p>Hello World!',102- b'<p>Hello World!',103- b'<p>Hello World!',104- b'<p>Hello World!',105- b'<p>Hello World!',106- b'<p>Hello World!'102+ b"<p>Hello World!",103+ b"<p>Hello World!",104+ b"<p>Hello World!",105+ b"<p>Hello World!",106+ b"<p>Hello World!",107+ b"<p>Hello World!",108+ b"<p>Hello World!",109+ b"<p>Hello World!",110 ]111 112 113 def test_escaping_without_template_filename(app, client, req_ctx):111- assert flask.render_template_string(112- '{{ foo }}', foo='<test>') == '<test>'113- assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'114+ assert flask.render_template_string("{{ foo }}", foo="<test>") == "<test>"115+ assert flask.render_template("mail.txt", foo="<test>") == "<test> Mail"116 117 118 def test_macros(app, req_ctx):117- macro = flask.get_template_attribute('_macro.html', 'hello')118- assert macro('World') == 'Hello World!'119+ macro = flask.get_template_attribute("_macro.html", "hello")120+ assert macro("World") == "Hello World!"121 122 123 def test_template_filter(app):124 @app.template_filter()125 def my_reverse(s):126 return s[::-1]127 126- assert 'my_reverse' in app.jinja_env.filters.keys()127- assert app.jinja_env.filters['my_reverse'] == my_reverse128- assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'128+ assert "my_reverse" in app.jinja_env.filters.keys()129+ assert app.jinja_env.filters["my_reverse"] == my_reverse130+ assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"131 132 133 def test_add_template_filter(app):134 def my_reverse(s):135 return s[::-1]136 137 app.add_template_filter(my_reverse)136- assert 'my_reverse' in app.jinja_env.filters.keys()137- assert app.jinja_env.filters['my_reverse'] == my_reverse138- assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'138+ assert "my_reverse" in app.jinja_env.filters.keys()139+ assert app.jinja_env.filters["my_reverse"] == my_reverse140+ assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"141 142 143 def test_template_filter_with_name(app):142- @app.template_filter('strrev')144+ @app.template_filter("strrev")145 def my_reverse(s):146 return s[::-1]147 146- assert 'strrev' in app.jinja_env.filters.keys()147- assert app.jinja_env.filters['strrev'] == my_reverse148- assert app.jinja_env.filters['strrev']('abcd') == 'dcba'148+ assert "strrev" in app.jinja_env.filters.keys()149+ assert app.jinja_env.filters["strrev"] == my_reverse150+ assert app.jinja_env.filters["strrev"]("abcd") == "dcba"151 152 153 def test_add_template_filter_with_name(app):154 def my_reverse(s):155 return s[::-1]156 155- app.add_template_filter(my_reverse, 'strrev')156- assert 'strrev' in app.jinja_env.filters.keys()157- assert app.jinja_env.filters['strrev'] == my_reverse158- assert app.jinja_env.filters['strrev']('abcd') == 'dcba'157+ app.add_template_filter(my_reverse, "strrev")158+ assert "strrev" in app.jinja_env.filters.keys()159+ assert app.jinja_env.filters["strrev"] == my_reverse160+ assert app.jinja_env.filters["strrev"]("abcd") == "dcba"161 162 163 def test_template_filter_with_template(app, client):164 @app.template_filter()165 def super_reverse(s):166 return s[::-1]167 166- @app.route('/')168+ @app.route("/")169 def index():168- return flask.render_template('template_filter.html', value='abcd')170+ return flask.render_template("template_filter.html", value="abcd")171 170- rv = client.get('/')171- assert rv.data == b'dcba'172+ rv = client.get("/")173+ assert rv.data == b"dcba"174 175 176 def test_add_template_filter_with_template(app, client):177 def super_reverse(s):178 return s[::-1]179 180 app.add_template_filter(super_reverse)181 180- @app.route('/')182+ @app.route("/")183 def index():182- return flask.render_template('template_filter.html', value='abcd')184+ return flask.render_template("template_filter.html", value="abcd")185 184- rv = client.get('/')185- assert rv.data == b'dcba'186+ rv = client.get("/")187+ assert rv.data == b"dcba"188 189 190 def test_template_filter_with_name_and_template(app, client):189- @app.template_filter('super_reverse')191+ @app.template_filter("super_reverse")192 def my_reverse(s):193 return s[::-1]194 193- @app.route('/')195+ @app.route("/")196 def index():195- return flask.render_template('template_filter.html', value='abcd')197+ return flask.render_template("template_filter.html", value="abcd")198 197- rv = client.get('/')198- assert rv.data == b'dcba'199+ rv = client.get("/")200+ assert rv.data == b"dcba"201 202 203 def test_add_template_filter_with_name_and_template(app, client):204 def my_reverse(s):205 return s[::-1]206 205- app.add_template_filter(my_reverse, 'super_reverse')207+ app.add_template_filter(my_reverse, "super_reverse")208 207- @app.route('/')209+ @app.route("/")210 def index():209- return flask.render_template('template_filter.html', value='abcd')211+ return flask.render_template("template_filter.html", value="abcd")212 211- rv = client.get('/')212- assert rv.data == b'dcba'213+ rv = client.get("/")214+ assert rv.data == b"dcba"215 216 217 def test_template_test(app):218 @app.template_test()219 def boolean(value):220 return isinstance(value, bool)221 220- assert 'boolean' in app.jinja_env.tests.keys()221- assert app.jinja_env.tests['boolean'] == boolean222- assert app.jinja_env.tests['boolean'](False)222+ assert "boolean" in app.jinja_env.tests.keys()223+ assert app.jinja_env.tests["boolean"] == boolean224+ assert app.jinja_env.tests["boolean"](False)225 226 227 def test_add_template_test(app):228 def boolean(value):229 return isinstance(value, bool)230 231 app.add_template_test(boolean)230- assert 'boolean' in app.jinja_env.tests.keys()231- assert app.jinja_env.tests['boolean'] == boolean232- assert app.jinja_env.tests['boolean'](False)232+ assert "boolean" in app.jinja_env.tests.keys()233+ assert app.jinja_env.tests["boolean"] == boolean234+ assert app.jinja_env.tests["boolean"](False)235 236 237 def test_template_test_with_name(app):236- @app.template_test('boolean')238+ @app.template_test("boolean")239 def is_boolean(value):240 return isinstance(value, bool)241 240- assert 'boolean' in app.jinja_env.tests.keys()241- assert app.jinja_env.tests['boolean'] == is_boolean242- assert app.jinja_env.tests['boolean'](False)242+ assert "boolean" in app.jinja_env.tests.keys()243+ assert app.jinja_env.tests["boolean"] == is_boolean244+ assert app.jinja_env.tests["boolean"](False)245 246 247 def test_add_template_test_with_name(app):248 def is_boolean(value):249 return isinstance(value, bool)250 249- app.add_template_test(is_boolean, 'boolean')250- assert 'boolean' in app.jinja_env.tests.keys()251- assert app.jinja_env.tests['boolean'] == is_boolean252- assert app.jinja_env.tests['boolean'](False)251+ app.add_template_test(is_boolean, "boolean")252+ assert "boolean" in app.jinja_env.tests.keys()253+ assert app.jinja_env.tests["boolean"] == is_boolean254+ assert app.jinja_env.tests["boolean"](False)255 256 257 def test_template_test_with_template(app, client):258 @app.template_test()259 def boolean(value):260 return isinstance(value, bool)261 260- @app.route('/')262+ @app.route("/")263 def index():262- return flask.render_template('template_test.html', value=False)264+ return flask.render_template("template_test.html", value=False)265 264- rv = client.get('/')265- assert b'Success!' in rv.data266+ rv = client.get("/")267+ assert b"Success!" in rv.data268 269 270 def test_add_template_test_with_template(app, client):271 def boolean(value):272 return isinstance(value, bool)273 274 app.add_template_test(boolean)275 274- @app.route('/')276+ @app.route("/")277 def index():276- return flask.render_template('template_test.html', value=False)278+ return flask.render_template("template_test.html", value=False)279 278- rv = client.get('/')279- assert b'Success!' in rv.data280+ rv = client.get("/")281+ assert b"Success!" in rv.data282 283 284 def test_template_test_with_name_and_template(app, client):283- @app.template_test('boolean')285+ @app.template_test("boolean")286 def is_boolean(value):287 return isinstance(value, bool)288 287- @app.route('/')289+ @app.route("/")290 def index():289- return flask.render_template('template_test.html', value=False)291+ return flask.render_template("template_test.html", value=False)292 291- rv = client.get('/')292- assert b'Success!' in rv.data293+ rv = client.get("/")294+ assert b"Success!" in rv.data295 296 297 def test_add_template_test_with_name_and_template(app, client):298 def is_boolean(value):299 return isinstance(value, bool)300 299- app.add_template_test(is_boolean, 'boolean')301+ app.add_template_test(is_boolean, "boolean")302 301- @app.route('/')303+ @app.route("/")304 def index():303- return flask.render_template('template_test.html', value=False)305+ return flask.render_template("template_test.html", value=False)306 305- rv = client.get('/')306- assert b'Success!' in rv.data307+ rv = client.get("/")308+ assert b"Success!" in rv.data309 310 311 def test_add_template_global(app, app_ctx):312 @app.template_global()313 def get_stuff():314 return 42315 314- assert 'get_stuff' in app.jinja_env.globals.keys()315- assert app.jinja_env.globals['get_stuff'] == get_stuff316- assert app.jinja_env.globals['get_stuff'](), 42316+ assert "get_stuff" in app.jinja_env.globals.keys()317+ assert app.jinja_env.globals["get_stuff"] == get_stuff318+ assert app.jinja_env.globals["get_stuff"](), 42319 318- rv = flask.render_template_string('{{ get_stuff() }}')319- assert rv == '42'320+ rv = flask.render_template_string("{{ get_stuff() }}")321+ assert rv == "42"322 323 324 def test_custom_template_loader(client):325 class MyFlask(flask.Flask):326 def create_global_jinja_loader(self):327 from jinja2 import DictLoader326- return DictLoader({'index.html': 'Hello Custom World!'})328 329+ return DictLoader({"index.html": "Hello Custom World!"})330+331 app = MyFlask(__name__)332 330- @app.route('/')333+ @app.route("/")334 def index():332- return flask.render_template('index.html')335+ return flask.render_template("index.html")336 337 c = app.test_client()335- rv = c.get('/')336- assert rv.data == b'Hello Custom World!'338+ rv = c.get("/")339+ assert rv.data == b"Hello Custom World!"340 341 342 def test_iterable_loader(app, client):343 @app.context_processor344 def context_processor():342- return {'whiskey': 'Jameson'}345+ return {"whiskey": "Jameson"}346 344- @app.route('/')347+ @app.route("/")348 def index():349 return flask.render_template(347- ['no_template.xml', # should skip this one348- 'simple_template.html', # should render this349- 'context_template.html'],350- value=23)350+ [351+ "no_template.xml", # should skip this one352+ "simple_template.html", # should render this353+ "context_template.html",354+ ],355+ value=23,356+ )357 352- rv = client.get('/')353- assert rv.data == b'<h1>Jameson</h1>'358+ rv = client.get("/")359+ assert rv.data == b"<h1>Jameson</h1>"360 361 362 def test_templates_auto_reload(app):363 # debug is False, config option is None364 assert app.debug is False359- assert app.config['TEMPLATES_AUTO_RELOAD'] is None365+ assert app.config["TEMPLATES_AUTO_RELOAD"] is None366 assert app.jinja_env.auto_reload is False367 # debug is False, config option is False368 app = flask.Flask(__name__)363- app.config['TEMPLATES_AUTO_RELOAD'] = False369+ app.config["TEMPLATES_AUTO_RELOAD"] = False370 assert app.debug is False371 assert app.jinja_env.auto_reload is False372 # debug is False, config option is True373 app = flask.Flask(__name__)368- app.config['TEMPLATES_AUTO_RELOAD'] = True374+ app.config["TEMPLATES_AUTO_RELOAD"] = True375 assert app.debug is False376 assert app.jinja_env.auto_reload is True377 # debug is True, config option is None378 app = flask.Flask(__name__)373- app.config['DEBUG'] = True374- assert app.config['TEMPLATES_AUTO_RELOAD'] is None379+ app.config["DEBUG"] = True380+ assert app.config["TEMPLATES_AUTO_RELOAD"] is None381 assert app.jinja_env.auto_reload is True382 # debug is True, config option is False383 app = flask.Flask(__name__)378- app.config['DEBUG'] = True379- app.config['TEMPLATES_AUTO_RELOAD'] = False384+ app.config["DEBUG"] = True385+ app.config["TEMPLATES_AUTO_RELOAD"] = False386 assert app.jinja_env.auto_reload is False387 # debug is True, config option is True388 app = flask.Flask(__name__)383- app.config['DEBUG'] = True384- app.config['TEMPLATES_AUTO_RELOAD'] = True389+ app.config["DEBUG"] = True390+ app.config["TEMPLATES_AUTO_RELOAD"] = True391 assert app.jinja_env.auto_reload is True392 393+394 def test_templates_auto_reload_debug_run(app, monkeypatch):395 def run_simple_mock(*args, **kwargs):396 pass397 391- monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)398+ monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)399 400 app.run()401 assert app.templates_auto_reload == False402 assert app.jinja_env.auto_reload == False12 unmodified lines415 def handle(x, record):416 called.append(True)417 text = str(record.msg)418 assert '1: trying loader of application "blueprintapp"' in text412- assert ('2: trying loader of blueprint "admin" '413- '(blueprintapp.apps.admin)') in text414- assert ('trying loader of blueprint "frontend" '415- '(blueprintapp.apps.frontend)') in text416- assert 'Error: the template could not be found' in text417- assert ('looked up from an endpoint that belongs to '418- 'the blueprint "frontend"') in text419- assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text419+ assert (420+ '2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"421+ ) in text422+ assert (423+ 'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"424+ ) in text425+ assert "Error: the template could not be found" in text426+ assert (427+ "looked up from an endpoint that belongs to " 'the blueprint "frontend"'428+ ) in text429+ assert "See http://flask.pocoo.org/docs/blueprints/#templates" in text430 431 with app.test_client() as c:422- monkeypatch.setitem(app.config, 'EXPLAIN_TEMPLATE_LOADING', True)423- monkeypatch.setattr(424- logging.getLogger('flask'), 'handlers', [_TestHandler()]425- )432+ monkeypatch.setitem(app.config, "EXPLAIN_TEMPLATE_LOADING", True)433+ monkeypatch.setattr(logging.getLogger("flask"), "handlers", [_TestHandler()])434 435 with pytest.raises(TemplateNotFound) as excinfo:428- c.get('/missing')436+ c.get("/missing")437 430- assert 'missing_template.html' in str(excinfo.value)438+ assert "missing_template.html" in str(excinfo.value)439 440 assert len(called) == 1441 442 9 unmodified linesmodified:tests/test_testing.py+112 added-112 removed
19 unmodified lines20 from flask.testing import make_test_environ_builder, FlaskCliRunner21 22 23 def test_environ_defaults_from_config(app, client):24- app.config['SERVER_NAME'] = 'example.com:1234'25- app.config['APPLICATION_ROOT'] = '/foo'24+ app.config["SERVER_NAME"] = "example.com:1234"25+ app.config["APPLICATION_ROOT"] = "/foo"26 27- @app.route('/')27+ @app.route("/")28 def index():29 return flask.request.url30 31 ctx = app.test_request_context()32- assert ctx.request.url == 'http://example.com:1234/foo/'32+ assert ctx.request.url == "http://example.com:1234/foo/"33 34- rv = client.get('/')35- assert rv.data == b'http://example.com:1234/foo/'34+ rv = client.get("/")35+ assert rv.data == b"http://example.com:1234/foo/"36 37 38 def test_environ_defaults(app, client, app_ctx, req_ctx):39- @app.route('/')39+ @app.route("/")40 def index():41 return flask.request.url42 43 ctx = app.test_request_context()44- assert ctx.request.url == 'http://localhost/'44+ assert ctx.request.url == "http://localhost/"45 with client:46- rv = client.get('/')47- assert rv.data == b'http://localhost/'46+ rv = client.get("/")47+ assert rv.data == b"http://localhost/"48 49 50 def test_environ_base_default(app, client, app_ctx):51- @app.route('/')51+ @app.route("/")52 def index():53 flask.g.user_agent = flask.request.headers["User-Agent"]54 return flask.request.remote_addr55 56- rv = client.get('/')57- assert rv.data == b'127.0.0.1'58- assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__56+ rv = client.get("/")57+ assert rv.data == b"127.0.0.1"58+ assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__59 60 61 def test_environ_base_modified(app, client, app_ctx):62- @app.route('/')62+ @app.route("/")63 def index():64 flask.g.user_agent = flask.request.headers["User-Agent"]65 return flask.request.remote_addr66 67- client.environ_base['REMOTE_ADDR'] = '0.0.0.0'68- client.environ_base['HTTP_USER_AGENT'] = 'Foo'69- rv = client.get('/')70- assert rv.data == b'0.0.0.0'71- assert flask.g.user_agent == 'Foo'67+ client.environ_base["REMOTE_ADDR"] = "0.0.0.0"68+ client.environ_base["HTTP_USER_AGENT"] = "Foo"69+ rv = client.get("/")70+ assert rv.data == b"0.0.0.0"71+ assert flask.g.user_agent == "Foo"72 73- client.environ_base['REMOTE_ADDR'] = '0.0.0.1'74- client.environ_base['HTTP_USER_AGENT'] = 'Bar'75- rv = client.get('/')76- assert rv.data == b'0.0.0.1'77- assert flask.g.user_agent == 'Bar'73+ client.environ_base["REMOTE_ADDR"] = "0.0.0.1"74+ client.environ_base["HTTP_USER_AGENT"] = "Bar"75+ rv = client.get("/")76+ assert rv.data == b"0.0.0.1"77+ assert flask.g.user_agent == "Bar"78 79 80 def test_client_open_environ(app, client, request):81- @app.route('/index')81+ @app.route("/index")82 def index():83 return flask.request.remote_addr84 85- builder = make_test_environ_builder(app, path='/index', method='GET')85+ builder = make_test_environ_builder(app, path="/index", method="GET")86 request.addfinalizer(builder.close)87 88 rv = client.open(builder)89- assert rv.data == b'127.0.0.1'89+ assert rv.data == b"127.0.0.1"90 91 environ = builder.get_environ()92- client.environ_base['REMOTE_ADDR'] = '127.0.0.2'92+ client.environ_base["REMOTE_ADDR"] = "127.0.0.2"93 rv = client.open(environ)94- assert rv.data == b'127.0.0.2'94+ assert rv.data == b"127.0.0.2"95 96 97 def test_specify_url_scheme(app, client):98- @app.route('/')98+ @app.route("/")99 def index():100 return flask.request.url101 102- ctx = app.test_request_context(url_scheme='https')103- assert ctx.request.url == 'https://localhost/'102+ ctx = app.test_request_context(url_scheme="https")103+ assert ctx.request.url == "https://localhost/"104 105- rv = client.get('/', url_scheme='https')106- assert rv.data == b'https://localhost/'105+ rv = client.get("/", url_scheme="https")106+ assert rv.data == b"https://localhost/"107 108 109 def test_path_is_url(app):110- eb = make_test_environ_builder(app, 'https://example.com/')111- assert eb.url_scheme == 'https'112- assert eb.host == 'example.com'113- assert eb.script_root == ''114- assert eb.path == '/'110+ eb = make_test_environ_builder(app, "https://example.com/")111+ assert eb.url_scheme == "https"112+ assert eb.host == "example.com"113+ assert eb.script_root == ""114+ assert eb.path == "/"115 116 117 def test_blueprint_with_subdomain():118 app = flask.Flask(__name__, subdomain_matching=True)119- app.config['SERVER_NAME'] = 'example.com:1234'120- app.config['APPLICATION_ROOT'] = '/foo'119+ app.config["SERVER_NAME"] = "example.com:1234"120+ app.config["APPLICATION_ROOT"] = "/foo"121 client = app.test_client()122 123- bp = flask.Blueprint('company', __name__, subdomain='xxx')123+ bp = flask.Blueprint("company", __name__, subdomain="xxx")124 125- @bp.route('/')125+ @bp.route("/")126 def index():127 return flask.request.url128 129 app.register_blueprint(bp)130 131- ctx = app.test_request_context('/', subdomain='xxx')132- assert ctx.request.url == 'http://xxx.example.com:1234/foo/'131+ ctx = app.test_request_context("/", subdomain="xxx")132+ assert ctx.request.url == "http://xxx.example.com:1234/foo/"133 assert ctx.request.blueprint == bp.name134 135- rv = client.get('/', subdomain='xxx')136- assert rv.data == b'http://xxx.example.com:1234/foo/'135+ rv = client.get("/", subdomain="xxx")136+ assert rv.data == b"http://xxx.example.com:1234/foo/"137 138 139 def test_redirect_keep_session(app, client, app_ctx):140- @app.route('/', methods=['GET', 'POST'])140+ @app.route("/", methods=["GET", "POST"])141 def index():142- if flask.request.method == 'POST':143- return flask.redirect('/getsession')144- flask.session['data'] = 'foo'145- return 'index'142+ if flask.request.method == "POST":143+ return flask.redirect("/getsession")144+ flask.session["data"] = "foo"145+ return "index"146 147- @app.route('/getsession')147+ @app.route("/getsession")148 def get_session():149- return flask.session.get('data', '<missing>')149+ return flask.session.get("data", "<missing>")150 151 with client:152- rv = client.get('/getsession')153- assert rv.data == b'<missing>'152+ rv = client.get("/getsession")153+ assert rv.data == b"<missing>"154 155- rv = client.get('/')156- assert rv.data == b'index'157- assert flask.session.get('data') == 'foo'158- rv = client.post('/', data={}, follow_redirects=True)159- assert rv.data == b'foo'155+ rv = client.get("/")156+ assert rv.data == b"index"157+ assert flask.session.get("data") == "foo"158+ rv = client.post("/", data={}, follow_redirects=True)159+ assert rv.data == b"foo"160 161 # This support requires a new Werkzeug version162- if not hasattr(client, 'redirect_client'):163- assert flask.session.get('data') == 'foo'162+ if not hasattr(client, "redirect_client"):163+ assert flask.session.get("data") == "foo"164 165- rv = client.get('/getsession')166- assert rv.data == b'foo'165+ rv = client.get("/getsession")166+ assert rv.data == b"foo"167 168 169 def test_session_transactions(app, client):170- @app.route('/')170+ @app.route("/")171 def index():172- return text_type(flask.session['foo'])172+ return text_type(flask.session["foo"])173 174 with client:175 with client.session_transaction() as sess:176 assert len(sess) == 0177- sess['foo'] = [42]177+ sess["foo"] = [42]178 assert len(sess) == 1179- rv = client.get('/')180- assert rv.data == b'[42]'179+ rv = client.get("/")180+ assert rv.data == b"[42]"181 with client.session_transaction() as sess:182 assert len(sess) == 1183- assert sess['foo'] == [42]183+ assert sess["foo"] == [42]184 185 186 def test_session_transactions_no_null_sessions():187 app = flask.Flask(__name__)2 unmodified lines190 with app.test_client() as c:191 with pytest.raises(RuntimeError) as e:192 with c.session_transaction() as sess:193 pass194- assert 'Session backend did not open a session' in str(e.value)194+ assert "Session backend did not open a session" in str(e.value)195 196 197 def test_session_transactions_keep_context(app, client, req_ctx):198- rv = client.get('/')198+ rv = client.get("/")199 req = flask.request._get_current_object()200 assert req is not None201 with client.session_transaction():202 assert req is flask.request._get_current_object()3 unmodified lines206 c = app.test_client(use_cookies=False)207 with pytest.raises(RuntimeError) as e:208 with c.session_transaction() as s:209 pass210- assert 'cookies' in str(e.value)210+ assert "cookies" in str(e.value)211 212 213 def test_test_client_context_binding(app, client):214 app.testing = False215 216- @app.route('/')216+ @app.route("/")217 def index():218 flask.g.value = 42219- return 'Hello World!'219+ return "Hello World!"220 221- @app.route('/other')221+ @app.route("/other")222 def other():223 1 // 0224 225 with client:226- resp = client.get('/')226+ resp = client.get("/")227 assert flask.g.value == 42228- assert resp.data == b'Hello World!'228+ assert resp.data == b"Hello World!"229 assert resp.status_code == 200230 231- resp = client.get('/other')232- assert not hasattr(flask.g, 'value')233- assert b'Internal Server Error' in resp.data231+ resp = client.get("/other")232+ assert not hasattr(flask.g, "value")233+ assert b"Internal Server Error" in resp.data234 assert resp.status_code == 500235 flask.g.value = 23236 237 try:238 flask.g.value239 except (AttributeError, RuntimeError):240 pass241 else:242- raise AssertionError('some kind of exception expected')242+ raise AssertionError("some kind of exception expected")243 244 245 def test_reuse_client(client):246 c = client247 248 with c:249- assert client.get('/').status_code == 404249+ assert client.get("/").status_code == 404250 251 with c:252- assert client.get('/').status_code == 404252+ assert client.get("/").status_code == 404253 254 255 def test_test_client_calls_teardown_handlers(app, client):256 called = []3 unmodified lines260 called.append(error)261 262 with client:263 assert called == []264- client.get('/')264+ client.get("/")265 assert called == []266 assert called == [None]267 268 del called[:]269 with client:270 assert called == []271- client.get('/')271+ client.get("/")272 assert called == []273- client.get('/')273+ client.get("/")274 assert called == [None]275 assert called == [None, None]276 277 278 def test_full_url_request(app, client):279- @app.route('/action', methods=['POST'])279+ @app.route("/action", methods=["POST"])280 def action():281- return 'x'281+ return "x"282 283 with client:284- rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})284+ rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})285 assert rv.status_code == 200286- assert 'gin' in flask.request.form287- assert 'vodka' in flask.request.args286+ assert "gin" in flask.request.form287+ assert "vodka" in flask.request.args288 289 290 def test_json_request_and_response(app, client):291- @app.route('/echo', methods=['POST'])291+ @app.route("/echo", methods=["POST"])292 def echo():293 return jsonify(flask.request.get_json())294 295 with client:296- json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}297- rv = client.post('/echo', json=json_data)296+ json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}297+ rv = client.post("/echo", json=json_data)298 299 # Request should be in JSON300 assert flask.request.is_json301 assert flask.request.get_json() == json_data5 unmodified lines307 308 309 def test_subdomain():310 app = flask.Flask(__name__, subdomain_matching=True)311- app.config['SERVER_NAME'] = 'example.com'311+ app.config["SERVER_NAME"] = "example.com"312 client = app.test_client()313 314- @app.route('/', subdomain='<company_id>')314+ @app.route("/", subdomain="<company_id>")315 def view(company_id):316 return company_id317 318 with app.test_request_context():319- url = flask.url_for('view', company_id='xxx')319+ url = flask.url_for("view", company_id="xxx")320 321 with client:322 response = client.get(url)323 324 assert 200 == response.status_code325- assert b'xxx' == response.data325+ assert b"xxx" == response.data326 327 328 def test_nosubdomain(app, client):329- app.config['SERVER_NAME'] = 'example.com'329+ app.config["SERVER_NAME"] = "example.com"330 331- @app.route('/<company_id>')331+ @app.route("/<company_id>")332 def view(company_id):333 return company_id334 335 with app.test_request_context():336- url = flask.url_for('view', company_id='xxx')336+ url = flask.url_for("view", company_id="xxx")337 338 with client:339 response = client.get(url)340 341 assert 200 == response.status_code342- assert b'xxx' == response.data342+ assert b"xxx" == response.data343 344 345 def test_cli_runner_class(app):346 runner = app.test_cli_runner()7 unmodified lines354 assert isinstance(runner, SubRunner)355 356 357 def test_cli_invoke(app):358- @app.cli.command('hello')358+ @app.cli.command("hello")359 def hello_command():360- click.echo('Hello, World!')360+ click.echo("Hello, World!")361 362 runner = app.test_cli_runner()363 # invoke with command name364- result = runner.invoke(args=['hello'])365- assert 'Hello' in result.output364+ result = runner.invoke(args=["hello"])365+ assert "Hello" in result.output366 # invoke with command object367 result = runner.invoke(hello_command)368- assert 'Hello' in result.output368+ assert "Hello" in result.output369 370 371 def test_cli_custom_obj(app):372 class NS(object):2 unmodified lines375 def create_app():376 NS.called = True377 return app378 379- @app.cli.command('hello')379+ @app.cli.command("hello")380 def hello_command():381- click.echo('Hello, World!')381+ click.echo("Hello, World!")382 383 script_info = ScriptInfo(create_app=create_app)384 runner = app.test_cli_runner()385 runner.invoke(hello_command, obj=script_info)1 unmodified linemodified:tests/test_user_error_handler.py+43 added-49 removed
5 unmodified lines6 :copyright: © 2010 by the Pallets team.7 :license: BSD, see LICENSE for more details.8 """9 10-from werkzeug.exceptions import (11- Forbidden,12- InternalServerError,13- HTTPException,14- NotFound15- )10+from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound11 import flask12 13 14 def test_error_handler_no_match(app, client):20-15 class CustomException(Exception):16 pass17 18 @app.errorhandler(CustomException)19 def custom_exception_handler(e):20 assert isinstance(e, CustomException)27- return 'custom'21+ return "custom"22 23 @app.errorhandler(500)24 def handle_500(e):25 return type(e).__name__26 33- @app.route('/custom')27+ @app.route("/custom")28 def custom_test():29 raise CustomException()30 37- @app.route('/keyerror')31+ @app.route("/keyerror")32 def key_error():33 raise KeyError()34 35 app.testing = False42- assert client.get('/custom').data == b'custom'43- assert client.get('/keyerror').data == b'KeyError'36+ assert client.get("/custom").data == b"custom"37+ assert client.get("/keyerror").data == b"KeyError"38 39 40 def test_error_handler_subclass(app):41 class ParentException(Exception):7 unmodified lines49 50 @app.errorhandler(ParentException)51 def parent_exception_handler(e):52 assert isinstance(e, ParentException)59- return 'parent'53+ return "parent"54 55 @app.errorhandler(ChildExceptionRegistered)56 def child_exception_handler(e):57 assert isinstance(e, ChildExceptionRegistered)64- return 'child-registered'58+ return "child-registered"59 66- @app.route('/parent')60+ @app.route("/parent")61 def parent_test():62 raise ParentException()63 70- @app.route('/child-unregistered')64+ @app.route("/child-unregistered")65 def unregistered_test():66 raise ChildExceptionUnregistered()67 74- @app.route('/child-registered')68+ @app.route("/child-registered")69 def registered_test():70 raise ChildExceptionRegistered()71 72 c = app.test_client()73 80- assert c.get('/parent').data == b'parent'81- assert c.get('/child-unregistered').data == b'parent'82- assert c.get('/child-registered').data == b'child-registered'74+ assert c.get("/parent").data == b"parent"75+ assert c.get("/child-unregistered").data == b"parent"76+ assert c.get("/child-registered").data == b"child-registered"77 78 79 def test_error_handler_http_subclass(app):80 class ForbiddenSubclassRegistered(Forbidden):4 unmodified lines85 86 @app.errorhandler(403)87 def code_exception_handler(e):88 assert isinstance(e, Forbidden)95- return 'forbidden'89+ return "forbidden"90 91 @app.errorhandler(ForbiddenSubclassRegistered)92 def subclass_exception_handler(e):93 assert isinstance(e, ForbiddenSubclassRegistered)100- return 'forbidden-registered'94+ return "forbidden-registered"95 102- @app.route('/forbidden')96+ @app.route("/forbidden")97 def forbidden_test():98 raise Forbidden()99 106- @app.route('/forbidden-registered')100+ @app.route("/forbidden-registered")101 def registered_test():102 raise ForbiddenSubclassRegistered()103 110- @app.route('/forbidden-unregistered')104+ @app.route("/forbidden-unregistered")105 def unregistered_test():106 raise ForbiddenSubclassUnregistered()107 108 c = app.test_client()109 116- assert c.get('/forbidden').data == b'forbidden'117- assert c.get('/forbidden-unregistered').data == b'forbidden'118- assert c.get('/forbidden-registered').data == b'forbidden-registered'110+ assert c.get("/forbidden").data == b"forbidden"111+ assert c.get("/forbidden-unregistered").data == b"forbidden"112+ assert c.get("/forbidden-registered").data == b"forbidden-registered"113 114 115 def test_error_handler_blueprint(app):122- bp = flask.Blueprint('bp', __name__)116+ bp = flask.Blueprint("bp", __name__)117 118 @bp.errorhandler(500)119 def bp_exception_handler(e):126- return 'bp-error'120+ return "bp-error"121 128- @bp.route('/error')122+ @bp.route("/error")123 def bp_test():124 raise InternalServerError()125 126 @app.errorhandler(500)127 def app_exception_handler(e):134- return 'app-error'128+ return "app-error"129 136- @app.route('/error')130+ @app.route("/error")131 def app_test():132 raise InternalServerError()133 140- app.register_blueprint(bp, url_prefix='/bp')134+ app.register_blueprint(bp, url_prefix="/bp")135 136 c = app.test_client()137 144- assert c.get('/error').data == b'app-error'145- assert c.get('/bp/error').data == b'bp-error'138+ assert c.get("/error").data == b"app-error"139+ assert c.get("/bp/error").data == b"bp-error"140 141 142 def test_default_error_handler():149- bp = flask.Blueprint('bp', __name__)143+ bp = flask.Blueprint("bp", __name__)144 145 @bp.errorhandler(HTTPException)146 def bp_exception_handler(e):147 assert isinstance(e, HTTPException)148 assert isinstance(e, NotFound)155- return 'bp-default'149+ return "bp-default"150 151 @bp.errorhandler(Forbidden)152 def bp_exception_handler(e):153 assert isinstance(e, Forbidden)160- return 'bp-forbidden'154+ return "bp-forbidden"155 162- @bp.route('/undefined')156+ @bp.route("/undefined")157 def bp_registered_test():158 raise NotFound()159 166- @bp.route('/forbidden')160+ @bp.route("/forbidden")161 def bp_forbidden_test():162 raise Forbidden()163 164 app = flask.Flask(__name__)1 unmodified line166 @app.errorhandler(HTTPException)167 def catchall_errorhandler(e):168 assert isinstance(e, HTTPException)169 assert isinstance(e, NotFound)176- return 'default'170+ return "default"171 172 @app.errorhandler(Forbidden)173 def catchall_errorhandler(e):174 assert isinstance(e, Forbidden)181- return 'forbidden'175+ return "forbidden"176 183- @app.route('/forbidden')177+ @app.route("/forbidden")178 def forbidden():179 raise Forbidden()180 181 @app.route("/slash/")182 def slash():183 return "slash"184 191- app.register_blueprint(bp, url_prefix='/bp')185+ app.register_blueprint(bp, url_prefix="/bp")186 187 c = app.test_client()194- assert c.get('/bp/undefined').data == b'bp-default'195- assert c.get('/bp/forbidden').data == b'bp-forbidden'196- assert c.get('/undefined').data == b'default'197- assert c.get('/forbidden').data == b'forbidden'188+ assert c.get("/bp/undefined").data == b"bp-default"189+ assert c.get("/bp/forbidden").data == b"bp-forbidden"190+ assert c.get("/undefined").data == b"default"191+ assert c.get("/forbidden").data == b"forbidden"192 # Don't handle RequestRedirect raised when adding slash.193 assert c.get("/slash", follow_redirects=True).data == b"slash"modified:tests/test_views.py+70 added-72 removed
18 unmodified lines19 20 def common_test(app):21 c = app.test_client()22 23- assert c.get('/').data == b'GET'24- assert c.post('/').data == b'POST'25- assert c.put('/').status_code == 40526- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27- assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']23+ assert c.get("/").data == b"GET"24+ assert c.post("/").data == b"POST"25+ assert c.put("/").status_code == 40526+ meths = parse_set_header(c.open("/", method="OPTIONS").headers["Allow"])27+ assert sorted(meths) == ["GET", "HEAD", "OPTIONS", "POST"]28 29 30 def test_basic_view(app):31 class Index(flask.views.View):32- methods = ['GET', 'POST']32+ methods = ["GET", "POST"]33 34 def dispatch_request(self):35 return flask.request.method36 37- app.add_url_rule('/', view_func=Index.as_view('index'))37+ app.add_url_rule("/", view_func=Index.as_view("index"))38 common_test(app)39 40 41 def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44- return 'GET'44+ return "GET"45 46 def post(self):47- return 'POST'47+ return "POST"48 49- app.add_url_rule('/', view_func=Index.as_view('index'))49+ app.add_url_rule("/", view_func=Index.as_view("index"))50 51 common_test(app)52 53 6 unmodified lines60 1 // 061 62 class Other(Index):63 def get(self):64- return 'GET'64+ return "GET"65 66 def post(self):67- return 'POST'67+ return "POST"68 69- view = Index.as_view('index')69+ view = Index.as_view("index")70 view.view_class = Other71- app.add_url_rule('/', view_func=view)71+ app.add_url_rule("/", view_func=view)72 common_test(app)73 74 75 def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78- return 'GET'78+ return "GET"79 80 def post(self):81- return 'POST'81+ return "POST"82 83 class BetterIndex(Index):84 def delete(self):85- return 'DELETE'85+ return "DELETE"86 87- app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87+ app.add_url_rule("/", view_func=BetterIndex.as_view("index"))88 89- meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90- assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']89+ meths = parse_set_header(client.open("/", method="OPTIONS").headers["Allow"])90+ assert sorted(meths) == ["DELETE", "GET", "HEAD", "OPTIONS", "POST"]91 92 93 def test_view_decorators(app, client):94 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97- resp.headers['X-Parachute'] = 'awesome'97+ resp.headers["X-Parachute"] = "awesome"98 return resp99 100 return new_function101 102 class Index(flask.views.View):103 decorators = [add_x_parachute]104 105 def dispatch_request(self):106- return 'Awesome'106+ return "Awesome"107 108- app.add_url_rule('/', view_func=Index.as_view('index'))109- rv = client.get('/')110- assert rv.headers['X-Parachute'] == 'awesome'111- assert rv.data == b'Awesome'108+ app.add_url_rule("/", view_func=Index.as_view("index"))109+ rv = client.get("/")110+ assert rv.headers["X-Parachute"] == "awesome"111+ assert rv.data == b"Awesome"112 113 114 def test_view_provide_automatic_options_attr():115 app = flask.Flask(__name__)1 unmodified line117 class Index1(flask.views.View):118 provide_automatic_options = False119 120 def dispatch_request(self):121- return 'Hello World!'121+ return "Hello World!"122 123- app.add_url_rule('/', view_func=Index1.as_view('index'))123+ app.add_url_rule("/", view_func=Index1.as_view("index"))124 c = app.test_client()125- rv = c.open('/', method='OPTIONS')125+ rv = c.open("/", method="OPTIONS")126 assert rv.status_code == 405127 128 app = flask.Flask(__name__)129 130 class Index2(flask.views.View):131- methods = ['OPTIONS']131+ methods = ["OPTIONS"]132 provide_automatic_options = True133 134 def dispatch_request(self):135- return 'Hello World!'135+ return "Hello World!"136 137- app.add_url_rule('/', view_func=Index2.as_view('index'))137+ app.add_url_rule("/", view_func=Index2.as_view("index"))138 c = app.test_client()139- rv = c.open('/', method='OPTIONS')140- assert sorted(rv.allow) == ['OPTIONS']139+ rv = c.open("/", method="OPTIONS")140+ assert sorted(rv.allow) == ["OPTIONS"]141 142 app = flask.Flask(__name__)143 144 class Index3(flask.views.View):145 def dispatch_request(self):146- return 'Hello World!'146+ return "Hello World!"147 148- app.add_url_rule('/', view_func=Index3.as_view('index'))148+ app.add_url_rule("/", view_func=Index3.as_view("index"))149 c = app.test_client()150- rv = c.open('/', method='OPTIONS')151- assert 'OPTIONS' in rv.allow150+ rv = c.open("/", method="OPTIONS")151+ assert "OPTIONS" in rv.allow152 153 154 def test_implicit_head(app, client):155 class Index(flask.views.MethodView):156 def get(self):157- return flask.Response('Blub', headers={158- 'X-Method': flask.request.method159- })157+ return flask.Response("Blub", headers={"X-Method": flask.request.method})158 161- app.add_url_rule('/', view_func=Index.as_view('index'))162- rv = client.get('/')163- assert rv.data == b'Blub'164- assert rv.headers['X-Method'] == 'GET'165- rv = client.head('/')166- assert rv.data == b''167- assert rv.headers['X-Method'] == 'HEAD'159+ app.add_url_rule("/", view_func=Index.as_view("index"))160+ rv = client.get("/")161+ assert rv.data == b"Blub"162+ assert rv.headers["X-Method"] == "GET"163+ rv = client.head("/")164+ assert rv.data == b""165+ assert rv.headers["X-Method"] == "HEAD"166 167 168 def test_explicit_head(app, client):169 class Index(flask.views.MethodView):170 def get(self):173- return 'GET'171+ return "GET"172 173 def head(self):176- return flask.Response('', headers={'X-Method': 'HEAD'})174+ return flask.Response("", headers={"X-Method": "HEAD"})175 178- app.add_url_rule('/', view_func=Index.as_view('index'))179- rv = client.get('/')180- assert rv.data == b'GET'181- rv = client.head('/')182- assert rv.data == b''183- assert rv.headers['X-Method'] == 'HEAD'176+ app.add_url_rule("/", view_func=Index.as_view("index"))177+ rv = client.get("/")178+ assert rv.data == b"GET"179+ rv = client.head("/")180+ assert rv.data == b""181+ assert rv.headers["X-Method"] == "HEAD"182 183 184 def test_endpoint_override(app):185 app.debug = True186 187 class Index(flask.views.View):190- methods = ['GET', 'POST']188+ methods = ["GET", "POST"]189 190 def dispatch_request(self):191 return flask.request.method192 195- app.add_url_rule('/', view_func=Index.as_view('index'))193+ app.add_url_rule("/", view_func=Index.as_view("index"))194 195 with pytest.raises(AssertionError):198- app.add_url_rule('/', view_func=Index.as_view('index'))196+ app.add_url_rule("/", view_func=Index.as_view("index"))197 198 # But these tests should still pass. We just log a warning.199 common_test(app)200 201 202 def test_multiple_inheritance(app, client):203 class GetView(flask.views.MethodView):204 def get(self):207- return 'GET'205+ return "GET"206 207 class DeleteView(flask.views.MethodView):208 def delete(self):211- return 'DELETE'209+ return "DELETE"210 211 class GetDeleteView(GetView, DeleteView):212 pass213 216- app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))214+ app.add_url_rule("/", view_func=GetDeleteView.as_view("index"))215 218- assert client.get('/').data == b'GET'219- assert client.delete('/').data == b'DELETE'220- assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']216+ assert client.get("/").data == b"GET"217+ assert client.delete("/").data == b"DELETE"218+ assert sorted(GetDeleteView.methods) == ["DELETE", "GET"]219 220 221 def test_remove_method_from_parent(app, client):222 class GetView(flask.views.MethodView):223 def get(self):226- return 'GET'224+ return "GET"225 226 class OtherView(flask.views.MethodView):227 def post(self):230- return 'POST'228+ return "POST"229 230 class View(GetView, OtherView):233- methods = ['GET']231+ methods = ["GET"]232 235- app.add_url_rule('/', view_func=View.as_view('index'))233+ app.add_url_rule("/", view_func=View.as_view("index"))234 237- assert client.get('/').data == b'GET'238- assert client.post('/').status_code == 405239- assert sorted(View.methods) == ['GET']235+ assert client.get("/").data == b"GET"236+ assert client.post("/").status_code == 405237+ assert sorted(View.methods) == ["GET"]added:.pre-commit-config.yaml+5 added
1+repos:2+ - repo: https://github.com/python/black3+ rev: 19.3b04+ hooks:5+ - id: blackmodified:setup.py+53 added-59 removed
4 unmodified lines5 from collections import OrderedDict6 7 from setuptools import setup8 9-with io.open('README.rst', 'rt', encoding='utf8') as f:9+with io.open("README.rst", "rt", encoding="utf8") as f:10 readme = f.read()11 12-with io.open('flask/__init__.py', 'rt', encoding='utf8') as f:13- version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)12+with io.open("flask/__init__.py", "rt", encoding="utf8") as f:13+ version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1)14 15 setup(16- name='Flask',16+ name="Flask",17 version=version,18- url='https://www.palletsprojects.com/p/flask/',19- project_urls=OrderedDict((20- ('Documentation', 'http://flask.pocoo.org/docs/'),21- ('Code', 'https://github.com/pallets/flask'),22- ('Issue tracker', 'https://github.com/pallets/flask/issues'),23- )),24- license='BSD',25- author='Armin Ronacher',26- author_email='armin.ronacher@active-4.com',27- maintainer='Pallets team',28- maintainer_email='contact@palletsprojects.com',29- description='A simple framework for building complex web applications.',18+ url="https://www.palletsprojects.com/p/flask/",19+ project_urls=OrderedDict(20+ (21+ ("Documentation", "http://flask.pocoo.org/docs/"),22+ ("Code", "https://github.com/pallets/flask"),23+ ("Issue tracker", "https://github.com/pallets/flask/issues"),24+ )25+ ),26+ license="BSD",27+ author="Armin Ronacher",28+ author_email="armin.ronacher@active-4.com",29+ maintainer="Pallets team",30+ maintainer_email="contact@palletsprojects.com",31+ description="A simple framework for building complex web applications.",32 long_description=readme,31- packages=['flask', 'flask.json'],33+ packages=["flask", "flask.json"],34 include_package_data=True,35 zip_safe=False,34- platforms='any',35- python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*',36+ platforms="any",37+ python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",38 install_requires=[37- 'Werkzeug>=0.14',38- 'Jinja2>=2.10.1',39- 'itsdangerous>=0.24',40- 'click>=5.1',39+ "Werkzeug>=0.14",40+ "Jinja2>=2.10.1",41+ "itsdangerous>=0.24",42+ "click>=5.1",43 ],44 extras_require={43- 'dotenv': ['python-dotenv'],44- 'dev': [45- 'pytest>=3',46- 'coverage',47- 'tox',48- 'sphinx',49- 'pallets-sphinx-themes',50- 'sphinxcontrib-log-cabinet',45+ "dotenv": ["python-dotenv"],46+ "dev": [47+ "pytest>=3",48+ "coverage",49+ "tox",50+ "sphinx",51+ "pallets-sphinx-themes",52+ "sphinxcontrib-log-cabinet",53 ],52- 'docs': [53- 'sphinx',54- 'pallets-sphinx-themes',55- 'sphinxcontrib-log-cabinet',56- ]54+ "docs": ["sphinx", "pallets-sphinx-themes", "sphinxcontrib-log-cabinet"],55 },56 classifiers=[59- 'Development Status :: 5 - Production/Stable',60- 'Environment :: Web Environment',61- 'Framework :: Flask',62- 'Intended Audience :: Developers',63- 'License :: OSI Approved :: BSD License',64- 'Operating System :: OS Independent',65- 'Programming Language :: Python',66- 'Programming Language :: Python :: 2',67- 'Programming Language :: Python :: 2.7',68- 'Programming Language :: Python :: 3',69- 'Programming Language :: Python :: 3.4',70- 'Programming Language :: Python :: 3.5',71- 'Programming Language :: Python :: 3.6',72- 'Programming Language :: Python :: 3.7',73- 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',74- 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',75- 'Topic :: Software Development :: Libraries :: Application Frameworks',76- 'Topic :: Software Development :: Libraries :: Python Modules',57+ "Development Status :: 5 - Production/Stable",58+ "Environment :: Web Environment",59+ "Framework :: Flask",60+ "Intended Audience :: Developers",61+ "License :: OSI Approved :: BSD License",62+ "Operating System :: OS Independent",63+ "Programming Language :: Python",64+ "Programming Language :: Python :: 2",65+ "Programming Language :: Python :: 2.7",66+ "Programming Language :: Python :: 3",67+ "Programming Language :: Python :: 3.4",68+ "Programming Language :: Python :: 3.5",69+ "Programming Language :: Python :: 3.6",70+ "Programming Language :: Python :: 3.7",71+ "Topic :: Internet :: WWW/HTTP :: Dynamic Content",72+ "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",73+ "Topic :: Software Development :: Libraries :: Application Frameworks",74+ "Topic :: Software Development :: Libraries :: Python Modules",75 ],78- entry_points={79- 'console_scripts': [80- 'flask = flask.cli:main',81- ],82- },76+ entry_points={"console_scripts": ["flask = flask.cli:main"]},77 )modified:tox.ini+5 added
35 unmodified lines36 37 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest tests examples39 40+[testenv:stylecheck]41+deps = pre-commit42+skip_install = true43+commands = pre-commit run --all-files --show-diff-on-failure44+45 [testenv:docs-html]46 deps =47 -r docs/requirements.txt48 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html17 unmodified lines