Merge branch 'master' into improve-flaskr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by GitHub · parents 54b6fc8, 386ac92 · Browse files · 65 files·+3487 added−2266 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
65 files+3487 added−2266 removed
- tests:+2040 added−1291 removed
- other:+1447 added−975 removed
Provenance
- Commit
e6740ec- Tree
5495b20- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
54b6fc8- Parent 2
386ac92
65 files changed+3487 added−2266 removed
added:docs/_static/pycharm-runconfig.pngbinary
A binary file, added.
modified:docs/_templates/sidebarintro.html+1 added-1 removed
1233456715 unmodified lines<h3>About Flask</h3><p> Flask is a micro webdevelopment framework for Python. You are currently Flask is a micro web development framework for Python. You are currently looking at the documentation of the development version.</p><h3>Other Formats</h3><p>15 unmodified linesmodified:docs/deploying/index.rst+1 added-1 removed
30 unmodified lines31 32 .. toctree::33 :maxdepth: 234 35- mod_wsgi35 wsgi-standalone36 uwsgi37+ mod_wsgi38 fastcgi39 cgimodified:docs/deploying/wsgi-standalone.rst+16 added
25 unmodified lines26 .. _Gunicorn: http://gunicorn.org/27 .. _eventlet: http://eventlet.net/28 .. _greenlet: https://greenlet.readthedocs.io/en/latest/29 30+uWSGI31+--------32+33+`uWSGI`_ is a fast application server written in C. It is very configurable34+which makes it more complicated to setup than gunicorn.35+36+Running `uWSGI HTTP Router`_::37+38+ uwsgi --http 127.0.0.1:5000 --module myproject:app39+40+For a more optimized setup, see `configuring uWSGI and NGINX`_.41+42+.. _uWSGI: http://uwsgi-docs.readthedocs.io/en/latest/43+.. _uWSGI HTTP Router: http://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router44+.. _configuring uWSGI and NGINX: uwsgi.html#starting-your-app-with-uwsgi45+46 Gevent47 -------48 49 `Gevent`_ is a coroutine-based Python networking library that uses101 unmodified linesmodified:docs/patterns/celery.rst+44 added-36 removed
1-Celery Based Background Tasks2-=============================1+Celery Background Tasks2+=======================3 4-Celery is a task queue for Python with batteries included. It used to5-have a Flask integration but it became unnecessary after some6-restructuring of the internals of Celery with Version 3. This guide fills7-in the blanks in how to properly use Celery with Flask but assumes that8-you generally already read the `First Steps with Celery9-<http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_10-guide in the official Celery documentation.4+If your application has a long running task, such as processing some uploaded5+data or sending email, you don't want to wait for it to finish during a6+request. Instead, use a task queue to send the necessary data to another7+process that will run the task in the background while the request returns8+immediately.9 12-Installing Celery13------------------10+Celery is a powerful task queue that can be used for simple background tasks11+as well as complex multi-stage programs and schedules. This guide will show you12+how to configure Celery using Flask, but assumes you've already read the13+`First Steps with Celery <http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_14+guide in the Celery documentation.15 15-Celery is on the Python Package Index (PyPI), so it can be installed with16-standard Python tools like :command:`pip` or :command:`easy_install`::16+Install17+-------18 19+Celery is a separate Python package. Install it from PyPI using pip::20+21 $ pip install celery22 20-Configuring Celery21-------------------23+Configure24+---------25 26 The first thing you need is a Celery instance, this is called the celery27 application. It serves the same purpose as the :class:`~flask.Flask`28 object in Flask, just for Celery. Since this instance is used as the9 unmodified lines38 39 from celery import Celery40 41 def make_celery(app):42+ celery = Celery(43+ app.import_name,39- celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],40- broker=app.config['CELERY_BROKER_URL'])44+ backend=app.config['CELERY_RESULT_BACKEND'],45+ broker=app.config['CELERY_BROKER_URL']46+ )47 celery.conf.update(app.config)42- TaskBase = celery.Task43- class ContextTask(TaskBase):44- abstract = True48+49+ class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():47- return TaskBase.__call__(self, *args, **kwargs)52+ return self.run(*args, **kwargs)53+54 celery.Task = ContextTask55 return celery56 57 The function creates a new Celery object, configures it with the broker58 from the application config, updates the rest of the Celery config from59 the Flask config and then creates a subclass of the task that wraps the60 task execution in an application context.61 56-Minimal Example62+An example task63 ---------------64 59-With what we have above this is the minimal example of using Celery with60-Flask::65+Let's write a task that adds two numbers together and returns the result. We66+configure Celery's broker and backend to use Redis, create a ``celery``67+application using the factor from above, and then use it to define the task. ::68 69 from flask import Flask70 71 flask_app = Flask(__name__)2 unmodified lines74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)77 71-78 @celery.task()79 def add_together(a, b):80 return a + b81 76-This task can now be called in the background:82+This task can now be called in the background::83 78->>> result = add_together.delay(23, 42)79->>> result.wait()80-6584+ result = add_together.delay(23, 42)85+ result.wait() # 6586 82-Running the Celery Worker83--------------------------87+Run a worker88+------------89 85-Now if you jumped in and already executed the above code you will be86-disappointed to learn that your ``.wait()`` will never actually return.87-That's because you also need to run celery. You can do that by running88-celery as a worker::90+If you jumped in and already executed the above code you will be91+disappointed to learn that ``.wait()`` will never actually return.92+That's because you also need to run a Celery worker to receive and execute the93+task. ::94 95 $ celery -A your_application.celery worker96 97 The ``your_application`` string has to point to your application's package93-or module that creates the `celery` object.98+or module that creates the ``celery`` object.99+100+Now that the worker is running, ``wait`` will return the result once the task101+is finished.modified:docs/patterns/deferredcallbacks.rst+24 added-52 removed
1 unmodified line2 3 Deferred Request Callbacks4 ==========================5 6-One of the design principles of Flask is that response objects are created7-and passed down a chain of potential callbacks that can modify them or8-replace them. When the request handling starts, there is no response9-object yet. It is created as necessary either by a view function or by10-some other component in the system.6+One of the design principles of Flask is that response objects are created and7+passed down a chain of potential callbacks that can modify them or replace8+them. When the request handling starts, there is no response object yet. It is9+created as necessary either by a view function or by some other component in10+the system.11 12-But what happens if you want to modify the response at a point where the13-response does not exist yet? A common example for that would be a14-before-request function that wants to set a cookie on the response object.12+What happens if you want to modify the response at a point where the response13+does not exist yet? A common example for that would be a14+:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15+response object.16 16-One way is to avoid the situation. Very often that is possible. For17-instance you can try to move that logic into an after-request callback18-instead. Sometimes however moving that code there is just not a very19-pleasant experience or makes code look very awkward.17+One way is to avoid the situation. Very often that is possible. For instance18+you can try to move that logic into a :meth:`~flask.Flask.after_request`19+callback instead. However, sometimes moving code there makes it more20+more complicated or awkward to reason about.21 21-As an alternative possibility you can attach a bunch of callback functions22-to the :data:`~flask.g` object and call them at the end of the request.23-This way you can defer code execution from anywhere in the application.22+As an alternative, you can use :func:`~flask.after_this_request` to register23+callbacks that will execute after only the current request. This way you can24+defer code execution from anywhere in the application, based on the current25+request.26 25-26-The Decorator27--------------28-29-The following decorator is the key. It registers a function on a list on30-the :data:`~flask.g` object::31-32- from flask import g33-34- def after_this_request(f):35- if not hasattr(g, 'after_request_callbacks'):36- g.after_request_callbacks = []37- g.after_request_callbacks.append(f)38- return f39-40-41-Calling the Deferred42---------------------43-44-Now you can use the `after_this_request` decorator to mark a function to45-be called at the end of the request. But we still need to call them. For46-this the following function needs to be registered as47-:meth:`~flask.Flask.after_request` callback::48-49- @app.after_request50- def call_after_request_callbacks(response):51- for callback in getattr(g, 'after_request_callbacks', ()):52- callback(response)53- return response54-55-56-A Practical Example57--------------------58-27 At any time during a request, we can register a function to be called at the60-end of the request. For example you can remember the current language of the61-user in a cookie in the before-request function::28+end of the request. For example you can remember the current language of the29+user in a cookie in a :meth:`~flask.Flask.before_request` callback::30 63- from flask import request31+ from flask import request, after_this_request32 33 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')36+37 if language is None:38 language = guess_language_from_request()39+40+ # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)44+45 g.language = languagemodified:docs/patterns/errorpages.rst+35 added-19 removed
45 unmodified lines46 47 Error Handlers48 --------------49 50-An error handler is a function, just like a view function, but it is51-called when an error happens and is passed that error. The error is most52-likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it53-can be a different error: a handler for internal server errors will be54-passed other exception instances as well if they are uncaught.50+An error handler is a function that returns a response when a type of error is51+raised, similar to how a view is a function that returns a response when a52+request URL is matched. It is passed the instance of the error being handled,53+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54+handler for "500 Internal Server Error" will be passed uncaught exceptions in55+addition to explicit 500 errors.56 57 An error handler is registered with the :meth:`~flask.Flask.errorhandler`57-decorator and the error code of the exception. Keep in mind that Flask58-will *not* set the error code for you, so make sure to also provide the59-HTTP status code when returning a response.58+decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59+can be registered for a status code, like 404, or for an exception class.60 61-Please note that if you add an error handler for "500 Internal Server62-Error", Flask will not trigger it if it's running in Debug mode.61+The status code of the response will not be set to the handler's code. Make62+sure to provide the appropriate HTTP status code when returning a response from63+a handler.64 64-Here an example implementation for a "404 Page Not Found" exception::65+A handler for "500 Internal Server Error" will not be used when running in66+debug mode. Instead, the interactive debugger will be shown.67 68+Here is an example implementation for a "404 Page Not Found" exception::69+70 from flask import render_template71 72 @app.errorhandler(404)73 def page_not_found(e):74+ # note that we set the 404 status explicitly75 return render_template('404.html'), 40476 77+When using the :ref:`application factory pattern <app-factories>`::78+79+ from flask import Flask, render_template80+81+ def page_not_found(e):82+ return render_template('404.html'), 40483+84+ def create_app(config_filename):85+ app = Flask(__name__)86+ app.register_error_handler(404, page_not_found)87+ return app88+89 An example template might be this:90 91 .. sourcecode:: html+jinja92 76- {% extends "layout.html" %}77- {% block title %}Page Not Found{% endblock %}78- {% block body %}79- <h1>Page Not Found</h1>80- <p>What you were looking for is just not there.81- <p><a href="{{ url_for('index') }}">go somewhere nice</a>82- {% endblock %}83-93+ {% extends "layout.html" %}94+ {% block title %}Page Not Found{% endblock %}95+ {% block body %}96+ <h1>Page Not Found</h1>97+ <p>What you were looking for is just not there.98+ <p><a href="{{ url_for('index') }}">go somewhere nice</a>99+ {% endblock %}modified:docs/patterns/fileuploads.rst+1 added-1 removed
19 unmodified lines20 specific upload folder and displays a file to the user. Let's look at the21 bootstrapping code for our application::22 23 import os24- from flask import Flask, request, redirect, url_for24+ from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename26 27 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])156 unmodified linesmodified:docs/patterns/packages.rst+1 added-1 removed
63 unmodified lines64 65 export FLASK_APP=yourapplication66 67 If you are outside of the project directory make sure to provide the exact 68-path to your application directory. Similiarly you can turn on "debug 68+path to your application directory. Similarly you can turn on "debug 69 mode" with this environment variable:: 70 71 export FLASK_DEBUG=true 72 73 unmodified linesmodified:docs/tutorial/dbcon.rst+3 added
1 unmodified line2 3 Step 4: Database Connections4 ----------------------------5 6+Let's continue building our code in the ``flaskr.py`` file.7+(Scroll to the end of the page for more about project layout.)8+9 You currently have a function for establishing a database connection with10 `connect_db`, but by itself, it is not particularly useful. Creating and11 closing database connections all the time is very inefficient, so you will12 need to keep it around for longer. Because database connections66 unmodified linesmodified:docs/tutorial/dbinit.rst+19 added-12 removed
7 unmodified lines8 systems need a schema that tells them how to store that information.9 Before starting the server for the first time, it's important to create10 that schema.11 12-Such a schema can be created by piping the ``schema.sql`` file into the13-`sqlite3` command as follows::12+Such a schema could be created by piping the ``schema.sql`` file into the13+``sqlite3`` command as follows::14 15 sqlite3 /tmp/flaskr.db < schema.sql16 17-The downside of this is that it requires the ``sqlite3`` command to be18-installed, which is not necessarily the case on every system. This also19-requires that you provide the path to the database, which can introduce20-errors. It's a good idea to add a function that initializes the database21-for you, to the application.17+However, the downside of this is that it requires the ``sqlite3`` command18+to be installed, which is not necessarily the case on every system. This19+also requires that you provide the path to the database, which can introduce20+errors.21 23-To do this, you can create a function and hook it into a :command:`flask`24-command that initializes the database. For now just take a look at the25-code segment below. A good place to add this function, and command, is26-just below the `connect_db` function in :file:`flaskr.py`::22+Instead of the ``sqlite3`` command above, it's a good idea to add a function23+to our application that initializes the database for you. To do this, you24+can create a function and hook it into a :command:`flask` command that25+initializes the database.26 27+Take a look at the code segment below. A good place to add this function,28+and command, is just below the ``connect_db`` function in :file:`flaskr.py`::29+30 def init_db():31 db = get_db()32+33 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())35+36 db.commit()37 38+39 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""42+43 init_db()44 print('Initialized the database.')45 46 The ``app.cli.command()`` decorator registers a new command with the17 unmodified lines64 On that cursor, there is a method to execute a complete script. Finally, you65 only have to commit the changes. SQLite3 and other transactional66 databases will not commit unless you explicitly tell it to.67 68+Now, in a terminal, from the application root directory :file:`flaskr/` it is62-Now, it is possible to create a database with the :command:`flask` script::69+possible to create a database with the :command:`flask` script::70 71 flask initdb72 Initialized the database.73 7 unmodified linesmodified:docs/tutorial/folders.rst+9 added-5 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before getting started, you will need to create the folders needed for this7-application::6+It is recommended to install your Flask application within a virtualenv. Please7+read the :ref:`installation` section to set up your environment.8 9+Now that you have installed Flask, you will need to create the folders required10+for this tutorial. Your directory structure will look like this::11+12 /flaskr13 /flaskr14 /static15 /templates16 17 The application will be installed and run as Python package. This is the18 recommended way to install and run Flask applications. You will see exactly16-how to run ``flaskr`` later on in this tutorial. For now go ahead and create17-the applications directory structure. In the next few steps you will be18-creating the database schema as well as the main module.19+how to run ``flaskr`` later on in this tutorial.20 21+For now go ahead and create the applications directory structure. In the next22+few steps you will be creating the database schema as well as the main module.23+24 As a quick side note, the files inside of the :file:`static` folder are25 available to users of the application via HTTP. This is the place where CSS and26 JavaScript files go. Inside the :file:`templates` folder, Flask will look for27 `Jinja2`_ templates. You will see examples of this later on.4 unmodified linesmodified:docs/tutorial/index.rst+9 added-9 removed
1 unmodified line2 3 Tutorial4 ========5 6-You want to develop an application with Python and Flask? Here you have7-the chance to learn by example. In this tutorial, we will create a simple8-microblogging application. It only supports one user that can create9-text-only entries and there are no feeds or comments, but it still10-features everything you need to get started. We will use Flask and SQLite11-as a database (which comes out of the box with Python) so there is nothing12-else you need.6+Learn by example to develop an application with Python and Flask.7 8+In this tutorial, we will create a simple blogging application. It only9+supports one user, only allows text entries, and has no feeds or comments.10+11+While very simple, this example still features everything you need to get12+started. In addition to Flask, we will use SQLite for the database, which is13+built-in to Python, so there is nothing else you need.14+15 If you want the full source code in advance or for comparison, check out16 the `example source`_.17 17-.. _example source:18- https://github.com/pallets/flask/tree/master/examples/flaskr/18+.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/19 20 .. toctree::21 :maxdepth: 222 11 unmodified linesmodified:docs/tutorial/introduction.rst+1 added-1 removed
20 unmodified lines21 connections in a more intelligent way, allowing you to target different22 relational databases at once and more. You might also want to consider23 one of the popular NoSQL databases if your data is more suited for those.24 25-Here a screenshot of the final application:25+Here is a screenshot of the final application:26 27 .. image:: ../_static/flaskr.png28 :align: center29 :class: screenshot5 unmodified linesmodified:docs/tutorial/packaging.rst+24 added-26 removed
7 unmodified lines8 tutorial you will see exactly how to extend the ``flask`` command line9 interface (CLI).10 11 A useful pattern to manage a Flask application is to install your app12-following the `Python Packaging Guide`_. Presently this involves 13-creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14-projects root directory. You also need to add an :file:`__init__.py` 15-file to make the :file:`flaskr/flaskr` directory a package. After these 12+following the `Python Packaging Guide`_. Presently this involves13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14+projects root directory. You also need to add an :file:`__init__.py`15+file to make the :file:`flaskr/flaskr` directory a package. After these16 changes, your code structure should be::17 18 /flaskr19 /flaskr4 unmodified lines24 schema.sql25 setup.py26 MANIFEST.in27 28-The content of the ``setup.py`` file for ``flaskr`` is:28+Create the ``setup.py`` file for ``flaskr`` with the following content::29 30-.. sourcecode:: python31-30 from setuptools import setup31 32 setup(33 name='flaskr',6 unmodified lines40 41 When using setuptools, it is also necessary to specify any special files42 that should be included in your package (in the :file:`MANIFEST.in`).43 In this case, the static and templates directories need to be included,46-as well as the schema. Create the :file:`MANIFEST.in` and add the47-following lines::44+as well as the schema.45 46+Create the :file:`MANIFEST.in` and add the following lines::47+48 graft flaskr/templates49 graft flaskr/static50 include flaskr/schema.sql51 53-To simplify locating the application, add the following import statement 54-into this file, :file:`flaskr/__init__.py`:52+Next, to simplify locating the application, create the file,53+:file:`flaskr/__init__.py` containing only the following import statement::54 56-.. sourcecode:: python57-55 from .flaskr import app56 60-This import statement brings the application instance into the top-level 61-of the application package. When it is time to run the application, the 62-Flask development server needs the location of the app instance. This 63-import statement simplifies the location process. Without it the export 64-statement a few steps below would need to be 57+This import statement brings the application instance into the top-level58+of the application package. When it is time to run the application, the59+Flask development server needs the location of the app instance. This60+import statement simplifies the location process. Without the above61+import statement, the export statement a few steps below would need to be62 ``export FLASK_APP=flaskr.flaskr``.63 64 At this point you should be able to install the application. As usual, it65 is recommended to install your Flask application within a `virtualenv`_.69-With that said, go ahead and install the application with::66+With that said, from the ``flaskr/`` directory, go ahead and install the67+application with::68 69 pip install --editable .70 73-The above installation command assumes that it is run within the projects 74-root directory, `flaskr/`. The `editable` flag allows editing 75-source code without having to reinstall the Flask app each time you make 76-changes. The flaskr app is now installed in your virtualenv (see output 71+The above installation command assumes that it is run within the projects72+root directory, ``flaskr/``. The ``editable`` flag allows editing73+source code without having to reinstall the Flask app each time you make74+changes. The flaskr app is now installed in your virtualenv (see output75 of ``pip freeze``).76 77 With that out of the way, you should be able to start up the application.80-Do this with the following commands::78+Do this on Mac or Linux with the following commands in ``flaskr/``::79 80 export FLASK_APP=flaskr81 export FLASK_DEBUG=true82 flask run83 86-(In case you are on Windows you need to use `set` instead of `export`).84+(In case you are on Windows you need to use ``set`` instead of ``export``).85 The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.86 *Never leave debug mode activated in a production system*, because it will87 allow users to execute code on the server!88 89 You will see a message telling you that server has started along with92-the address at which you can access it.90+the address at which you can access it in a browser.91 92 When you head over to the server in your browser, you will get a 404 error93 because we don't have any views yet. That will be addressed a little later,94 but first, you should get the database working.12 unmodified linesmodified:docs/tutorial/setup.rst+35 added-31 removed
1 unmodified line2 3 Step 2: Application Setup Code4 ==============================5 6-Now that the schema is in place, you can create the application module,7-:file:`flaskr.py`. This file should be placed inside of the8-:file:`flaskr/flaskr` folder. The first several lines of code in the9-application module are the needed import statements. After that there will be a10-few lines of configuration code. For small applications like ``flaskr``, it is11-possible to drop the configuration directly into the module. However, a cleaner12-solution is to create a separate ``.ini`` or ``.py`` file, load that, and13-import the values from there.6+Next, we will create the application module, :file:`flaskr.py`. Just like the7+:file:`schema.sql` file you created in the previous step, this file should be8+placed inside of the :file:`flaskr/flaskr` folder.9 10+For this tutorial, all the Python code we use will be put into this file11+(except for one line in ``__init__.py``, and any testing or optional files you12+decide to create).13+14+The first several lines of code in the application module are the needed import15+statements. After that there will be a few lines of configuration code.16+17+For small applications like ``flaskr``, it is possible to drop the configuration18+directly into the module. However, a cleaner solution is to create a separate19+``.py`` file, load that, and import the values from there.20+21 Here are the import statements (in :file:`flaskr.py`)::22 17- # all the imports23 import os24 import sqlite320- from flask import Flask, request, session, g, redirect, url_for, abort, \21- render_template, flash25 26+ from flask import (Flask, request, session, g, redirect, url_for, abort,27+ render_template, flash)28+29 The next couple lines will create the actual application instance and24-initialize it with the config from the same file in :file:`flaskr.py`:30+initialize it with the config from the same file in :file:`flaskr.py`::31 26-.. sourcecode:: python27-32 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py34 35 # Load default config and override config from an environment variable4 unmodified lines40 PASSWORD='default'41 ))42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)43 40-The :class:`~flask.Config` object works similarly to a dictionary, so it can be41-updated with new values.44+In the above code, the :class:`~flask.Config` object works similarly to a45+dictionary, so it can be updated with new values.46 47 .. admonition:: Database Path48 49 Operating systems know the concept of a current working directory for11 unmodified lines61 62 Usually, it is a good idea to load a separate, environment-specific63 configuration file. Flask allows you to import multiple configurations and it64 will use the setting defined in the last import. This enables robust61-configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.65+configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66+this. ::67 63-.. sourcecode:: python64-68 app.config.from_envvar('FLASKR_SETTINGS', silent=True)69 67-Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to68-a config file to be loaded. The silent switch just tells Flask to not complain69-if no such environment key is set.70+If you want to do this (not required for this tutorial) simply define the71+environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72+to be loaded. The silent switch just tells Flask to not complain if no such73+environment key is set.74 75 In addition to that, you can use the :meth:`~flask.Config.from_object`76 method on the config object and provide it with an import name of a77 module. Flask will then initialize the variable from that module. Note1 unmodified line79 80 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.81 Choose that key wisely and as hard to guess and complex as possible.82 79-Lastly, you will add a method that allows for easy connections to the80-specified database. This can be used to open a connection on request and81-also from the interactive Python shell or a script. This will come in82-handy later. You can create a simple database connection through SQLite and83-then tell it to use the :class:`sqlite3.Row` object to represent rows.84-This allows the rows to be treated as if they were dictionaries instead of85-tuples.83+Lastly, add a method that allows for easy connections to the specified84+database. ::85 87-.. sourcecode:: python88-86 def connect_db():87 """Connects to the specific database."""88+89 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv92 93+This can be used to open a connection on request and also from the94+interactive Python shell or a script. This will come in handy later.95+You can create a simple database connection through SQLite and then tell96+it to use the :class:`sqlite3.Row` object to represent rows. This allows97+the rows to be treated as if they were dictionaries instead of tuples.98+99 In the next section you will see how to run the application.100 101 Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+2 added-1 removed
13 unmodified lines14 15 We are also using template inheritance which makes it possible to reuse16 the layout of the website in all pages.17 18-Put the following templates into the :file:`templates` folder:18+Create the follwing three HTML files and place them in the19+:file:`templates` folder:20 21 .. _Jinja2: http://jinja.pocoo.org/docs/templates22 23 layout.html90 unmodified linesmodified:docs/tutorial/views.rst+2 added-1 removed
2 unmodified lines3 Step 6: The View Functions4 ==========================5 6 Now that the database connections are working, you can start writing the7-view functions. You will need four of them:7+view functions. You will need four of them; Show Entries, Add New Entry,8+Login and Logout. Add the following code snipets to :file:`flaskr.py`.9 10 Show Entries11 ------------12 106 unmodified linesdeleted:docs/_themesnot shown
Its text is not shown, deleted.
modified:docs/blueprints.rst+23 added-5 removed
175 unmodified lines176 177 admin = Blueprint('admin', __name__, template_folder='templates')178 179 For static files, the path can be absolute or relative to the blueprint180-resource folder. 180+resource folder.181 182-The template folder is added to the search path of templates but with a lower 183-priority than the actual application's template folder. That way you can 184-easily override templates that a blueprint provides in the actual application. 182+The template folder is added to the search path of templates but with a lower183+priority than the actual application's template folder. That way you can184+easily override templates that a blueprint provides in the actual application.185 This also means that if you don't want a blueprint template to be accidentally186 overridden, make sure that no other blueprint or actual application template187 has the same relative path. When multiple blueprints provide the same relative188 template path the first blueprint registered takes precedence over the others.4 unmodified lines193 ``templates`` as a `template_folder` you will have to create a file like194 this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195 for the extra ``admin`` folder is to avoid getting our template overridden196 by a template named ``index.html`` in the actual application template197-folder. 197+folder.198 199 To further reiterate this: if you have a blueprint named ``admin`` and you200 want to render a template called :file:`index.html` which is specific to this201 blueprint, the best idea is to lay out your templates like this::42 unmodified lines244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247 248+Most errorhandlers will simply work as expected; however, there is a caveat249+concerning handlers for 404 and 405 exceptions. These errorhandlers are only250+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252+access. This is because the blueprint does not "own" a certain URL space, so253+the application instance has no way of knowing which blueprint errorhandler it254+should run if given an invalid URL. If you would like to execute different255+handling strategies for these errors based on URL prefixes, they may be defined256+at the application level using the ``request`` proxy object::257+258+ @app.errorhandler(404)259+ @app.errorhandler(405)260+ def _handle_api_error(ex):261+ if request.path.startswith('/api/'):262+ return jsonify_error(ex)263+ else:264+ return ex265+266 More information on error handling see :ref:`errorpages`.modified:docs/cli.rst+55 added
54 unmodified lines55 ``export FLASK_APP`` into your ``activate`` script by adding it to the56 bottom of the file. That way every time you activate your virtualenv you57 automatically also activate the correct application name.58 59+Edit the activate script for the shell you use. For example:60+61+Unix Bash: ``venv/bin/activate``::62+63+ FLASK_APP=hello64+ export FLASK_APP65+66+Windows CMD.exe: ``venv\Scripts\activate.bat``::67+68+ set "FLASK_APP=hello"69+ :END70+71 Debug Flag72 ----------73 74 The :command:`flask` script can also be instructed to enable the debug182 unmodified lines257 258 Once that package is installed in the same virtualenv as Flask itself you259 can run ``flask my-command`` to invoke your command. This is useful to260 provide extra functionality that Flask itself cannot ship.261+262+PyCharm Integration263+-------------------264+265+The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,266+so we have to do a few tweaks to get them working smoothly.267+268+In your PyCharm application, with your project open, click on *Run*269+from the menu bar and go to *Edit Configurations*. You’ll be greeted by a270+screen similar to this:271+272+.. image:: _static/pycharm-runconfig.png273+ :align: center274+ :class: screenshot275+ :alt: screenshot of pycharm's run configuration settings276+277+There’s quite a few options to change, but don’t worry— once we’ve done it278+for one command, we can easily copy the entire configuration and make a279+single tweak to give us access to other flask cli commands, including280+any custom ones you may implement yourself.281+282+For the *Script* input (**A**), we want to navigate to the virtual environment283+we’re using for our project and within that folder we want to pick the ``flask``284+file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if285+you're on Windows.286+287+The *Script Parameter* field (**B**) is set to the cli command you wish to288+execute, in this example we use ``run`` which will run our development server.289+290+We need to add an environment variable (**C**) to identify our application.291+Click on the browse button and add an entry with ``FLASK_APP`` on the292+left and the name of the python file, or package on the right293+(``app.py`` for example).294+295+Next we need to set the working directory (**D**) to be the same folder where296+our application file or package resides.297+298+Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a299+good descriptive name, such as “Run Flask Server” and click *Apply*.300+301+Now that we have on run configuration which implements ``flask run`` from within302+PyCharm, we can simply copy that configuration and alter the script argument303+to run a different cli command, e.g. ``flask shell``.modified:docs/conf.py+12 added-17 removed
20 unmodified lines21 22 # If extensions (or modules to document with autodoc) are in another directory,23 # add these directories to sys.path here. If the directory is relative to the24 # documentation root, use os.path.abspath to make it absolute, like shown here.25-sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))25 sys.path.append(os.path.dirname(__file__))26 27 # -- General configuration -----------------------------------------------------28 7 unmodified lines36 'sphinx.ext.intersphinx',37 'flaskdocext'38 ]39 40+try:41+ __import__('sphinxcontrib.log_cabinet')42+except ImportError:43+ print('sphinxcontrib-log-cabinet is not installed.')44+ print('Changelog directives will not be re-organized.')45+else:46+ extensions.append('sphinxcontrib.log_cabinet')47+48 # Add any paths that contain templates here, relative to this directory.49 templates_path = ['_templates']50 51 # The suffix of source filenames.67 unmodified lines119 # documentation.120 # html_theme_options = {}121 122 # Add any paths that contain custom themes here, relative to this directory.116-html_theme_path = ['_themes']123+# html_theme_path = ['_themes']124 125 # The name for this set of Sphinx documents. If None, it defaults to126 # "<project> v<release> documentation".127 #html_title = None143 unmodified lines271 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),272 'blinker': ('https://pythonhosted.org/blinker/', None)273 }274 268-try:269- __import__('flask_theme_support')270- pygments_style = 'flask_theme_support.FlaskyStyle'271- html_theme = 'flask'272- html_theme_options = {273- 'touch_icon': 'touch-icon.png'274- }275+html_theme_options = {276+ 'touch_icon': 'touch-icon.png'277+}275-except ImportError:276- print('-' * 74)277- print('Warning: Flask themes unavailable. Building with default theme')278- print('If you want the Flask themes, run this command and build again:')279- print()280- print(' git submodule update --init')281- print('-' * 74)278 283-279 # unwrap decorators280 def unwrap_decorators():281 import sphinx.util.inspect as inspect282 import functools15 unmodified linesmodified:docs/config.rst+7 added-7 removed
130 unmodified lines131 help. Setting a ``SERVER_NAME`` also132 by default enables URL generation133 without a request context but with an134 application context.135-``APPLICATION_ROOT`` If the application does not occupy136- a whole domain or subdomain this can137- be set to the path where the application138- is configured to live. This is for139- session cookie as path value. If140- domains are used, this should be141- ``None``.135+``APPLICATION_ROOT`` The path value used for the session136+ cookie if ``SESSION_COOKIE_PATH`` isn't137+ set. If it's also ``None`` ``'/'`` is used.138+ Note that to actually serve your Flask139+ app under a subpath you need to tell140+ your WSGI container the ``SCRIPT_NAME``141+ WSGI environment variable.142 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will143 reject incoming requests with a144 content length greater than this by145 returning a 413 status code.334 unmodified linesmodified:docs/extensiondev.rst+16 added-16 removed
40 unmodified lines41 that people can easily install the development version into their42 virtualenv without having to download the library by hand.43 44 Flask extensions must be licensed under a BSD, MIT or more liberal license45-to be able to be enlisted in the Flask Extension Registry. Keep in mind45+in order to be listed in the Flask Extension Registry. Keep in mind46 that the Flask Extension Registry is a moderated place and libraries will47 be reviewed upfront if they behave as required.48 49 "Hello Flaskext!"97 unmodified lines147 What to use depends on what you have in mind. For the SQLite 3 extension148 we will use the class-based approach because it will provide users with an149 object that handles opening and closing database connections.150 151-What's important about classes is that they encourage to be shared around152-on module level. In that case, the object itself must not under any151+When designing your classes, it's important to make them easily reusable152+at the module level. This means the object itself must not under any153 circumstances store any application specific state and must be shareable154-between different application.154+between different applications.155 156 The Extension Code157 ------------------158 168 unmodified lines327 development. If you want to learn more, it's a very good idea to check328 out existing extensions on the `Flask Extension Registry`_. If you feel329 lost there is still the `mailinglist`_ and the `IRC channel`_ to get some330 ideas for nice looking APIs. Especially if you do something nobody before331-you did, it might be a very good idea to get some more input. This not332-only to get an idea about what people might want to have from an333-extension, but also to avoid having multiple developers working on pretty334-much the same side by side.331+you did, it might be a very good idea to get some more input. This not only332+generates useful feedback on what people might want from an extension, but333+also avoids having multiple developers working in isolation on pretty much the334+same problem.335 336 Remember: good API design is hard, so introduce your project on the337 mailinglist, and let other developers give you a helping hand with338 designing the API.24 unmodified lines363 test suite also has to be part of the distribution.364 3. APIs of approved extensions will be checked for the following365 characteristics:366 367- - an approved extension has to support multiple applications368- running in the same Python process.369- - it must be possible to use the factory pattern for creating370- applications.367+ - an approved extension has to support multiple applications368+ running in the same Python process.369+ - it must be possible to use the factory pattern for creating370+ applications.371 372 4. The license must be BSD/MIT/WTFPL licensed.373 5. The naming scheme for official extensions is *Flask-ExtensionName* or374 *ExtensionName-Flask*.5 unmodified lines380 8. The setup.py description (and thus the PyPI description) has to381 link to the documentation, website (if there is one) and there382 must be a link to automatically install the development version383 (``PackageName==dev``).384-9. The ``zip_safe`` flag in the setup script must be set to ``False``,385- even if the extension would be safe for zipping.386-10. An extension currently has to support Python 2.6 as well as387- Python 2.7384+9. The ``zip_safe`` flag in the setup script must be set to ``False``,385+ even if the extension would be safe for zipping.386+10. An extension currently has to support Python 2.7, Python 3.3 and higher.387 388 389+390 Extension Import Transition391 ---------------------------392 393 In early versions of Flask we recommended using namespace packages for Flask17 unmodified linesdeleted:docs/flaskext.py-86 removed
1-# flasky extensions. flasky pygments style based on tango style2-from pygments.style import Style3-from pygments.token import Keyword, Name, Comment, String, Error, \4- Number, Operator, Generic, Whitespace, Punctuation, Other, Literal5-6-7-class FlaskyStyle(Style):8- background_color = "#f8f8f8"9- default_style = ""10-11- styles = {12- # No corresponding class for the following:13- #Text: "", # class: ''14- Whitespace: "underline #f8f8f8", # class: 'w'15- Error: "#a40000 border:#ef2929", # class: 'err'16- Other: "#000000", # class 'x'17-18- Comment: "italic #8f5902", # class: 'c'19- Comment.Preproc: "noitalic", # class: 'cp'20-21- Keyword: "bold #004461", # class: 'k'22- Keyword.Constant: "bold #004461", # class: 'kc'23- Keyword.Declaration: "bold #004461", # class: 'kd'24- Keyword.Namespace: "bold #004461", # class: 'kn'25- Keyword.Pseudo: "bold #004461", # class: 'kp'26- Keyword.Reserved: "bold #004461", # class: 'kr'27- Keyword.Type: "bold #004461", # class: 'kt'28-29- Operator: "#582800", # class: 'o'30- Operator.Word: "bold #004461", # class: 'ow' - like keywords31-32- Punctuation: "bold #000000", # class: 'p'33-34- # because special names such as Name.Class, Name.Function, etc.35- # are not recognized as such later in the parsing, we choose them36- # to look the same as ordinary variables.37- Name: "#000000", # class: 'n'38- Name.Attribute: "#c4a000", # class: 'na' - to be revised39- Name.Builtin: "#004461", # class: 'nb'40- Name.Builtin.Pseudo: "#3465a4", # class: 'bp'41- Name.Class: "#000000", # class: 'nc' - to be revised42- Name.Constant: "#000000", # class: 'no' - to be revised43- Name.Decorator: "#888", # class: 'nd' - to be revised44- Name.Entity: "#ce5c00", # class: 'ni'45- Name.Exception: "bold #cc0000", # class: 'ne'46- Name.Function: "#000000", # class: 'nf'47- Name.Property: "#000000", # class: 'py'48- Name.Label: "#f57900", # class: 'nl'49- Name.Namespace: "#000000", # class: 'nn' - to be revised50- Name.Other: "#000000", # class: 'nx'51- Name.Tag: "bold #004461", # class: 'nt' - like a keyword52- Name.Variable: "#000000", # class: 'nv' - to be revised53- Name.Variable.Class: "#000000", # class: 'vc' - to be revised54- Name.Variable.Global: "#000000", # class: 'vg' - to be revised55- Name.Variable.Instance: "#000000", # class: 'vi' - to be revised56-57- Number: "#990000", # class: 'm'58-59- Literal: "#000000", # class: 'l'60- Literal.Date: "#000000", # class: 'ld'61-62- String: "#4e9a06", # class: 's'63- String.Backtick: "#4e9a06", # class: 'sb'64- String.Char: "#4e9a06", # class: 'sc'65- String.Doc: "italic #8f5902", # class: 'sd' - like a comment66- String.Double: "#4e9a06", # class: 's2'67- String.Escape: "#4e9a06", # class: 'se'68- String.Heredoc: "#4e9a06", # class: 'sh'69- String.Interpol: "#4e9a06", # class: 'si'70- String.Other: "#4e9a06", # class: 'sx'71- String.Regex: "#4e9a06", # class: 'sr'72- String.Single: "#4e9a06", # class: 's1'73- String.Symbol: "#4e9a06", # class: 'ss'74-75- Generic: "#000000", # class: 'g'76- Generic.Deleted: "#a40000", # class: 'gd'77- Generic.Emph: "italic #000000", # class: 'ge'78- Generic.Error: "#ef2929", # class: 'gr'79- Generic.Heading: "bold #000080", # class: 'gh'80- Generic.Inserted: "#00A000", # class: 'gi'81- Generic.Output: "#888", # class: 'go'82- Generic.Prompt: "#745334", # class: 'gp'83- Generic.Strong: "bold #000000", # class: 'gs'84- Generic.Subheading: "bold #800080", # class: 'gu'85- Generic.Traceback: "bold #a40000", # class: 'gt'86- }modified:docs/installation.rst+120 added-110 removed
1 unmodified line2 3 Installation4 ============5 6-Flask depends on some external libraries, like `Werkzeug7-<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/>`_.8-Werkzeug is a toolkit for WSGI, the standard Python interface between web9-applications and a variety of servers for both development and deployment.10-Jinja2 renders templates.6+Python Version7+--------------8 12-So how do you get all that on your computer quickly? There are many ways you13-could do that, but the most kick-ass method is virtualenv, so let's have a look14-at that first.9+We recommend using the latest version of Python 3. Flask supports Python 3.310+and newer, Python 2.6 and newer, and PyPy.11 16-You will need Python 2.6 or newer to get started, so be sure to have an17-up-to-date Python 2.x installation. For using Flask with Python 3 have a18-look at :ref:`python3-support`.12+Dependencies13+------------14 20-.. _virtualenv:15+These distributions will be installed automatically when installing Flask.16 22-virtualenv23-----------17+* `Werkzeug`_ implements WSGI, the standard Python interface between18+ applications and servers.19+* `Jinja`_ is a template language that renders the pages your application20+ serves.21+* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering22+ templates to avoid injection attacks.23+* `ItsDangerous`_ securely signs data to ensure its integrity. This is used24+ to protect Flask's session cookie.25+* `Click`_ is a framework for writing command line applications. It provides26+ the ``flask`` command and allows adding custom management commands.27 25-Virtualenv is probably what you want to use during development, and if you have26-shell access to your production machines, you'll probably want to use it there,27-too.28+.. _Werkzeug: http://werkzeug.pocoo.org/29+.. _Jinja: http://jinja.pocoo.org/30+.. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe31+.. _ItsDangerous: https://pythonhosted.org/itsdangerous/32+.. _Click: http://click.pocoo.org/33 29-What problem does virtualenv solve? If you like Python as much as I do,30-chances are you want to use it for other projects besides Flask-based web31-applications. But the more projects you have, the more likely it is that you32-will be working with different versions of Python itself, or at least different33-versions of Python libraries. Let's face it: quite often libraries break34-backwards compatibility, and it's unlikely that any serious application will35-have zero dependencies. So what do you do if two or more of your projects have36-conflicting dependencies?34+Optional dependencies35+~~~~~~~~~~~~~~~~~~~~~36 38-Virtualenv to the rescue! Virtualenv enables multiple side-by-side39-installations of Python, one for each project. It doesn't actually install40-separate copies of Python, but it does provide a clever way to keep different41-project environments isolated. Let's see how virtualenv works.37+These distributions will not be installed automatically. Flask will detect and38+use them if you install them.39 43-If you are on Mac OS X or Linux, chances are that the following44-command will work for you::40+* `Blinker`_ provides support for :ref:`signals`.41+* `SimpleJSON`_ is a fast JSON implementation that is compatible with42+ Python's ``json`` module. It is preferred for JSON operations if it is43+ installed.44 46- $ sudo pip install virtualenv45+.. _Blinker: https://pythonhosted.org/blinker/46+.. _SimpleJSON: https://simplejson.readthedocs.io/47 48-It will probably install virtualenv on your system. Maybe it's even49-in your package manager. If you use Ubuntu, try::48+Virtual environments49+--------------------50 51- $ sudo apt-get install python-virtualenv51+Use a virtual environment to manage the dependencies for your project, both in52+development and in production.53 53-If you are on Windows and don't have the ``easy_install`` command, you must54-install it first. Check the :ref:`windows-easy-install` section for more55-information about how to do that. Once you have it installed, run the same56-commands as above, but without the ``sudo`` prefix.54+What problem does a virtual environment solve? The more Python projects you55+have, the more likely it is that you need to work with different versions of56+Python libraries, or even Python itself. Newer versions of libraries for one57+project can break compatibility in another project.58 58-Once you have virtualenv installed, just fire up a shell and create59-your own environment. I usually create a project folder and a :file:`venv`60-folder within::59+Virtual environments are independent groups of Python libraries, one for each60+project. Packages installed for one project will not affect other projects or61+the operating system's packages.62 62- $ mkdir myproject63- $ cd myproject64- $ virtualenv venv65- New python executable in venv/bin/python66- Installing setuptools, pip............done.63+Python 3 comes bundled with the :mod:`venv` module to create virtual64+environments. If you're using a modern version of Python, you can continue on65+to the next section.66 68-Now, whenever you want to work on a project, you only have to activate the69-corresponding environment. On OS X and Linux, do the following::67+If you're using Python 2, see :ref:`install-install-virtualenv` first.68 71- $ . venv/bin/activate69+.. _install-create-env:70 73-If you are a Windows user, the following command is for you::71+Create an environment72+~~~~~~~~~~~~~~~~~~~~~73 75- $ venv\Scripts\activate74+Create a project folder and a :file:`venv` folder within:75 77-Either way, you should now be using your virtualenv (notice how the prompt of78-your shell has changed to show the active environment).76+.. code-block:: sh77 80-And if you want to go back to the real world, use the following command::78+ mkdir myproject79+ cd myproject80+ python3 -m venv venv81 82- $ deactivate82+On Windows:83 84-After doing this, the prompt of your shell should be as familiar as before.84+.. code-block:: bat85 86-Now, let's move on. Enter the following command to get Flask activated in your87-virtualenv::86+ py -3 -m venv venv87 89- $ pip install Flask88+If you needed to install virtualenv because you are on an older version of89+Python, use the following command instead:90 91-A few seconds later and you are good to go.91+.. code-block:: sh92 93+ virtualenv venv94 94-System-Wide Installation95-------------------------95+On Windows:96 97-This is possible as well, though I do not recommend it. Just run98-``pip`` with root privileges::97+.. code-block:: bat98 100- $ sudo pip install Flask99+ \Python27\Scripts\virtualenv.exe venv100 102-(On Windows systems, run it in a command-prompt window with administrator103-privileges, and leave out ``sudo``.)101+Activate the environment102+~~~~~~~~~~~~~~~~~~~~~~~~103 104+Before you work on your project, activate the corresponding environment:105 106-Living on the Edge107-------------------106+.. code-block:: sh107 109-If you want to work with the latest version of Flask, there are two ways: you110-can either let ``pip`` pull in the development version, or you can tell111-it to operate on a git checkout. Either way, virtualenv is recommended.108+ . venv/bin/activate109 113-Get the git checkout in a new virtualenv and run in development mode::110+On Windows:111 115- $ git clone https://github.com/pallets/flask.git116- Initialized empty Git repository in ~/dev/flask/.git/117- $ cd flask118- $ virtualenv venv119- New python executable in venv/bin/python120- Installing setuptools, pip............done.121- $ . venv/bin/activate122- $ python setup.py develop123- ...124- Finished processing dependencies for Flask112+.. code-block:: bat113 126-This will pull in the dependencies and activate the git head as the current127-version inside the virtualenv. Then all you have to do is run ``git pull128-origin`` to update to the latest version.114+ venv\Scripts\activate115 130-.. _windows-easy-install:116+Your shell prompt will change to show the name of the activated environment.117 132-`pip` and `setuptools` on Windows133----------------------------------118+Install Flask119+-------------120 135-Sometimes getting the standard "Python packaging tools" like ``pip``, ``setuptools``136-and ``virtualenv`` can be a little trickier, but nothing very hard. The crucial137-package you will need is pip - this will let you install138-anything else (like virtualenv). Fortunately there is a "bootstrap script"139-you can run to install.121+Within the activated environment, use the following command to install Flask:122 141-If you don't currently have ``pip``, then `get-pip.py` will install it for you.123+.. code-block:: sh124 143-`get-pip.py`_125+ pip install Flask126 145-It should be double-clickable once you download it. If you already have ``pip``,146-you can upgrade them by running::127+Living on the edge128+~~~~~~~~~~~~~~~~~~129 148- > pip install --upgrade pip setuptools130+If you want to work with the latest Flask code before it's released, install or131+update the code from the master branch:132 150-Most often, once you pull up a command prompt you want to be able to type ``pip``151-and ``python`` which will run those things, but this might not automatically happen152-on Windows, because it doesn't know where those executables are (give either a try!).133+.. code-block:: sh134 154-To fix this, you should be able to navigate to your Python install directory155-(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the156-:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and157-check that you can now just type ``python`` to bring up the interpreter.135+ pip install -U https://github.com/pallets/flask/archive/master.tar.gz136 159-Finally, to install `virtualenv`_, you can simply run::137+.. _install-install-virtualenv:138 161- > pip install virtualenv139+Install virtualenv140+------------------141 163-Then you can be off on your way following the installation instructions above.142+If you are using Python 2, the venv module is not available. Instead,143+install `virtualenv`_.144 145+On Linux, virtualenv is provided by your package manager:146+147+.. code-block:: sh148+149+ # Debian, Ubuntu150+ sudo apt-get install python-virtualenv151+152+ # CentOS, Fedora153+ sudo yum install python-virtualenv154+155+ # Arch156+ sudo pacman -S python-virtualenv157+158+If you are on Mac OS X or Windows, download `get-pip.py`_, then:159+160+.. code-block:: sh161+162+ sudo python2 Downloads/get-pip.py163+ sudo python2 -m pip install virtualenv164+165+On Windows, as an administrator:166+167+.. code-block:: bat168+169+ \Python27\python.exe Downloads\get-pip.py170+ \Python27\python.exe -m pip install virtualenv171+172+Now you can continue to :ref:`install-create-env`.173+174+.. _virtualenv: https://virtualenv.pypa.io/175 .. _get-pip.py: https://bootstrap.pypa.io/get-pip.pymodified:docs/quickstart.rst+107 added-151 removed
48 unmodified lines49 $ export FLASK_APP=hello.py50 $ flask run51 * Running on http://127.0.0.1:5000/52 53-If you are on Windows you need to use ``set`` instead of ``export``.53+If you are on Windows, the environment variable syntax depends on command line54+interpreter. On Command Prompt::55 56+ C:\path\to\app>set FLASK_APP=hello.py57+58+And on PowerShell::59+60+ PS C:\path\to\app> $env:FLASK_APP = "hello.py"61+62 Alternatively you can use :command:`python -m flask`::63 64 $ export FLASK_APP=hello.py65 $ python -m flask run93 unmodified lines159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162 163+More information on using the debugger can be found in the `Werkzeug 164+documentation`_.165+166+.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167+168 Have another debugger in mind? See :ref:`working-with-debuggers`.169 170 171 Routing172 -------173 162-Modern web applications have beautiful URLs. This helps people remember163-the URLs, which is especially handy for applications that are used from164-mobile devices with slower network connections. If the user can directly165-go to the desired page without having to hit the index page it is more166-likely they will like the page and come back next time.174+Modern web applications use meaningful URLs to help users. Users are more175+likely to like a page and come back if the page uses a meaningful URL they can176+remember and use to directly visit a page.177 168-As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169-bind a function to a URL. Here are some basic examples::178+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::179 180 @app.route('/')181 def index():182 return 'Index Page'1 unmodified line184 @app.route('/hello')185 def hello():186 return 'Hello, World'187 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.188+You can do more! You can make parts of the URL dynamic and attach multiple189+rules to a function.190 191 Variable Rules192 ``````````````193 185-To add variable parts to a URL you can mark these special sections as186-``<variable_name>``. Such a part is then passed as a keyword argument to your187-function. Optionally a converter can be used by specifying a rule with188-``<converter:variable_name>``. Here are some nice examples::194+You can add variable sections to a URL by marking sections with195+``<variable_name>``. Your function then receives the ``<variable_name>``196+as a keyword argument. Optionally, you can use a converter to specify the type197+of the argument like ``<converter:variable_name>``. ::198 199 @app.route('/user/<username>')200 def show_user_profile(username):201 # show the user profile for that user3 unmodified lines205 def show_post(post_id):206 # show the post with the given id, the id is an integer207 return 'Post %d' % post_id208 200-The following converters exist:209+ @app.route('/path/<path:subpath>')210+ def show_subpath(subpath):211+ # show the subpath after /path/212+ return 'Subpath %s' % subpath213 202-=========== ===============================================203-`string` accepts any text without a slash (the default)204-`int` accepts integers205-`float` like ``int`` but for floating point values206-`path` like the default but also accepts slashes207-`any` matches one of the items provided208-`uuid` accepts UUID strings209-=========== ===============================================214+Converter types:215 211-.. admonition:: Unique URLs / Redirection Behavior216+========== ==========================================217+``string`` (default) accepts any text without a slash218+``int`` accepts positive integers219+``float`` accepts positive floating point values220+``path`` like ``string`` but also accepts slashes221+``uuid`` accepts UUID strings222+========== ==========================================223 213- Flask's URL rules are based on Werkzeug's routing module. The idea214- behind that module is to ensure beautiful and unique URLs based on215- precedents laid down by Apache and earlier HTTP servers.224+Unique URLs / Redirection Behavior225+``````````````````````````````````226 217- Take these two rules::227+Take these two rules::228 219- @app.route('/projects/')220- def projects():221- return 'The project page'229+ @app.route('/projects/')230+ def projects():231+ return 'The project page'232 223- @app.route('/about')224- def about():225- return 'The about page'233+ @app.route('/about')234+ def about():235+ return 'The about page'236 227- Though they look rather similar, they differ in their use of the trailing228- slash in the URL *definition*. In the first case, the canonical URL for the229- ``projects`` endpoint has a trailing slash. In that sense, it is similar to230- a folder on a filesystem. Accessing it without a trailing slash will cause231- Flask to redirect to the canonical URL with the trailing slash.237+Though they look similar, they differ in their use of the trailing slash in238+the URL. In the first case, the canonical URL for the ``projects`` endpoint239+uses a trailing slash. It's similar to a folder in a file system; if you240+access the URL without a trailing slash, Flask redirects you to the241+canonical URL with the trailing slash.242 233- In the second case, however, the URL is defined without a trailing slash,234- rather like the pathname of a file on UNIX-like systems. Accessing the URL235- with a trailing slash will produce a 404 "Not Found" error.243+In the second case, however, the URL definition lacks a trailing slash,244+like the pathname of a file on UNIX-like systems. Accessing the URL with a245+trailing slash produces a 404 “Not Found” error.246 237- This behavior allows relative URLs to continue working even if the trailing238- slash is omitted, consistent with how Apache and other servers work. Also,239- the URLs will stay unique, which helps search engines avoid indexing the240- same page twice.247+This behavior allows relative URLs to continue working even if the trailing248+slash is omitted, consistent with how Apache and other servers work. Also,249+the URLs will stay unique, which helps search engines avoid indexing the250+same page twice.251 242-252 .. _url-building:253 254 URL Building255 ````````````256 248-If it can match URLs, can Flask also generate them? Of course it can. To249-build a URL to a specific function you can use the :func:`~flask.url_for`250-function. It accepts the name of the function as first argument and a number251-of keyword arguments, each corresponding to the variable part of the URL rule.252-Unknown variable parts are appended to the URL as query parameters. Here are253-some examples::257+To build a URL to a specific function, use the :func:`~flask.url_for` function.258+It accepts the name of the function as its first argument and any number of259+keyword arguments, each corresponding to a variable part of the URL rule.260+Unknown variable parts are appended to the URL as query parameters.261 255- >>> from flask import Flask, url_for256- >>> app = Flask(__name__)257- >>> @app.route('/')258- ... def index(): pass259- ...260- >>> @app.route('/login')261- ... def login(): pass262- ...263- >>> @app.route('/user/<username>')264- ... def profile(username): pass265- ...266- >>> with app.test_request_context():267- ... print(url_for('index'))268- ... print(url_for('login'))269- ... print(url_for('login', next='/'))270- ... print(url_for('profile', username='John Doe'))271- ...272- /273- /login274- /login?next=/275- /user/John%20Doe276-277-(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278-below. It tells Flask to behave as though it is handling a request, even279-though we are interacting with it through a Python shell. Have a look at the280-explanation below. :ref:`context-locals`).281-262 Why would you want to build URLs using the URL reversing function263 :func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:264 286-1. Reversing is often more descriptive than hard-coding the URLs. More287- importantly, it allows you to change URLs in one go, without having to288- remember to change URLs all over the place.289-2. URL building will handle escaping of special characters and Unicode290- data transparently for you, so you don't have to deal with them.291-3. If your application is placed outside the URL root - say, in292- ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle293- that properly for you.265+1. Reversing is often more descriptive than hard-coding the URLs.266+2. You can change your URLs in one go instead of needing to remember to267+ manually change hard-coded URLs.268+3. URL building handles escaping of special characters and Unicode data269+ transparently.270+4. If your application is placed outside the URL root, for example, in271+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly272+ handles that for you.273 274+For example, here we use the :meth:`~flask.Flask.test_request_context` method275+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`276+tells Flask to behave as though it's handling a request even while we use a277+Python shell. See :ref:`context-locals`. ::278 296-HTTP Methods297-````````````279+ from flask import Flask, url_for280 299-HTTP (the protocol web applications are speaking) knows different methods for300-accessing URLs. By default, a route only answers to ``GET`` requests, but that301-can be changed by providing the ``methods`` argument to the302-:meth:`~flask.Flask.route` decorator. Here are some examples::281+ app = Flask(__name__)282 304- from flask import request283+ @app.route('/')284+ def index():285+ return 'index'286 306- @app.route('/login', methods=['GET', 'POST'])287+ @app.route('/login')288 def login():308- if request.method == 'POST':309- return do_the_login()310- else:311- return show_the_login_form()289+ return 'login'290 313-If ``GET`` is present, ``HEAD`` will be added automatically for you. You314-don't have to deal with that. It will also make sure that ``HEAD`` requests315-are handled as the `HTTP RFC`_ (the document describing the HTTP316-protocol) demands, so you can completely ignore that part of the HTTP317-specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318-automatically as well.291+ @app.route('/user/<username>')292+ def profile(username):293+ return '{}'s profile'.format(username)294 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction to HTTP methods and why they matter:295+ with app.test_request_context():296+ print(url_for('index'))297+ print(url_for('login'))298+ print(url_for('login', next='/'))299+ print(url_for('profile', username='John Doe'))300 323-The HTTP method (also often called "the verb") tells the server what the324-client wants to *do* with the requested page. The following methods are325-very common:301+ /302+ /login303+ /login?next=/304+ /user/John%20Doe305 327-``GET``328- The browser tells the server to just *get* the information stored on329- that page and send it. This is probably the most common method.306+HTTP Methods307+````````````308 331-``HEAD``332- The browser tells the server to get the information, but it is only333- interested in the *headers*, not the content of the page. An334- application is supposed to handle that as if a ``GET`` request was335- received but to not deliver the actual content. In Flask you don't336- have to deal with that at all, the underlying Werkzeug library handles337- that for you.309+Web applications use different HTTP methods when accessing URLs. You should310+familiarize yourself with the HTTP methods as you work with Flask. By default,311+a route only answers to ``GET`` requests. You can use the ``methods`` argument312+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.313+::314 339-``POST``340- The browser tells the server that it wants to *post* some new341- information to that URL and that the server must ensure the data is342- stored and only stored once. This is how HTML forms usually343- transmit data to the server.315+ @app.route('/login', methods=['GET', 'POST'])316+ def login():317+ if request.method == 'POST':318+ do_the_login()319+ else:320+ show_the_login_form()321 345-``PUT``346- Similar to ``POST`` but the server might trigger the store procedure347- multiple times by overwriting the old values more than once. Now you348- might be asking why this is useful, but there are some good reasons349- to do it this way. Consider that the connection is lost during350- transmission: in this situation a system between the browser and the351- server might receive the request safely a second time without breaking352- things. With ``POST`` that would not be possible because it must only353- be triggered once.322+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method323+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,324+``OPTIONS`` is automatically implemented for you.325 355-``DELETE``356- Remove the information at the given location.357-358-``OPTIONS``359- Provides a quick way for a client to figure out which methods are360- supported by this URL. Starting with Flask 0.6, this is implemented361- for you automatically.362-363-Now the interesting part is that in HTML4 and XHTML1, the only methods a364-form can submit to the server are ``GET`` and ``POST``. But with JavaScript365-and future HTML standards you can use the other methods as well. Furthermore366-HTTP has become quite popular lately and browsers are no longer the only367-clients that are using HTTP. For instance, many revision control systems368-use it.369-326 .. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt327 328 Static Files329 ------------520 unmodified linesmodified:docs/reqcontext.rst+8 added-7 removed
117 unmodified lines118 unhandled exception down the road or if a before-request handler was119 not executed yet or at all (for example in test environments sometimes120 you might want to not execute before-request callbacks).121 122-Now what happens on errors? In production mode if an exception is not123-caught, the 500 internal server handler is called. In development mode124-however the exception is not further processed and bubbles up to the WSGI122+Now what happens on errors? If you are not in debug mode and an exception is not 123+caught, the 500 internal server handler is called. In debug mode 124+however the exception is not further processed and bubbles up to the WSGI 125 server. That way things like the interactive debugger can provide helpful126 debug information.127 128 An important change in 0.7 is that the internal server error is now no84 unmodified lines213 214 Starting with Flask 0.7 you have finer control over that behavior by215 setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216 default it's linked to the setting of ``DEBUG``. If the application is in217-debug mode the context is preserved, in production mode it's not.217+debug mode the context is preserved. If debug mode is set to off, the context218+is not preserved.219 219-Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode220-as it will cause your application to leak memory on exceptions. However220+Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221+as it will cause your application to leak memory on exceptions. However,222 it can be useful during development to get the same error preserving222-behavior as in development mode when attempting to debug an error that223+behavior as debug mode when attempting to debug an error that224 only occurs under production settings.modified:docs/signals.rst+2 added-2 removed
25 unmodified lines26 executed in undefined order and do not modify any data.27 28 The big advantage of signals over handlers is that you can safely29 subscribe to them for just a split second. These temporary30-subscriptions are helpful for unittesting for example. Say you want to30+subscriptions are helpful for unit testing for example. Say you want to31 know what templates were rendered as part of a request: signals allow you32 to do exactly that.33 34 Subscribing to Signals9 unmodified lines44 signal. When you subscribe to a signal, be sure to also provide a sender45 unless you really want to listen for signals from all applications. This is46 especially true if you are developing an extension.47 48-For example, here is a helper context manager that can be used in a unittest48+For example, here is a helper context manager that can be used in a unit test49 to determine which templates were rendered and what variables were passed50 to the template::51 52 from flask import template_rendered138 unmodified linesmodified:docs/testing.rst+112 added-90 removed
3 unmodified lines4 ==========================5 6 **Something that is untested is broken.**7 8-The origin of this quote is unknown and while it is not entirely correct, it is also9-not far from the truth. Untested applications make it hard to8+The origin of this quote is unknown and while it is not entirely correct, it9+is also not far from the truth. Untested applications make it hard to10 improve existing code and developers of untested applications tend to11 become pretty paranoid. If an application has automated tests, you can12 safely make changes and instantly know if anything breaks.13 14 Flask provides a way to test your application by exposing the Werkzeug15 test :class:`~werkzeug.test.Client` and handling the context locals for you.16-You can then use that with your favourite testing solution. In this documentation17-we will use the :mod:`unittest` package that comes pre-installed with Python.16+You can then use that with your favourite testing solution.17 18+In this documentation we will use the `pytest`_ package as the base19+framework for our tests. You can install it with ``pip``, like so::20+21+ pip install pytest22+23+.. _pytest:24+ https://pytest.org25+26 The Application27 ---------------28 29 First, we need an application to test; we will use the application from30 the :ref:`tutorial`. If you don't have that application yet, get the24-sources from `the examples`_.31+source code from `the examples`_.32 33 .. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/35 36 The Testing Skeleton37 --------------------38 32-In order to test the application, we add a second module33-(:file:`flaskr_tests.py`) and create a unittest skeleton there::39+We begin by adding a tests directory under the application root. Then40+create a Python file to store our tests (:file:`test_flaskr.py`). When we41+format the filename like ``test_*.py``, it will be auto-discoverable by42+pytest.43 44+Next, we create a `pytest fixture`_ called45+:func:`client` that configures46+the application for testing and initializes a new database.::47+48 import os36- import flaskr37- import unittest49 import tempfile50 40- class FlaskrTestCase(unittest.TestCase):51+ import pytest52 42- def setUp(self):43- self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44- flaskr.app.config['TESTING'] = True45- self.app = flaskr.app.test_client()46- with flaskr.app.app_context():47- flaskr.init_db()53+ from flaskr import flaskr54 49- def tearDown(self):50- os.close(self.db_fd)51- os.unlink(flaskr.app.config['DATABASE'])55 53- if __name__ == '__main__':54- unittest.main()56+ @pytest.fixture57+ def client():58+ db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59+ flaskr.app.config['TESTING'] = True60+ client = flaskr.app.test_client()61 56-The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57-client and initializes a new database. This function is called before58-each individual test function is run. To delete the database after the59-test, we close the file and remove it from the filesystem in the60-:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the61-``TESTING`` config flag is activated. What it does is disable the error62-catching during request handling so that you get better error reports when63-performing test requests against the application.62+ with flaskr.app.app_context():63+ flaskr.init_db()64 65-This test client will give us a simple interface to the application. We can66-trigger test requests to the application, and the client will also keep track67-of cookies for us.65+ yield client66 67+ os.close(db_fd)68+ os.unlink(flaskr.app.config['DATABASE'])69+70+This client fixture will be called by each individual test. It gives us a71+simple interface to the application, where we can trigger test requests to the72+application. The client will also keep track of cookies for us.73+74+During setup, the ``TESTING`` config flag is activated. What75+this does is disable error catching during request handling, so that76+you get better error reports when performing test requests against the77+application.78+69-Because SQLite3 is filesystem-based we can easily use the tempfile module79+Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80 to create a temporary database and initialize it. The81 :func:`~tempfile.mkstemp` function does two things for us: it returns a82 low-level file handle and a random file name, the latter we use as83 database name. We just have to keep the `db_fd` around so that we can use84 the :func:`os.close` function to close the file.85 86+To delete the database after the test, the fixture closes the file and removes87+it from the filesystem.88+89 If we now run the test suite, we should see the following output::90 78- $ python flaskr_tests.py91+ $ pytest92 80- ----------------------------------------------------------------------81- Ran 0 tests in 0.000s93+ ================ test session starts ================94+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg95+ collected 0 items96 83- OK97+ =========== no tests ran in 0.07 seconds ============98 85-Even though it did not run any actual tests, we already know that our flaskr99+Even though it did not run any actual tests, we already know that our ``flaskr``100 application is syntactically valid, otherwise the import would have died101 with an exception.102 103+.. _pytest fixture:104+ https://docs.pytest.org/en/latest/fixture.html105+106 The First Test107 --------------108 109 Now it's time to start testing the functionality of the application.110 Let's check that the application shows "No entries here so far" if we94-access the root of the application (``/``). To do this, we add a new95-test method to our class, like this::111+access the root of the application (``/``). To do this, we add a new112+test function to :file:`test_flaskr.py`, like this::113 97- class FlaskrTestCase(unittest.TestCase):114+ def test_empty_db(client):115+ """Start with a blank database."""116 99- def setUp(self):100- self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101- self.app = flaskr.app.test_client()102- flaskr.init_db()117+ rv = client.get('/')118+ assert b'No entries here so far' in rv.data119 104- def tearDown(self):105- os.close(self.db_fd)106- os.unlink(flaskr.app.config['DATABASE'])107-108- def test_empty_db(self):109- rv = self.app.get('/')110- assert b'No entries here so far' in rv.data111-120 Notice that our test functions begin with the word `test`; this allows113-:mod:`unittest` to automatically identify the method as a test to run.121+`pytest`_ to automatically identify the function as a test to run.122 115-By using `self.app.get` we can send an HTTP ``GET`` request to the application with123+By using ``client.get`` we can send an HTTP ``GET`` request to the application with124 the given path. The return value will be a :class:`~flask.Flask.response_class` object.125 We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126 the return value (as string) from the application. In this case, we ensure that127 ``'No entries here so far'`` is part of the output.128 129 Run it again and you should see one passing test::130 123- $ python flaskr_tests.py124- .125- ----------------------------------------------------------------------126- Ran 1 test in 0.034s131+ $ pytest -v132 128- OK133+ ================ test session starts ================134+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg135+ collected 1 items136 137+ tests/test_flaskr.py::test_empty_db PASSED138+139+ ============= 1 passed in 0.10 seconds ==============140+141 Logging In and Out142 ------------------143 144 The majority of the functionality of our application is only available for1 unmodified line146 of the application. To do this, we fire some requests to the login and logout147 pages with the required form data (username and password). And because the148 login and logout pages redirect, we tell the client to `follow_redirects`.149 139-Add the following two methods to your `FlaskrTestCase` class::150+Add the following two functions to your :file:`test_flaskr.py` file::151 141- def login(self, username, password):142- return self.app.post('/login', data=dict(143- username=username,144- password=password145- ), follow_redirects=True)152+ def login(client, username, password):153+ return client.post('/login', data=dict(154+ username=username,155+ password=password156+ ), follow_redirects=True)157 147- def logout(self):148- return self.app.get('/logout', follow_redirects=True)158 159+ def logout(client):160+ return client.get('/logout', follow_redirects=True)161+162 Now we can easily test that logging in and out works and that it fails with151-invalid credentials. Add this new test to the class::163+invalid credentials. Add this new test function::164 153- def test_login_logout(self):154- rv = self.login('admin', 'default')155- assert b'You were logged in' in rv.data156- rv = self.logout()157- assert b'You were logged out' in rv.data158- rv = self.login('adminx', 'default')159- assert b'Invalid username' in rv.data160- rv = self.login('admin', 'defaultx')161- assert b'Invalid password' in rv.data165+ def test_login_logout(client):166+ """Make sure login and logout works."""167 168+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])169+ assert b'You were logged in' in rv.data170+171+ rv = logout(client)172+ assert b'You were logged out' in rv.data173+174+ rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175+ assert b'Invalid username' in rv.data176+177+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178+ assert b'Invalid password' in rv.data179+180 Test Adding Messages181 --------------------182 166-We should also test that adding messages works. Add a new test method183+We should also test that adding messages works. Add a new test function184 like this::185 169- def test_messages(self):170- self.login('admin', 'default')171- rv = self.app.post('/add', data=dict(186+ def test_messages(client):187+ """Test that messages work."""188+189+ login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])190+ rv = client.post('/add', data=dict(191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)194 assert b'No entries here so far' not in rv.data4 unmodified lines199 which is the intended behavior.200 201 Running that should now give us three passing tests::202 184- $ python flaskr_tests.py185- ...186- ----------------------------------------------------------------------187- Ran 3 tests in 0.332s203+ $ pytest -v204 189- OK205+ ================ test session starts ================206+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg207+ collected 3 items208 209+ tests/test_flaskr.py::test_empty_db PASSED210+ tests/test_flaskr.py::test_login_logout PASSED211+ tests/test_flaskr.py::test_messages PASSED212+213+ ============= 3 passed in 0.23 seconds ==============214+215 For more complex tests with headers and status codes, check out the216 `MiniTwit Example`_ from the sources which contains a larger test217 suite.218 195-219 .. _MiniTwit Example:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221 199-222 Other Testing Tricks223 --------------------224 225 Besides using the test client as shown above, there is also the3 unmodified lines229 :class:`~flask.g` and :class:`~flask.session` objects like in view230 functions. Here is a full example that demonstrates this approach::231 232 import flask211- 233+234 app = flask.Flask(__name__)235 236 with app.test_request_context('/?name=Peter'):237 assert flask.request.path == '/'140 unmodified linesmodified:examples/minitwit/tests/test_minitwit.py+5 added-7 removed
13 unmodified lines14 from minitwit import minitwit15 16 17 @pytest.fixture18-def client(request):18+def client():19 db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20 client = minitwit.app.test_client()21 with minitwit.app.app_context():22 minitwit.init_db()23 24- def teardown():25- """Get rid of the database again after each test."""26- os.close(db_fd)27- os.unlink(minitwit.app.config['DATABASE'])28- request.addfinalizer(teardown)29- return client24+ yield client25 26+ os.close(db_fd)27+ os.unlink(minitwit.app.config['DATABASE'])28 29+30 def register(client, username, password, password2=None, email=None):31 """Helper function to register a user"""32 if password2 is None:33 password2 = password116 unmodified linesmodified:flask/_compat.py+2 added
23 unmodified lines24 iterkeys = lambda d: iter(d.keys())25 itervalues = lambda d: iter(d.values())26 iteritems = lambda d: iter(d.items())27 28+ from inspect import getfullargspec as getargspec29 from io import StringIO30 31 def reraise(tp, value, tb=None):32 if value.__traceback__ is not tb:10 unmodified lines43 iterkeys = lambda d: d.iterkeys()44 itervalues = lambda d: d.itervalues()45 iteritems = lambda d: d.iteritems()46 47+ from inspect import getargspec48 from cStringIO import StringIO49 50 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')51 47 unmodified linesmodified:flask/app.py+182 added-113 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13 from datetime import timedelta15-from itertools import chain14 from functools import update_wrapper15+from itertools import chain16+from threading import Lock17 18-from werkzeug.datastructures import ImmutableDict19-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError20-from werkzeug.exceptions import HTTPException, InternalServerError, \21- MethodNotAllowed, BadRequest, default_exceptions18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 23-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \24- locked_cached_property, _endpoint_from_view_func, find_package, \25- get_debug_flag26-from . import json, cli27-from .wrappers import Request, Response28-from .config import ConfigAttribute, Config29-from .ctx import RequestContext, AppContext, _AppCtxGlobals30-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \33- _default_template_ctx_processor34-from .signals import request_started, request_finished, got_request_exception, \35- request_tearing_down, appcontext_tearing_down36-from ._compat import reraise, string_types, text_type, integer_types35+ _default_template_ctx_processor36+from .wrappers import Request, Response37 38 # a lock used for logger initialization39 _logger_lock = Lock()40 81 unmodified lines122 123 .. versionadded:: 0.11124 The `root_path` parameter was added.125 126+ .. versionadded:: 0.13127+ The `host_matching` and `static_host` parameters were added.128+129 :param import_name: the name of the application package130 :param static_url_path: can be used to specify a different path for the131 static files on the web. Defaults to the name132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136+ :param host_matching: sets the app's ``url_map.host_matching`` to the given137+ given value. Defaults to False.138+ :param static_host: the host to use when adding the static route. Defaults139+ to None. Required when using ``host_matching=True``140+ with a ``static_folder`` configured.141 :param template_folder: the folder that contains the templates that should142 be used by the application. Defaults to143 ``'templates'`` folder in the root path of the144 application.74 unmodified lines219 debug = ConfigAttribute('DEBUG')220 221 #: The testing flag. Set this to ``True`` to enable the test mode of222 #: Flask extensions (and in the future probably also Flask itself).215- #: For example this might activate unittest helpers that have an223+ #: For example this might activate test helpers that have an224 #: additional runtime cost which should not be enabled by default.225 #:226 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the227 #: default it's implicitly enabled.116 unmodified lines344 #: .. versionadded:: 0.8345 session_interface = SecureCookieSessionInterface()346 347 def __init__(self, import_name, static_path=None, static_url_path=None,340- static_folder='static', template_folder='templates',348+ static_folder='static', static_host=None,349+ host_matching=False, template_folder='templates',350 instance_path=None, instance_relative_config=False,351 root_path=None):352 _PackageBoundObject.__init__(self, import_name,353 template_folder=template_folder,58 unmodified lines412 #:413 #: .. versionadded:: 0.9414 self.url_build_error_handlers = []415 407- #: A dictionary with lists of functions that should be called at the408- #: beginning of the request. The key of the dictionary is the name of409- #: the blueprint this function is active for, ``None`` for all requests.410- #: This can for example be used to open database connections or411- #: getting hold of the currently logged in user. To register a412- #: function here, use the :meth:`before_request` decorator.416+ #: A dictionary with lists of functions that will be called at the417+ #: beginning of each request. The key of the dictionary is the name of418+ #: the blueprint this function is active for, or ``None`` for all419+ #: requests. To register a function, use the :meth:`before_request`420+ #: decorator.421 self.before_request_funcs = {}422 415- #: A lists of functions that should be called at the beginning of the416- #: first request to this instance. To register a function here, use417- #: the :meth:`before_first_request` decorator.423+ #: A list of functions that will be called at the beginning of the424+ #: first request to this instance. To register a function, use the425+ #: :meth:`before_first_request` decorator.426 #:427 #: .. versionadded:: 0.8428 self.before_first_request_funcs = []429 23 unmodified lines453 #:454 #: .. versionadded:: 0.9455 self.teardown_appcontext_funcs = []456 449- #: A dictionary with lists of functions that can be used as URL450- #: value processor functions. Whenever a URL is built these functions451- #: are called to modify the dictionary of values in place. The key452- #: ``None`` here is used for application wide453- #: callbacks, otherwise the key is the name of the blueprint.454- #: Each of these functions has the chance to modify the dictionary457+ #: A dictionary with lists of functions that are called before the458+ #: :attr:`before_request_funcs` functions. The key of the dictionary is459+ #: the name of the blueprint this function is active for, or ``None``460+ #: for all requests. To register a function, use461+ #: :meth:`url_value_preprocessor`.462 #:463 #: .. versionadded:: 0.7464 self.url_value_preprocessors = {}465 65 unmodified lines531 #: app = Flask(__name__)532 #: app.url_map.converters['list'] = ListConverter533 self.url_map = Map()534 535+ self.url_map.host_matching = host_matching536+537 # tracks internally if the application already handled at least one538 # request.539 self._got_first_request = False540 self._before_request_lock = Lock()541 533- # register the static folder for the application. Do that even534- # if the folder does not exist. First of all it might be created535- # while the server is running (usually happens during development)536- # but also because google appengine stores static files somewhere537- # else when mapped with the .yml file.542+ # Add a static route using the provided static_url_path, static_host,543+ # and static_folder if there is a configured static_folder.544+ # Note we do this without checking if static_folder exists.545+ # For one, it might be created while the server is running (e.g. during546+ # development). Also, Google App Engine stores static files somewhere547 if self.has_static_folder:548+ assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'549 self.add_url_rule(self.static_url_path + '/<path:filename>',540- endpoint='static',550+ endpoint='static', host=static_host,551 view_func=self.send_static_file)552 553 #: The click command line context for this application. Commands554 #: registered here show up in the :command:`flask` command once the420 unmodified lines975 """976 return iter(self._blueprint_order)977 978 @setupmethod969- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):979+ def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):980 """Connects a URL rule. Works exactly like the :meth:`route`981 decorator. If a view_func is provided it will be registered with the982 endpoint.983 31 unmodified lines1015 itself assumes the name of the view function as1016 endpoint1017 :param view_func: the function to call when serving a request to the1018 provided endpoint1019+ :param provide_automatic_options: controls whether the ``OPTIONS``1020+ method should be added automatically. This can also be controlled1021+ by setting the ``view_func.provide_automatic_options = False``1022+ before adding the rule.1023 :param options: the options to be forwarded to the underlying1024 :class:`~werkzeug.routing.Rule` object. A change1025 to Werkzeug is handling of method options. methods1026 is a list of methods this rule should be limited21 unmodified lines1048 required_methods = set(getattr(view_func, 'required_methods', ()))1049 1050 # starting with Flask 0.8 the view_func object can disable and1051 # force-enable the automatic options handling.1052+ if provide_automatic_options is None:1038- provide_automatic_options = getattr(view_func,1039- 'provide_automatic_options', None)1053+ provide_automatic_options = getattr(view_func,1054+ 'provide_automatic_options', None)1055 1056 if provide_automatic_options is None:1057 if 'OPTIONS' not in methods:1058 provide_automatic_options = True250 unmodified lines1309 1310 @setupmethod1311 def before_request(self, f):1312 """Registers a function to run before each request.1313+ 1314+ For example, this can be used to open a database connection, or to load1315+ the logged in user from the session.1316 1299- The function will be called without any arguments.1300- If the function returns a non-None value, it's handled as1301- if it was the return value from the view and further1302- request handling is stopped.1317+ The function will be called without any arguments. If it returns a1318+ non-None value, the value is handled as if it was the return value from1319+ the view, and further request handling is stopped.1320 """1321 self.before_request_funcs.setdefault(None, []).append(f)1322 return f1323 110 unmodified lines1434 return f1435 1436 @setupmethod1437 def url_value_preprocessor(self, f):1421- """Registers a function as URL value preprocessor for all view1422- functions of the application. It's called before the view functions1423- are called and can modify the url values provided.1438+ """Register a URL value preprocessor function for all view1439+ functions in the application. These functions will be called before the1440+ :meth:`before_request` functions.1441+ 1442+ The function can modify the values captured from the matched url before1443+ they are passed to the view. For example, this can be used to pop a1444+ common language code value and place it in ``g`` rather than pass it to1445+ every view.1446+ 1447+ The function is passed the endpoint name and values dict. The return1448+ value is ignored.1449 """1450 self.url_value_preprocessors.setdefault(None, []).append(f)1451 return f1452 6 unmodified lines1459 self.url_default_functions.setdefault(None, []).append(f)1460 return f1461 1462 def _find_error_handler(self, e):1438- """Finds a registered error handler for the request’s blueprint.1439- Otherwise falls back to the app, returns None if not a suitable1440- handler is found.1463+ """Find a registered error handler for a request in this order:1464+ blueprint handler for a specific code, app handler for a specific code,1465+ blueprint generic HTTPException handler, app generic HTTPException handler,1466+ and returns None if a suitable handler is not found.1467 """1468 exc_class, code = self._get_exc_class_and_code(type(e))1469 1470 def find_handler(handler_map):1471 if not handler_map:1472 return1473+1474 for cls in exc_class.__mro__:1475 handler = handler_map.get(cls)1476 if handler is not None:1477 # cache for next time exc_class is raised1478 handler_map[exc_class] = handler1479 return handler1480 1454- # try blueprint handlers1455- handler = find_handler(self.error_handler_spec1456- .get(request.blueprint, {})1457- .get(code))1458- if handler is not None:1459- return handler1481+ # check for any in blueprint or app1482+ for name, c in ((request.blueprint, code), (None, code),1483+ (request.blueprint, None), (None, None)):1484+ handler = find_handler(self.error_handler_spec.get(name, {}).get(c))1485 1461- # fall back to app handlers1462- return find_handler(self.error_handler_spec[None].get(code))1486+ if handler:1487+ return handler1488 1489 def handle_http_exception(self, e):1490 """Handles an HTTP exception. By default this will invoke the1491 registered error handlers and fall back to returning the228 unmodified lines1720 """1721 return False1722 1723 def make_response(self, rv):1699- """Converts the return value from a view function to a real1700- response object that is an instance of :attr:`response_class`.1724+ """Convert the return value from a view function to an instance of1725+ :attr:`response_class`.1726 1702- The following types are allowed for `rv`:1727+ :param rv: the return value from the view function. The view function1728+ must return a response. Returning ``None``, or the view ending1729+ without returning, is not allowed. The following types are allowed1730+ for ``view_rv``:1731 1704- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1732+ ``str`` (``unicode`` in Python 2)1733+ A response object is created with the string encoded to UTF-81734+ as the body.1735+ 1736+ ``bytes`` (``str`` in Python 2)1737+ A response object is created with the bytes as the body.1738+ 1739+ ``tuple``1740+ Either ``(body, status, headers)``, ``(body, status)``, or1741+ ``(body, headers)``, where ``body`` is any of the other types1742+ allowed here, ``status`` is a string or an integer, and1743+ ``headers`` is a dictionary or a list of ``(key, value)``1744+ tuples. If ``body`` is a :attr:`response_class` instance,1745+ ``status`` overwrites the exiting value and ``headers`` are1746+ extended.1747+ 1748+ :attr:`response_class`1749+ The object is returned unchanged.1750+ 1751+ other :class:`~werkzeug.wrappers.Response` class1752+ The object is coerced to :attr:`response_class`.1753+ 1754+ :func:`callable`1755+ The function is called as a WSGI application. The result is1756+ used to create a response object.1757 1706- ======================= ===========================================1707- :attr:`response_class` the object is returned unchanged1708- :class:`str` a response object is created with the1709- string as body1710- :class:`unicode` a response object is created with the1711- string encoded to utf-8 as body1712- a WSGI function the function is called as WSGI application1713- and buffered as response object1714- :class:`tuple` A tuple in the form ``(response, status,1715- headers)`` or ``(response, headers)``1716- where `response` is any of the1717- types defined here, `status` is a string1718- or an integer and `headers` is a list or1719- a dictionary with header values.1720- ======================= ===========================================1721-1722- :param rv: the return value from the view function1723-1758 .. versionchanged:: 0.91759 Previously a tuple was interpreted as the arguments for the1760 response object.1761 """1728- status_or_headers = headers = None1729- if isinstance(rv, tuple):1730- rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))1762 1732- if rv is None:1733- raise ValueError('View function did not return a response')1763+ status = headers = None1764 1735- if isinstance(status_or_headers, (dict, list)):1736- headers, status_or_headers = status_or_headers, None1765+ # unpack tuple returns1766+ if isinstance(rv, (tuple, list)):1767+ len_rv = len(rv)1768 1769+ # a 3-tuple is unpacked directly1770+ if len_rv == 3:1771+ rv, status, headers = rv1772+ # decide if a 2-tuple has status or headers1773+ elif len_rv == 2:1774+ if isinstance(rv[1], (Headers, dict, tuple, list)):1775+ rv, headers = rv1776+ else:1777+ rv, status = rv1778+ # other sized tuples are not allowed1779+ else:1780+ raise TypeError(1781+ 'The view function did not return a valid response tuple.'1782+ ' The tuple must have the form (body, status, headers),'1783+ ' (body, status), or (body, headers).'1784+ )1785+1786+ # the body must not be None1787+ if rv is None:1788+ raise TypeError(1789+ 'The view function did not return a valid response. The'1790+ ' function either returned None or ended without a return'1791+ ' statement.'1792+ )1793+1794+ # make sure the body is an instance of the response class1795 if not isinstance(rv, self.response_class):1739- # When we create a response object directly, we let the constructor1740- # set the headers and status. We do this because there can be1741- # some extra logic involved when creating these objects with1742- # specific values (like default content type selection).1796 if isinstance(rv, (text_type, bytes, bytearray)):1744- rv = self.response_class(rv, headers=headers,1745- status=status_or_headers)1746- headers = status_or_headers = None1797+ # let the response class set the status and headers instead of1798+ # waiting to do it manually, so that the class can handle any1799+ # special logic1800+ rv = self.response_class(rv, status=status, headers=headers)1801+ status = headers = None1802 else:1803+ # evaluate a WSGI callable, or coerce a different response1804+ # class to the correct type1805+ try:1748- rv = self.response_class.force_type(rv, request.environ)1806+ rv = self.response_class.force_type(rv, request.environ)1807+ except TypeError as e:1808+ new_error = TypeError(1809+ '{e}\nThe view function did not return a valid'1810+ ' response. The return type must be a string, tuple,'1811+ ' Response instance, or WSGI callable, but it was a'1812+ ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1813+ )1814+ reraise(TypeError, new_error, sys.exc_info()[2])1815 1816+ # prefer the status if it was provided1750- if status_or_headers is not None:1751- if isinstance(status_or_headers, string_types):1752- rv.status = status_or_headers1817+ if status is not None:1818+ if isinstance(status, (text_type, bytes, bytearray)):1819+ rv.status = status1820 else:1754- rv.status_code = status_or_headers1821+ rv.status_code = status1822+1823+ # extend existing headers with provided headers1824 if headers:1825 rv.headers.extend(headers)1826 1827 return rv54 unmodified lines1882 reraise(exc_type, exc_value, tb)1883 raise error1884 1885 def preprocess_request(self):1817- """Called before the actual request dispatching and will1818- call each :meth:`before_request` decorated function, passing no1819- arguments.1820- If any of these functions returns a value, it's handled as1821- if it was the return value from the view and further1822- request handling is stopped.1823-1824- This also triggers the :meth:`url_value_preprocessor` functions before1825- the actual :meth:`before_request` functions are called.1886+ """Called before the request is dispatched. Calls1887+ :attr:`url_value_preprocessors` registered with the app and the1888+ current blueprint (if any). Then calls :attr:`before_request_funcs`1889+ registered with the app and the blueprint.1890+ 1891+ If any :meth:`before_request` handler returns a non-None value, the1892+ value is handled as if it was the return value from the view, and1893+ further request handling is stopped.1894 """1895+1896 bp = _request_ctx_stack.top.request.blueprint1897 1898 funcs = self.url_value_preprocessors.get(None, ())1899 if bp is not None and bp in self.url_value_preprocessors:151 unmodified lines2051 a list of headers and an optional2052 exception context to start the response2053 """2054 ctx = self.request_context(environ)1986- ctx.push()2055 error = None2056 try:2057 try:2058+ ctx.push()2059 response = self.full_dispatch_request()2060 except Exception as e:2061 error = e2062 response = self.handle_exception(e)18 unmodified linesmodified:flask/blueprints.py+7 added
87 unmodified lines88 89 warn_on_modifications = False90 _got_registered_once = False91 92+ #: Blueprint local JSON decoder class to use.93+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.94+ json_encoder = None95+ #: Blueprint local JSON decoder class to use.96+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.97+ json_decoder = None98+99 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):318 unmodified linesmodified:flask/cli.py+107 added-15 removed
10 unmodified lines11 12 import os13 import sys14 import traceback15-from threading import Lock, Thread15 from functools import update_wrapper16+from operator import attrgetter17+from threading import Lock, Thread18 19 import click20 21+from . import __version__22 from ._compat import iteritems, reraise23+from .globals import current_app24 from .helpers import get_debug_flag22-from . import __version__25+from ._compat import getargspec26 27+28 class NoAppException(click.UsageError):29 """Raised if an application cannot be found or loaded."""30 31 28-def find_best_app(module):32+def find_best_app(script_info, module):33 """Given a module instance this tries to find the best possible34 application in the module or raises an exception.35 """36 from . import Flask37 38 # Search for the most common names first.35- for attr_name in 'app', 'application':39+ for attr_name in ('app', 'application'):40 app = getattr(module, attr_name, None)37- if app is not None and isinstance(app, Flask):41+ if isinstance(app, Flask):42 return app43 44 # Otherwise find the only object that is a Flask instance.41- matches = [v for k, v in iteritems(module.__dict__)42- if isinstance(v, Flask)]45+ matches = [46+ v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)47+ ]48 49 if len(matches) == 1:50 return matches[0]46- raise NoAppException('Failed to find application in module "%s". Are '47- 'you sure it contains a Flask application? Maybe '48- 'you wrapped it in a WSGI middleware or you are '49- 'using a factory function.' % module.__name__)51+ elif len(matches) > 1:52+ raise NoAppException(53+ 'Auto-detected multiple Flask applications in module "{module}".'54+ ' Use "FLASK_APP={module}:name" to specify the correct'55+ ' one.'.format(module=module.__name__)56+ )57 58+ # Search for app factory callables.59+ for attr_name in ('create_app', 'make_app'):60+ app_factory = getattr(module, attr_name, None)61 62+ if callable(app_factory):63+ try:64+ app = call_factory(app_factory, script_info)65+ if isinstance(app, Flask):66+ return app67+ except TypeError:68+ raise NoAppException(69+ 'Auto-detected "{callable}()" in module "{module}", but '70+ 'could not call it without specifying arguments.'.format(71+ callable=attr_name, module=module.__name__72+ )73+ )74+75+ raise NoAppException(76+ 'Failed to find application in module "{module}". Are you sure '77+ 'it contains a Flask application? Maybe you wrapped it in a WSGI '78+ 'middleware.'.format(module=module.__name__)79+ )80+81+82+def call_factory(func, script_info):83+ """Checks if the given app factory function has an argument named 84+ ``script_info`` or just a single argument and calls the function passing 85+ ``script_info`` if so. Otherwise, calls the function without any arguments86+ and returns the result.87+ """88+ arguments = getargspec(func).args89+ if 'script_info' in arguments:90+ return func(script_info=script_info)91+ elif len(arguments) == 1:92+ return func(script_info)93+ return func()94+95+96 def prepare_exec_for_file(filename):97 """Given a filename this will try to calculate the python path, add it98 to the search path and return the actual module name that is expected.99 """21 unmodified lines121 sys.path.insert(0, dirpath)122 return '.'.join(module[::-1])123 124 81-def locate_app(app_id):125+def locate_app(script_info, app_id):126 """Attempts to locate the application."""127 __traceback_hide__ = True128 if ':' in app_id:129 module, app_obj = app_id.split(':', 1)17 unmodified lines147 'ensure the extension is .py' % module)148 149 mod = sys.modules[module]150 if app_obj is None:107- app = find_best_app(mod)151+ app = find_best_app(script_info, mod)152 else:153 app = getattr(mod, app_obj, None)154 if app is None:155 raise RuntimeError('Failed to find application in module "%s"'116 unmodified lines272 __traceback_hide__ = True273 if self._loaded_app is not None:274 return self._loaded_app275 if self.create_app is not None:232- rv = self.create_app(self)276+ rv = call_factory(self.create_app, self)277 else:278 if not self.app_import_path:279 raise NoAppException(280 'Could not locate Flask application. You did not provide '281 'the FLASK_APP environment variable.\n\nFor more '282 'information see '283 'http://flask.pocoo.org/docs/latest/quickstart/')240- rv = locate_app(self.app_import_path)284+ rv = locate_app(self, self.app_import_path)285 debug = get_debug_flag()286 if debug is not None:287 rv.debug = debug288 self._loaded_app = rv73 unmodified lines362 363 if add_default_commands:364 self.add_command(run_command)365 self.add_command(shell_command)366+ self.add_command(routes_command)367 368 self._loaded_plugin_commands = False369 370 def _load_plugin_commands(self):157 unmodified lines528 529 code.interact(banner=banner, local=ctx)530 531 532+@click.command('routes', short_help='Show the routes for the app.')533+@click.option(534+ '--sort', '-s',535+ type=click.Choice(('endpoint', 'methods', 'rule', 'match')),536+ default='endpoint',537+ help=(538+ 'Method to sort routes by. "match" is the order that Flask will match '539+ 'routes when dispatching a request.'540+ )541+)542+@click.option(543+ '--all-methods',544+ is_flag=True,545+ help="Show HEAD and OPTIONS methods."546+)547+@with_appcontext548+def routes_command(sort, all_methods):549+ """Show all registered routes with endpoints and methods."""550+551+ rules = list(current_app.url_map.iter_rules())552+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))553+554+ if sort in ('endpoint', 'rule'):555+ rules = sorted(rules, key=attrgetter(sort))556+ elif sort == 'methods':557+ rules = sorted(rules, key=lambda rule: sorted(rule.methods))558+559+ rule_methods = [560+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules561+ ]562+563+ headers = ('Endpoint', 'Methods', 'Rule')564+ widths = (565+ max(len(rule.endpoint) for rule in rules),566+ max(len(methods) for methods in rule_methods),567+ max(len(rule.rule) for rule in rules),568+ )569+ widths = [max(len(h), w) for h, w in zip(headers, widths)]570+ row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)571+572+ click.echo(row.format(*headers).strip())573+ click.echo(row.format(*('-' * width for width in widths)))574+575+ for rule, methods in zip(rules, rule_methods):576+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())577+578+579 cli = FlaskGroup(help="""\580 This shell command acts as general utility script for Flask applications.581 582 It loads the application configured (through the FLASK_APP environment39 unmodified linesmodified:flask/helpers.py+71 added-11 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes18 from time import time19 from zlib import adler3220 from threading import RLock21+import unicodedata22 from werkzeug.routing import BuildError23 from functools import update_wrapper24 25 try:305 unmodified lines331 # deal with that sort of stuff.332 values['_external'] = external333 values['_anchor'] = anchor334 values['_method'] = method335+ values['_scheme'] = scheme336 return appctx.app.handle_url_build_error(error, endpoint, values)337 338 if anchor is not None:339 rv += '#' + url_quote(anchor)139 unmodified lines479 480 .. versionchanged:: 0.12481 The `attachment_filename` is preferred over `filename` for MIME-type482 detection.483+ 484+ .. versionchanged:: 0.13485+ UTF-8 filenames, as specified in `RFC 2231`_, are supported.486+ 487+ .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4488 481- :param filename_or_fp: the filename of the file to send in `latin-1`.489+ :param filename_or_fp: the filename of the file to send.490 This is relative to the :attr:`~Flask.root_path`491 if a relative path is specified.492 Alternatively a file object might be provided in493 which case ``X-Sendfile`` might not work and fall47 unmodified lines541 if as_attachment:542 if attachment_filename is None:543 raise TypeError('filename unavailable, required for '544 'sending as attachment')537- headers.add('Content-Disposition', 'attachment',538- filename=attachment_filename)545 546+ try:547+ attachment_filename = attachment_filename.encode('latin-1')548+ except UnicodeEncodeError:549+ filenames = {550+ 'filename': unicodedata.normalize(551+ 'NFKD', attachment_filename).encode('latin-1', 'ignore'),552+ 'filename*': "UTF-8''%s" % url_quote(attachment_filename),553+ }554+ else:555+ filenames = {'filename': attachment_filename}556+557+ headers.add('Content-Disposition', 'attachment', **filenames)558+559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = filename74 unmodified lines637 :param pathnames: the untrusted pathnames relative to that directory.638 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed639 paths fall out of its boundaries.640 """641+642+ parts = [directory]643+644 for filename in pathnames:645 if filename != '':646 filename = posixpath.normpath(filename)625- for sep in _os_alt_seps:626- if sep in filename:627- raise NotFound()628- if os.path.isabs(filename) or \629- filename == '..' or \630- filename.startswith('../'):647+648+ if (649+ any(sep in filename for sep in _os_alt_seps)650+ or os.path.isabs(filename)651+ or filename == '..'652+ or filename.startswith('../')653+ ):654 raise NotFound()632- directory = os.path.join(directory, filename)633- return directory655 656+ parts.append(filename)657 658+ return posixpath.join(*parts)659+660+661 def send_from_directory(directory, filename, **options):662 """Send a file from a given directory with :func:`send_file`. This663 is a secure way to quickly expose static files from an upload folder664 or something similar.317 unmodified lines982 :returns: number of seconds983 :rtype: int984 """985 return td.days * 60 * 60 * 24 + td.seconds986+987+988+def is_ip(value):989+ """Determine if the given string is an IP address.990+991+ :param value: value to check992+ :type value: str993+994+ :return: True if string is an IP address995+ :rtype: bool996+ """997+998+ for family in (socket.AF_INET, socket.AF_INET6):999+ try:1000+ socket.inet_pton(family, value)1001+ except socket.error:1002+ pass1003+ else:1004+ return True1005+1006+ return False1007+1008+1009+def patch_vary_header(response, value):1010+ """Add a value to the ``Vary`` header if it is not already present."""1011+1012+ header = response.headers.get('Vary', '')1013+ headers = [h for h in (h.strip() for h in header.split(',')) if h]1014+ lower_value = value.lower()1015+1016+ if not any(h.lower() == lower_value for h in headers):1017+ headers.append(value)1018+1019+ updated_header = ', '.join(headers)1020+ response.headers['Vary'] = updated_headermodified:flask/json.py+18 added-7 removed
89 unmodified lines90 91 def _dump_arg_defaults(kwargs):92 """Inject default arguments for dump functions."""93 if current_app:94- kwargs.setdefault('cls', current_app.json_encoder)94+ bp = current_app.blueprints.get(request.blueprint) if request else None95+ kwargs.setdefault(96+ 'cls',97+ bp.json_encoder if bp and bp.json_encoder98+ else current_app.json_encoder99+ )100+101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103+104 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105 else:106 kwargs.setdefault('sort_keys', True)107 kwargs.setdefault('cls', JSONEncoder)1 unmodified line109 110 def _load_arg_defaults(kwargs):111 """Inject default arguments for load functions."""112 if current_app:106- kwargs.setdefault('cls', current_app.json_decoder)113+ bp = current_app.blueprints.get(request.blueprint) if request else None114+ kwargs.setdefault(115+ 'cls',116+ bp.json_decoder if bp and bp.json_decoder117+ else current_app.json_decoder118+ )119 else:120 kwargs.setdefault('cls', JSONDecoder)121 122 124 unmodified lines247 .. versionchanged:: 0.11248 Added support for serializing top-level arrays. This introduces a249 security risk in ancient browsers. See :ref:`json-security` for details.250 239- This function's response will be pretty printed if it was not requested240- with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless241- the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.242- Compressed (not pretty) formatting currently means no indents and no243- spaces after separators.251+ This function's response will be pretty printed if the252+ ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the253+ Flask app is running in debug mode. Compressed (not pretty) formatting254+ currently means no indents and no spaces after separators.255 256 .. versionadded:: 0.2257 """258 22 unmodified linesmodified:flask/sessions.py+116 added-55 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import uuid12 import hashlib13+import uuid14+import warnings14-from base64 import b64encode, b64decode15+from base64 import b64decode, b64encode16 from datetime import datetime16-from werkzeug.http import http_date, parse_date17+18+from itsdangerous import BadSignature, URLSafeTimedSerializer19 from werkzeug.datastructures import CallbackDict20+from werkzeug.http import http_date, parse_date21+22+from flask.helpers import patch_vary_header23 from . import Markup, json24 from ._compat import iteritems, text_type20-from .helpers import total_seconds25+from .helpers import is_ip, total_seconds26 22-from itsdangerous import URLSafeTimedSerializer, BadSignature27 24-28 class SessionMixin(object):29 """Expands a basic dictionary with an accessors that are expected30 by Flask extensions and users for the session.31 """18 unmodified lines50 #: long as changes do not happen on mutable structures in the session.51 #: The default mixin implementation just hardcodes ``True`` in.52 modified = True53 54+ #: the accessed variable indicates whether or not the session object has55+ #: been accessed in that request. This allows flask to append a `Vary:56+ #: Cookie` header to the response if the session is being accessed. This57+ #: allows caching proxy servers, like Varnish, to use both the URL and the58+ #: session cookie as keys when caching pages, preventing multiple users59+ #: from being served the same cache.60+ accessed = True61 62 def _tag(value):63 if isinstance(value, tuple):64 return {' t': [_tag(x) for x in value]}60 unmodified lines125 126 def __init__(self, initial=None):127 def on_update(self):128 self.modified = True119- CallbackDict.__init__(self, initial, on_update)129+ self.accessed = True130+131+ super(SecureCookieSession, self).__init__(initial, on_update)132 self.modified = False133+ self.accessed = False134 135+ def __getitem__(self, key):136+ self.accessed = True137+ return super(SecureCookieSession, self).__getitem__(key)138 139+ def get(self, key, default=None):140+ self.accessed = True141+ return super(SecureCookieSession, self).get(key, default)142+143+ def setdefault(self, key, default=None):144+ self.accessed = True145+ return super(SecureCookieSession, self).setdefault(key, default)146+147+148 class NullSession(SecureCookieSession):149 """Class used to generate nicer error messages if sessions are not150 available. Will still allow read-only access to the empty session151 but fail on setting.72 unmodified lines224 """225 return isinstance(obj, self.null_session_class)226 227 def get_cookie_domain(self, app):203- """Helpful helper method that returns the cookie domain that should204- be used for the session cookie if session cookies are used.228+ """Returns the domain that should be set for the session cookie.229+ 230+ Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise231+ falls back to detecting the domain based on ``SERVER_NAME``.232+ 233+ Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is234+ updated to avoid re-running the logic.235 """206- if app.config['SESSION_COOKIE_DOMAIN'] is not None:207- return app.config['SESSION_COOKIE_DOMAIN']208- if app.config['SERVER_NAME'] is not None:209- # chop off the port which is usually not supported by browsers210- rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]236 212- # Google chrome does not like cookies set to .localhost, so213- # we just go with no domain then. Flask documents anyways that214- # cross domain cookies need a fully qualified domain name215- if rv == '.localhost':216- rv = None237+ rv = app.config['SESSION_COOKIE_DOMAIN']238 218- # If we infer the cookie domain from the server name we need219- # to check if we are in a subpath. In that case we can't220- # set a cross domain cookie.221- if rv is not None:222- path = self.get_cookie_path(app)223- if path != '/':224- rv = rv.lstrip('.')239+ # set explicitly, or cached from SERVER_NAME detection240+ # if False, return None241+ if rv is not None:242+ return rv if rv else None243 226- return rv244+ rv = app.config['SERVER_NAME']245 246+ # server name not set, cache False to return none next time247+ if not rv:248+ app.config['SESSION_COOKIE_DOMAIN'] = False249+ return None250+251+ # chop off the port which is usually not supported by browsers252+ # remove any leading '.' since we'll add that later253+ rv = rv.rsplit(':', 1)[0].lstrip('.')254+255+ if '.' not in rv:256+ # Chrome doesn't allow names without a '.'257+ # this should only come up with localhost258+ # hack around this by not setting the name, and show a warning259+ warnings.warn(260+ '"{rv}" is not a valid cookie domain, it must contain a ".".'261+ ' Add an entry to your hosts file, for example'262+ ' "{rv}.localdomain", and use that instead.'.format(rv=rv)263+ )264+ app.config['SESSION_COOKIE_DOMAIN'] = False265+ return None266+267+ ip = is_ip(rv)268+269+ if ip:270+ warnings.warn(271+ 'The session cookie domain is an IP address. This may not work'272+ ' as intended in some browsers. Add an entry to your hosts'273+ ' file, for example "localhost.localdomain", and use that'274+ ' instead.'275+ )276+277+ # if this is not an ip and app is mounted at the root, allow subdomain278+ # matching by adding a '.' prefix279+ if self.get_cookie_path(app) == '/' and not ip:280+ rv = '.' + rv281+282+ app.config['SESSION_COOKIE_DOMAIN'] = rv283+ return rv284+285 def get_cookie_path(self, app):286 """Returns the path for which the cookie should be valid. The287 default implementation uses the value from the ``SESSION_COOKIE_PATH``288 config var if it's set, and falls back to ``APPLICATION_ROOT`` or24 unmodified lines313 if session.permanent:314 return datetime.utcnow() + app.permanent_session_lifetime315 316 def should_set_cookie(self, app, session):260- """Indicates whether a cookie should be set now or not. This is261- used by session backends to figure out if they should emit a262- set-cookie header or not. The default behavior is controlled by263- the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If264- it's set to ``False`` then a cookie is only set if the session is265- modified, if set to ``True`` it's always set if the session is266- permanent.317+ """Used by session backends to determine if a ``Set-Cookie`` header318+ should be set for this session cookie for this response. If the session319+ has been modified, the cookie is set. If the session is permanent and320+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is321+ always set.322+ 323+ This check is usually skipped if the session was deleted.324 268- This check is usually skipped if sessions get deleted.269-325 .. versionadded:: 0.11326 """272- if session.modified:273- return True274- save_each = app.config['SESSION_REFRESH_EACH_REQUEST']275- return save_each and session.permanent327 328+ return session.modified or (329+ session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']330+ )331+332 def open_session(self, app, request):333 """This method has to be implemented and must either return ``None``334 in case the loading failed because of a configuration error or an335 instance of a session object which implements a dictionary like56 unmodified lines392 def save_session(self, app, session, response):393 domain = self.get_cookie_domain(app)394 path = self.get_cookie_path(app)395 341- # Delete case. If there is no session we bail early.342- # If the session was modified to be empty we remove the343- # whole cookie.396+ # If the session is modified to be empty, remove the cookie.397+ # If the session is empty, return without setting the cookie.398 if not session:399 if session.modified:346- response.delete_cookie(app.session_cookie_name,347- domain=domain, path=path)400+ response.delete_cookie(401+ app.session_cookie_name,402+ domain=domain,403+ path=path404+ )405+406 return407 350- # Modification case. There are upsides and downsides to351- # emitting a set-cookie header each request. The behavior352- # is controlled by the :meth:`should_set_cookie` method353- # which performs a quick check to figure out if the cookie354- # should be set or not. This is controlled by the355- # SESSION_REFRESH_EACH_REQUEST config flag as well as356- # the permanent flag on the session itself.408+ # Add a "Vary: Cookie" header if the session was accessed at all.409+ if session.accessed:410+ patch_vary_header(response, 'Cookie')411+412 if not self.should_set_cookie(app, session):413 return414 415 httponly = self.get_cookie_httponly(app)416 secure = self.get_cookie_secure(app)417 expires = self.get_expiration_time(app, session)418 val = self.get_signing_serializer(app).dumps(dict(session))364- response.set_cookie(app.session_cookie_name, val,365- expires=expires, httponly=httponly,366- domain=domain, path=path, secure=secure)419+ response.set_cookie(420+ app.session_cookie_name,421+ val,422+ expires=expires,423+ httponly=httponly,424+ domain=domain,425+ path=path,426+ secure=secure427+ )modified:flask/views.py+26 added-18 removed
49 unmodified lines50 51 #: A list of methods this view can handle.52 methods = None53 54+ #: Setting this disables or force-enables the automatic options handling.55+ provide_automatic_options = None56+57 #: The canonical way to decorate class-based views is to decorate the58 #: return value of as_view(). However since this moves parts of the59 #: logic from the class declaration to the place where it's hooked60 #: into the routing system.40 unmodified lines101 view.__name__ = name102 view.__doc__ = cls.__doc__103 view.__module__ = cls.__module__104 view.methods = cls.methods105+ view.provide_automatic_options = cls.provide_automatic_options106 return view107 108 109 class MethodViewType(type):110+ """Metaclass for :class:`MethodView` that determines what methods the view111+ defines.112+ """113 107- def __new__(cls, name, bases, d):108- rv = type.__new__(cls, name, bases, d)114+ def __init__(cls, name, bases, d):115+ super(MethodViewType, cls).__init__(name, bases, d)116+117 if 'methods' not in d:110- methods = set(rv.methods or [])111- for key in d:112- if key in http_method_funcs:118+ methods = set()119+120+ for key in http_method_funcs:121+ if hasattr(cls, key):122 methods.add(key.upper())114- # If we have no method at all in there we don't want to115- # add a method list. (This is for instance the case for116- # the base class or another subclass of a base method view117- # that does not introduce new methods).123+124+ # If we have no method at all in there we don't want to add a125+ # method list. This is for instance the case for the base class126+ # or another subclass of a base method view that does not introduce127+ # new methods.128 if methods:119- rv.methods = sorted(methods)120- return rv129+ cls.methods = methods130 131 132 class MethodView(with_metaclass(MethodViewType, View)):124- """Like a regular class-based view but that dispatches requests to125- particular methods. For instance if you implement a method called126- :meth:`get` it means it will respond to ``'GET'`` requests and127- the :meth:`dispatch_request` implementation will automatically128- forward your request to that. Also :attr:`options` is set for you129- automatically::133+ """A class-based view that dispatches request methods to the corresponding134+ class methods. For example, if you implement a ``get`` method, it will be135+ used to handle ``GET`` requests. ::136 137 class CounterAPI(MethodView):132-138 def get(self):139 return session.get('counter', 0)140 141 def post(self):1 unmodified line143 return 'OK'144 145 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))146 """147+148 def dispatch_request(self, *args, **kwargs):149 meth = getattr(self, request.method.lower(), None)150+151 # If the request method is HEAD and we don't have a handler for it152 # retry with GET.153 if meth is None and request.method == 'HEAD':154 meth = getattr(self, 'get', None)155+156 assert meth is not None, 'Unimplemented method %r' % request.method157 return meth(*args, **kwargs)modified:tests/conftest.py+55 added-16 removed
11 unmodified lines12 import sys13 import pkgutil14 import pytest15 import textwrap16+from flask import Flask as _Flask17 18 19+class Flask(_Flask):20+ testing = True21+ secret_key = __name__22+23+ def make_response(self, rv):24+ if rv is None:25+ rv = ''26+ return super(Flask, self).make_response(rv)27+28+29 @pytest.fixture30+def app():31+ app = Flask(__name__)32+ return app33+34+35+@pytest.fixture36+def app_ctx(app):37+ with app.app_context() as ctx:38+ yield ctx39+40+41+@pytest.fixture42+def req_ctx(app):43+ with app.test_request_context() as ctx:44+ yield ctx45+46+47+@pytest.fixture48+def client(app):49+ return app.test_client()50+51+52+@pytest.fixture53 def test_apps(monkeypatch):54 monkeypatch.syspath_prepend(55 os.path.abspath(os.path.join(56 os.path.dirname(__file__), 'test_apps'))57 )58 59+60 @pytest.fixture(autouse=True)26-def leak_detector(request):27- def ensure_clean_request_context():28- # make sure we're not leaking a request context since we are29- # testing flask internally in debug mode in a few cases30- leaks = []31- while flask._request_ctx_stack.top is not None:32- leaks.append(flask._request_ctx_stack.pop())33- assert leaks == []34- request.addfinalizer(ensure_clean_request_context)61+def leak_detector():62+ yield63 64+ # make sure we're not leaking a request context since we are65+ # testing flask internally in debug mode in a few cases66+ leaks = []67+ while flask._request_ctx_stack.top is not None:68+ leaks.append(flask._request_ctx_stack.pop())69+ assert leaks == []70 71+72 @pytest.fixture(params=(True, False))73 def limit_loader(request, monkeypatch):74 """Patch pkgutil.get_loader to give loader without get_filename or archive.75 20 unmodified lines96 old_get_loader = pkgutil.get_loader97 98 def get_loader(*args, **kwargs):99 return LimitedLoader(old_get_loader(*args, **kwargs))100+101 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)102 103 104 @pytest.fixture105 def modules_tmpdir(tmpdir, monkeypatch):70- '''A tmpdir added to sys.path'''106+ """A tmpdir added to sys.path."""107 rv = tmpdir.mkdir('modules_tmpdir')108 monkeypatch.syspath_prepend(str(rv))109 return rv110 5 unmodified lines116 117 118 @pytest.fixture119 def site_packages(modules_tmpdir, monkeypatch):84- '''Create a fake site-packages'''120+ """Create a fake site-packages."""121 rv = modules_tmpdir \86- .mkdir('lib')\87- .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\122+ .mkdir('lib') \123+ .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \124 .mkdir('site-packages')125 monkeypatch.syspath_prepend(str(rv))126 return rv127 128 129 @pytest.fixture130 def install_egg(modules_tmpdir, monkeypatch):95- '''Generate egg from package name inside base and put the egg into96- sys.path'''131+ """Generate egg from package name inside base and put the egg into132+ sys.path."""133+134 def inner(name, base=modules_tmpdir):135 if not isinstance(name, str):136 raise ValueError(name)137 base.join(name).ensure_dir()15 unmodified lines153 )154 egg_path, = modules_tmpdir.join('dist/').listdir()155 monkeypatch.syspath_prepend(str(egg_path))156 return egg_path157+158 return inner159 160 161 @pytest.fixture162 def purge_module(request):163 def inner(name):164 request.addfinalizer(lambda: sys.modules.pop(name, None))165+166 return inner167 168 169 @pytest.yield_fixture(autouse=True)170 def catch_deprecation_warnings(recwarn):171 yield172 gc.collect()134- assert not recwarn.list173+ assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)modified:tests/test_appctx.py+50 added-44 removed
12 unmodified lines13 14 import flask15 16 17-def test_basic_url_generation():18- app = flask.Flask(__name__)17+def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'20 21 @app.route('/')3 unmodified lines25 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'28 30-def test_url_generation_requires_server_name():31- app = flask.Flask(__name__)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')34 35+36 def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')39 40-def test_request_context_means_app_context():41- app = flask.Flask(__name__)40+41+def test_request_context_means_app_context(app):42 with app.test_request_context():43 assert flask.current_app._get_current_object() == app44 assert flask._app_ctx_stack.top is None45 46-def test_app_context_provides_current_app():47- app = flask.Flask(__name__)46+47+def test_app_context_provides_current_app(app):48 with app.app_context():49 assert flask.current_app._get_current_object() == app50 assert flask._app_ctx_stack.top is None51 52+52-def test_app_tearing_down():53+def test_app_tearing_down(app):54 cleanup_stuff = []54- app = flask.Flask(__name__)55+56 @app.teardown_appcontext57 def cleanup(exception):58 cleanup_stuff.append(exception)59 1 unmodified line61 pass62 63 assert cleanup_stuff == [None]64 65+64-def test_app_tearing_down_with_previous_exception():66+def test_app_tearing_down_with_previous_exception(app):67 cleanup_stuff = []66- app = flask.Flask(__name__)68+69 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)72 6 unmodified lines79 pass80 81 assert cleanup_stuff == [None]82 83+81-def test_app_tearing_down_with_handled_exception():84+def test_app_tearing_down_with_handled_exception(app):85 cleanup_stuff = []83- app = flask.Flask(__name__)86+87 @app.teardown_appcontext88 def cleanup(exception):89 cleanup_stuff.append(exception)90 4 unmodified lines95 pass96 97 assert cleanup_stuff == [None]98 96-def test_app_ctx_globals_methods():97- app = flask.Flask(__name__)98- with app.app_context():99- # get100- assert flask.g.get('foo') is None101- assert flask.g.get('foo', 'bar') == 'bar'102- # __contains__103- assert 'foo' not in flask.g104- flask.g.foo = 'bar'105- assert 'foo' in flask.g106- # setdefault107- flask.g.setdefault('bar', 'the cake is a lie')108- flask.g.setdefault('bar', 'hello world')109- assert flask.g.bar == 'the cake is a lie'110- # pop111- assert flask.g.pop('bar') == 'the cake is a lie'112- with pytest.raises(KeyError):113- flask.g.pop('bar')114- assert flask.g.pop('bar', 'more cake') == 'more cake'115- # __iter__116- assert list(flask.g) == ['foo']99 100+def test_app_ctx_globals_methods(app, app_ctx):101+ # get102+ assert flask.g.get('foo') is None103+ assert flask.g.get('foo', 'bar') == 'bar'104+ # __contains__105+ assert 'foo' not in flask.g106+ flask.g.foo = 'bar'107+ assert 'foo' in flask.g108+ # setdefault109+ flask.g.setdefault('bar', 'the cake is a lie')110+ flask.g.setdefault('bar', 'hello world')111+ assert flask.g.bar == 'the cake is a lie'112+ # pop113+ assert flask.g.pop('bar') == 'the cake is a lie'114+ with pytest.raises(KeyError):115+ flask.g.pop('bar')116+ assert flask.g.pop('bar', 'more cake') == 'more cake'117+ # __iter__118+ assert list(flask.g) == ['foo']119+120+118-def test_custom_app_ctx_globals_class():121+def test_custom_app_ctx_globals_class(app):122 class CustomRequestGlobals(object):123 def __init__(self):124 self.spam = 'eggs'122- app = flask.Flask(__name__)125+126 app.app_ctx_globals_class = CustomRequestGlobals127 with app.app_context():128 assert flask.render_template_string('{{ g.spam }}') == 'eggs'129 130+127-def test_context_refcounts():131+def test_context_refcounts(app, client):132 called = []129- app = flask.Flask(__name__)133+134 @app.teardown_request135 def teardown_req(error=None):136 called.append('request')137+138 @app.teardown_appcontext139 def teardown_app(error=None):140 called.append('app')141+142 @app.route('/')143 def index():144 with flask._app_ctx_stack.top:145 with flask._request_ctx_stack.top:146 pass147 env = flask._request_ctx_stack.top.request.environ148 assert env['werkzeug.request'] is not None149 return u''144- c = app.test_client()145- res = c.get('/')150+151+ res = client.get('/')152 assert res.status_code == 200153 assert res.data == b''154 assert called == ['request', 'app']155 156 151-def test_clean_pop():157+def test_clean_pop(app):158+ app.testing = False159 called = []153- app = flask.Flask(__name__)160 161 @app.teardown_request162 def teardown_req(error=None):163 1 / 07 unmodified lines171 called.append(flask.current_app.name)172 except ZeroDivisionError:173 pass174 169- assert called == ['test_appctx', 'TEARDOWN']175+ assert called == ['conftest', 'TEARDOWN']176 assert not flask.current_appmodified:tests/test_basic.py+554 added-455 removed
23 unmodified lines24 from werkzeug.routing import BuildError25 import werkzeug.serving26 27 28-def test_options_work():29- app = flask.Flask(__name__)30-28+def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'32+34- rv = app.test_client().open('/', method='OPTIONS')33+ rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''36 37 39-def test_options_on_multiple_rules():40- app = flask.Flask(__name__)41-38+def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])40 def index():41 return 'Hello World'42 43 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'46+49- rv = app.test_client().open('/', method='OPTIONS')47+ rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']49 50 53-def test_options_handling_disabled():51+def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)53 54 def index():55 return 'Hello World!'56+57 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')60 assert rv.status_code == 4051 unmodified line62 app = flask.Flask(__name__)63 64 def index2():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']71 72 73-def test_request_dispatching():74- app = flask.Flask(__name__)73+def test_provide_automatic_options_kwarg(app, client):74+ def index():75+ return flask.request.method76 77+ def more():78+ return flask.request.method79+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=False84+ )85+ assert client.get('/').data == b'GET'86+87+ rv = client.post('/')88+ assert rv.status_code == 40589+ assert sorted(rv.allow) == ['GET', 'HEAD']90+91+ # Older versions of Werkzeug.test.Client don't have an options method92+ if hasattr(client, 'options'):93+ rv = client.options('/')94+ else:95+ rv = client.open('/', method='OPTIONS')96+97+ assert rv.status_code == 40598+99+ rv = client.head('/')100+ assert rv.status_code == 200101+ assert not rv.data # head truncates102+ assert client.post('/more').data == b'POST'103+ assert client.get('/more').data == b'GET'104+105+ rv = client.delete('/more')106+ assert rv.status_code == 405107+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108+109+ if hasattr(client, 'options'):110+ rv = client.options('/more')111+ else:112+ rv = client.open('/more', method='OPTIONS')113+114+ assert rv.status_code == 405115+116+117+def test_request_dispatching(app, client):118 @app.route('/')119 def index():120 return flask.request.method121 122 @app.route('/more', methods=['GET', 'POST'])123 def more():124 return flask.request.method125 84- c = app.test_client()85- assert c.get('/').data == b'GET'86- rv = c.post('/')126+ assert client.get('/').data == b'GET'127+ rv = client.post('/')128 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']89- rv = c.head('/')130+ rv = client.head('/')131 assert rv.status_code == 200132 assert not rv.data # head truncates92- assert c.post('/more').data == b'POST'93- assert c.get('/more').data == b'GET'94- rv = c.delete('/more')133+ assert client.post('/more').data == b'POST'134+ assert client.get('/more').data == b'GET'135+ rv = client.delete('/more')136 assert rv.status_code == 405137 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']138 139 99-def test_disallow_string_for_allowed_methods():100- app = flask.Flask(__name__)140+def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145 146 107-def test_url_mapping():108- app = flask.Flask(__name__)109-147+def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149 150 def index():151 return flask.request.method3 unmodified lines155 156 def options():157 return random_uuid4158 121-159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161 162 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])164 128- c = app.test_client()129- assert c.get('/').data == b'GET'130- rv = c.post('/')165+ assert client.get('/').data == b'GET'166+ rv = client.post('/')167 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']133- rv = c.head('/')169+ rv = client.head('/')170 assert rv.status_code == 200171 assert not rv.data # head truncates136- assert c.post('/more').data == b'POST'137- assert c.get('/more').data == b'GET'138- rv = c.delete('/more')172+ assert client.post('/more').data == b'POST'173+ assert client.get('/more').data == b'GET'174+ rv = client.delete('/more')175 assert rv.status_code == 405176 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']141- rv = c.open('/options', method='OPTIONS')177+ rv = client.open('/options', method='OPTIONS')178 assert rv.status_code == 200179 assert random_uuid4 in rv.data.decode("utf-8")180 181 146-def test_werkzeug_routing():182+def test_werkzeug_routing(app, client):183 from werkzeug.routing import Submount, Rule148- app = flask.Flask(__name__)184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))2 unmodified lines190 return 'bar'191 192 def index():193 return 'index'194+195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197 162- c = app.test_client()163- assert c.get('/foo/').data == b'index'164- assert c.get('/foo/bar').data == b'bar'198+ assert client.get('/foo/').data == b'index'199+ assert client.get('/foo/bar').data == b'bar'200 201 167-def test_endpoint_decorator():202+def test_endpoint_decorator(app, client):203 from werkzeug.routing import Submount, Rule169- app = flask.Flask(__name__)204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))5 unmodified lines213 @app.endpoint('index')214 def index():215 return 'index'216 183- c = app.test_client()184- assert c.get('/foo/').data == b'index'185- assert c.get('/foo/bar').data == b'bar'217+ assert client.get('/foo/').data == b'index'218+ assert client.get('/foo/bar').data == b'bar'219 220 188-def test_session():189- app = flask.Flask(__name__)221+def test_session(app, client):222 app.secret_key = 'testkey'223 224 @app.route('/set', methods=['POST'])225 def set():3 unmodified lines229 @app.route('/get')230 def get():231 return flask.session['value']232 201- c = app.test_client()202- assert c.post('/set', data={'value': '42'}).data == b'value set'203- assert c.get('/get').data == b'42'233+ assert client.post('/set', data={'value': '42'}).data == b'value set'234+ assert client.get('/get').data == b'42'235 236 206-def test_session_using_server_name():207- app = flask.Flask(__name__)237+def test_session_using_server_name(app, client):238 app.config.update(239 SECRET_KEY='foo',240 SERVER_NAME='example.com'241 )1 unmodified line243 @app.route('/')244 def index():245 flask.session['testing'] = 42246 return 'Hello World'247+217- rv = app.test_client().get('/', 'http://example.com/')248+ rv = client.get('/', 'http://example.com/')249 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()250 assert 'httponly' in rv.headers['set-cookie'].lower()251 252 222-def test_session_using_server_name_and_port():223- app = flask.Flask(__name__)253+def test_session_using_server_name_and_port(app, client):254 app.config.update(255 SECRET_KEY='foo',256 SERVER_NAME='example.com:8080'257 )1 unmodified line259 @app.route('/')260 def index():261 flask.session['testing'] = 42262 return 'Hello World'263+233- rv = app.test_client().get('/', 'http://example.com:8080/')264+ rv = client.get('/', 'http://example.com:8080/')265 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()266 assert 'httponly' in rv.headers['set-cookie'].lower()267 268 238-def test_session_using_server_name_port_and_path():239- app = flask.Flask(__name__)269+def test_session_using_server_name_port_and_path(app, client):270 app.config.update(271 SECRET_KEY='foo',272 SERVER_NAME='example.com:8080',273 APPLICATION_ROOT='/foo'2 unmodified lines276 @app.route('/')277 def index():278 flask.session['testing'] = 42279 return 'Hello World'280+250- rv = app.test_client().get('/', 'http://example.com:8080/foo')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 256-def test_session_using_application_root():287+def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):258-289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292 293 def __call__(self, environ, start_response):294 environ['SCRIPT_NAME'] = self.prefix295 return self.app(environ, start_response)296 267- app = flask.Flask(__name__)297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')298 app.config.update(299 SECRET_KEY='foo',300 APPLICATION_ROOT='/bar'2 unmodified lines303 @app.route('/')304 def index():305 flask.session['testing'] = 42306 return 'Hello World'307+278- rv = app.test_client().get('/', 'http://example.com:8080/')308+ rv = client.get('/', 'http://example.com:8080/')309 assert 'path=/bar' in rv.headers['set-cookie'].lower()310 311 282-def test_session_using_session_settings():283- app = flask.Flask(__name__)312+def test_session_using_session_settings(app, client):313 app.config.update(314 SECRET_KEY='foo',315 SERVER_NAME='www.example.com:8080',316 APPLICATION_ROOT='/test',6 unmodified lines323 @app.route('/')324 def index():325 flask.session['testing'] = 42326 return 'Hello World'327+298- rv = app.test_client().get('/', 'http://www.example.com:8080/test/')328+ rv = client.get('/', 'http://www.example.com:8080/test/')329 cookie = rv.headers['set-cookie'].lower()330 assert 'domain=.example.com' in cookie331 assert 'path=/' in cookie332 assert 'secure' in cookie333 assert 'httponly' not in cookie334 335 336+def test_session_localhost_warning(recwarn, app, client):337+ app.config.update(338+ SECRET_KEY='testing',339+ SERVER_NAME='localhost:5000',340+ )341+342+ @app.route('/')343+ def index():344+ flask.session['testing'] = 42345+ return 'testing'346+347+ rv = client.get('/', 'http://localhost:5000/')348+ assert 'domain' not in rv.headers['set-cookie'].lower()349+ w = recwarn.pop(UserWarning)350+ assert '"localhost" is not a valid cookie domain' in str(w.message)351+352+353+def test_session_ip_warning(recwarn, app, client):354+ app.config.update(355+ SECRET_KEY='testing',356+ SERVER_NAME='127.0.0.1:5000',357+ )358+359+ @app.route('/')360+ def index():361+ flask.session['testing'] = 42362+ return 'testing'363+364+ rv = client.get('/', 'http://127.0.0.1:5000/')365+ assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366+ w = recwarn.pop(UserWarning)367+ assert 'cookie domain is an IP' in str(w.message)368+369+370 def test_missing_session():371 app = flask.Flask(__name__)372 373 def expect_exception(f, *args, **kwargs):374 e = pytest.raises(RuntimeError, f, *args, **kwargs)375 assert e.value.args and 'session is unavailable' in e.value.args[0]376+377 with app.test_request_context():378 assert flask.session.get('missing_key') is None379 expect_exception(flask.session.__setitem__, 'foo', 42)380 expect_exception(flask.session.pop, 'foo')381 382 318-def test_session_expiration():383+def test_session_expiration(app, client):384 permanent = True320- app = flask.Flask(__name__)385 app.secret_key = 'testkey'386 387 @app.route('/')388 def index():4 unmodified lines393 @app.route('/test')394 def test():395 return text_type(flask.session.permanent)396 333- client = app.test_client()397 rv = client.get('/')398 assert 'set-cookie' in rv.headers399 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])400 expires = parse_date(match.group())5 unmodified lines406 rv = client.get('/test')407 assert rv.data == b'True'408 409 permanent = False347- rv = app.test_client().get('/')410+ rv = client.get('/')411 assert 'set-cookie' in rv.headers412 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])413 assert match is None414 415 353-def test_session_stored_last():354- app = flask.Flask(__name__)416+def test_session_stored_last(app, client):417 app.secret_key = 'development-key'356- app.testing = True418 419 @app.after_request420 def modify_session(response):421 flask.session['foo'] = 422 unmodified lines424 @app.route('/')425 def dump_session_contents():426 return repr(flask.session.get('foo'))427 367- c = app.test_client()368- assert c.get('/').data == b'None'369- assert c.get('/').data == b'42'428+ assert client.get('/').data == b'None'429+ assert client.get('/').data == b'42'430 431 372-def test_session_special_types():373- app = flask.Flask(__name__)432+def test_session_special_types(app, client):433 app.secret_key = 'development-key'375- app.testing = True434 now = datetime.utcnow().replace(microsecond=0)435 the_uuid = uuid.uuid4()436 437 @app.after_request8 unmodified lines446 @app.route('/')447 def dump_session_contents():448 return pickle.dumps(dict(flask.session))449 392- c = app.test_client()393- c.get('/')394- rv = pickle.loads(c.get('/').data)450+ client.get('/')451+ rv = pickle.loads(client.get('/').data)452 assert rv['m'] == flask.Markup('Hello!')453 assert type(rv['m']) == flask.Markup454 assert rv['dt'] == now455 assert rv['u'] == the_uuid1 unmodified line457 assert type(rv['b']) == bytes458 assert rv['t'] == (1, 2, 3)459 460 404-def test_session_cookie_setting():405- app = flask.Flask(__name__)406- app.testing = True461+def test_session_cookie_setting(app):462 app.secret_key = 'dev key'463 is_permanent = True464 465 @app.route('/bump')33 unmodified lines499 app.config['SESSION_REFRESH_EACH_REQUEST'] = False500 run_test(expect_header=False)501 502 448-def test_flashes():449- app = flask.Flask(__name__)503+def test_session_vary_cookie(app, client):504 app.secret_key = 'testkey'505 452- with app.test_request_context():453- assert not flask.session.modified454- flask.flash('Zap')455- flask.session.modified = False456- flask.flash('Zip')457- assert flask.session.modified458- assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']506+ @app.route('/set')507+ def set_session():508+ flask.session['test'] = 'test'509+ return ''510 511+ @app.route('/get')512+ def get():513+ return flask.session.get('test')514 515+ @app.route('/getitem')516+ def getitem():517+ return flask.session['test']518+519+ @app.route('/setdefault')520+ def setdefault():521+ return flask.session.setdefault('test', 'default')522+523+ @app.route('/vary-cookie-header-set')524+ def vary_cookie_header_set():525+ response = flask.Response()526+ response.headers['Vary'] = 'Cookie'527+ flask.session['test'] = 'test'528+ return response529+530+ @app.route('/vary-header-set')531+ def vary_header_set():532+ response = flask.Response()533+ response.headers['Vary'] = 'Accept-Encoding, Accept-Language'534+ flask.session['test'] = 'test'535+ return response536+537+ @app.route('/no-vary-header')538+ def no_vary_header():539+ return ''540+541+ def expect(path, header_value='Cookie'):542+ rv = client.get(path)543+544+ if header_value:545+ # The 'Vary' key should exist in the headers only once.546+ assert len(rv.headers.get_all('Vary')) == 1547+ assert rv.headers['Vary'] == header_value548+ else:549+ assert 'Vary' not in rv.headers550+551+ expect('/set')552+ expect('/get')553+ expect('/getitem')554+ expect('/setdefault')555+ expect('/vary-cookie-header-set')556+ expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')557+ expect('/no-vary-header', None)558+559+560+def test_flashes(app, req_ctx):561+ app.secret_key = 'testkey'562+563+ assert not flask.session.modified564+ flask.flash('Zap')565+ flask.session.modified = False566+ flask.flash('Zip')567+ assert flask.session.modified568+ assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']569+570+461-def test_extended_flashing():571+def test_extended_flashing(app):572 # Be sure app.testing=True below, else tests can fail silently.573 #574 # Specifically, if app.testing is not set to True, the AssertionErrors575 # in the view functions will cause a 500 response to the test client576 # instead of propagating exceptions.577 468- app = flask.Flask(__name__)578 app.secret_key = 'testkey'470- app.testing = True579 580 @app.route('/')581 def index():582 flask.flash(u'Hello World')49 unmodified lines632 return ''633 634 # Create new test client on each test to clean flashed messages.635 528- c = app.test_client()529- c.get('/')530- c.get('/test/')636+ client = app.test_client()637+ client.get('/')638+ client.get('/test_with_categories/')639 532- c = app.test_client()533- c.get('/')534- c.get('/test_with_categories/')640+ client = app.test_client()641+ client.get('/')642+ client.get('/test_filter/')643 536- c = app.test_client()537- c.get('/')538- c.get('/test_filter/')644+ client = app.test_client()645+ client.get('/')646+ client.get('/test_filters/')647 540- c = app.test_client()541- c.get('/')542- c.get('/test_filters/')648+ client = app.test_client()649+ client.get('/')650+ client.get('/test_filters_without_returning_categories/')651 544- c = app.test_client()545- c.get('/')546- c.get('/test_filters_without_returning_categories/')652 548-549-def test_request_processing():653+def test_request_processing(app, client):550- app = flask.Flask(__name__)654 evts = []655 656 @app.before_request657 def before_request():9 unmodified lines667 def index():668 assert 'before' in evts669 assert 'after' not in evts670 return 'request'671+672 assert 'after' not in evts569- rv = app.test_client().get('/').data673+ rv = client.get('/').data674 assert 'after' in evts675 assert rv == b'request|after'676 677 574-def test_request_preprocessing_early_return():575- app = flask.Flask(__name__)678+def test_request_preprocessing_early_return(app, client):679 evts = []680 681 @app.before_request682 def before_request1():13 unmodified lines696 def index():697 evts.append('index')698 return "damnit"699 597- rv = app.test_client().get('/').data.strip()700+ rv = client.get('/').data.strip()701 assert rv == b'hello'702 assert evts == [1, 2]703 704 602-def test_after_request_processing():603- app = flask.Flask(__name__)604- app.testing = True605-705+def test_after_request_processing(app, client):706 @app.route('/')707 def index():708 @flask.after_this_request709 def foo(response):710 response.headers['X-Foo'] = 'a header'711 return response712+713 return 'Test'613- c = app.test_client()614- resp = c.get('/')714+715+ resp = client.get('/')716 assert resp.status_code == 200717 assert resp.headers['X-Foo'] == 'a header'718 719 619-def test_teardown_request_handler():720+def test_teardown_request_handler(app, client):721 called = []621- app = flask.Flask(__name__)722 723 @app.teardown_request724 def teardown_request(exc):725 called.append(True)1 unmodified line727 728 @app.route('/')729 def root():730 return "Response"631- rv = app.test_client().get('/')731+732+ rv = client.get('/')733 assert rv.status_code == 200734 assert b'Response' in rv.data735 assert len(called) == 1736 737 637-def test_teardown_request_handler_debug_mode():738+def test_teardown_request_handler_debug_mode(app, client):739 called = []639- app = flask.Flask(__name__)640- app.testing = True740 741 @app.teardown_request742 def teardown_request(exc):743 called.append(True)1 unmodified line745 746 @app.route('/')747 def root():748 return "Response"650- rv = app.test_client().get('/')749+750+ rv = client.get('/')751 assert rv.status_code == 200752 assert b'Response' in rv.data753 assert len(called) == 1754 755 656-def test_teardown_request_handler_error():756+def test_teardown_request_handler_error(app, client):757 called = []658- app = flask.Flask(__name__)758 app.config['LOGGER_HANDLER_POLICY'] = 'never'759+ app.testing = False760 761 @app.teardown_request762 def teardown_request1(exc):763 assert type(exc) == ZeroDivisionError20 unmodified lines784 785 @app.route('/')786 def fails():787 1 // 0688- rv = app.test_client().get('/')788+789+ rv = client.get('/')790 assert rv.status_code == 500791 assert b'Internal Server Error' in rv.data792 assert len(called) == 2793 794 694-def test_before_after_request_order():795+def test_before_after_request_order(app, client):796 called = []696- app = flask.Flask(__name__)797 798 @app.before_request799 def before1():800 called.append(1)22 unmodified lines823 824 @app.route('/')825 def index():826 return '42'727- rv = app.test_client().get('/')827+828+ rv = client.get('/')829 assert rv.data == b'42'830 assert called == [1, 2, 3, 4, 5, 6]831 832 732-def test_error_handling():733- app = flask.Flask(__name__)833+def test_error_handling(app, client):834 app.config['LOGGER_HANDLER_POLICY'] = 'never'835+ app.testing = False836 837 @app.errorhandler(404)838 def not_found(e):839 return 'not found', 40416 unmodified lines856 857 @app.route('/forbidden')858 def error2():859 flask.abort(403)759- c = app.test_client()760- rv = c.get('/')860+861+ rv = client.get('/')862 assert rv.status_code == 404863 assert rv.data == b'not found'763- rv = c.get('/error')864+ rv = client.get('/error')865 assert rv.status_code == 500866 assert b'internal server error' == rv.data766- rv = c.get('/forbidden')867+ rv = client.get('/forbidden')868 assert rv.status_code == 403869 assert b'forbidden' == rv.data870 871 771-def test_error_handling_processing():772- app = flask.Flask(__name__)872+def test_error_handling_processing(app, client):873 app.config['LOGGER_HANDLER_POLICY'] = 'never'874+ app.testing = False875 876 @app.errorhandler(500)877 def internal_server_error(e):878 return 'internal server error', 5006 unmodified lines885 def after_request(resp):886 resp.mimetype = 'text/x-special'887 return resp888 788- with app.test_client() as c:789- resp = c.get('/')790- assert resp.mimetype == 'text/x-special'791- assert resp.data == b'internal server error'889+ resp = client.get('/')890+ assert resp.mimetype == 'text/x-special'891+ assert resp.data == b'internal server error'892 893 794-def test_baseexception_error_handling():795- app = flask.Flask(__name__)894+def test_baseexception_error_handling(app, client):895 app.config['LOGGER_HANDLER_POLICY'] = 'never'896+ app.testing = False897 898 @app.route('/')899 def broken_func():900 raise KeyboardInterrupt()901 802- with app.test_client() as c:803- with pytest.raises(KeyboardInterrupt):804- c.get('/')902+ with pytest.raises(KeyboardInterrupt):903+ client.get('/')904 905 ctx = flask._request_ctx_stack.top906 assert ctx.preserved907 assert type(ctx._preserved_exc) is KeyboardInterrupt908 909 811-def test_before_request_and_routing_errors():812- app = flask.Flask(__name__)813-910+def test_before_request_and_routing_errors(app, client):911 @app.before_request912 def attach_something():913 flask.g.something = 'value'914 915 @app.errorhandler(404)916 def return_something(error):917 return flask.g.something, 404821- rv = app.test_client().get('/')918+919+ rv = client.get('/')920 assert rv.status_code == 404921 assert rv.data == b'value'922 923 826-def test_user_error_handling():924+def test_user_error_handling(app, client):925 class MyException(Exception):926 pass927 830- app = flask.Flask(__name__)831-928 @app.errorhandler(MyException)929 def handle_my_exception(e):930 assert isinstance(e, MyException)931 return '42'1 unmodified line933 @app.route('/')934 def index():935 raise MyException()936 841- c = app.test_client()842- assert c.get('/').data == b'42'937+ assert client.get('/').data == b'42'938 939 845-def test_http_error_subclass_handling():940+def test_http_error_subclass_handling(app, client):941 class ForbiddenSubclass(Forbidden):942 pass943 849- app = flask.Flask(__name__)850-944 @app.errorhandler(ForbiddenSubclass)945 def handle_forbidden_subclass(e):946 assert isinstance(e, ForbiddenSubclass)947 return 'banana'15 unmodified lines963 @app.route('/3')964 def index3():965 raise Forbidden()966 874- c = app.test_client()875- assert c.get('/1').data == b'banana'876- assert c.get('/2').data == b'apple'877- assert c.get('/3').data == b'apple'967+ assert client.get('/1').data == b'banana'968+ assert client.get('/2').data == b'apple'969+ assert client.get('/3').data == b'apple'970 971 880-def test_trapping_of_bad_request_key_errors():881- app = flask.Flask(__name__)882- app.testing = True883-972+def test_trapping_of_bad_request_key_errors(app, client):973 @app.route('/fail')974 def fail():975 flask.request.form['missing_key']887- c = app.test_client()888- assert c.get('/fail').status_code == 400976 977+ assert client.get('/fail').status_code == 400978+979 app.config['TRAP_BAD_REQUEST_ERRORS'] = True891- c = app.test_client()980 with pytest.raises(KeyError) as e:893- c.get("/fail")981+ client.get("/fail")982 assert e.errisinstance(BadRequest)983 984 897-def test_trapping_of_all_http_exceptions():898- app = flask.Flask(__name__)899- app.testing = True985+def test_trapping_of_all_http_exceptions(app, client):986 app.config['TRAP_HTTP_EXCEPTIONS'] = True987 988 @app.route('/fail')989 def fail():990 flask.abort(404)991 906- c = app.test_client()992 with pytest.raises(NotFound):908- c.get('/fail')993+ client.get('/fail')994 995 911-def test_enctype_debug_helper():996+def test_enctype_debug_helper(app, client):997 from flask.debughelpers import DebugFilesKeyError913- app = flask.Flask(__name__)998 app.debug = True999 1000 @app.route('/fail', methods=['POST'])1001 def index():1 unmodified line1003 1004 # with statement is important because we leave an exception on the1005 # stack otherwise and we want to ensure that this is not the case1006 # to not negatively affect other tests.923- with app.test_client() as c:1007+ with client:1008 with pytest.raises(DebugFilesKeyError) as e:925- c.post('/fail', data={'foo': 'index.txt'})1009+ client.post('/fail', data={'foo': 'index.txt'})1010 assert 'no file contents were transmitted' in str(e.value)1011 assert 'This was submitted: "index.txt"' in str(e.value)1012 1013 930-def test_response_creation():931- app = flask.Flask(__name__)932-933- @app.route('/unicode')934- def from_unicode():1014+def test_response_types(app, client):1015+ @app.route('/text')1016+ def from_text():1017 return u'Hällo Wörld'1018 937- @app.route('/string')938- def from_string():1019+ @app.route('/bytes')1020+ def from_bytes():1021 return u'Hällo Wörld'.encode('utf-8')1022 941- @app.route('/args')942- def from_tuple():1023+ @app.route('/full_tuple')1024+ def from_full_tuple():1025 return 'Meh', 400, {1026 'X-Foo': 'Testing',1027 'Content-Type': 'text/plain; charset=utf-8'1028 }1029 948- @app.route('/two_args')949- def from_two_args_tuple():1030+ @app.route('/text_headers')1031+ def from_text_headers():1032 return 'Hello', {1033 'X-Foo': 'Test',1034 'Content-Type': 'text/plain; charset=utf-8'1035 }1036 955- @app.route('/args_status')956- def from_status_tuple():1037+ @app.route('/text_status')1038+ def from_text_status():1039 return 'Hi, status!', 4001040 959- @app.route('/args_header')960- def from_response_instance_status_tuple():961- return flask.Response('Hello world', 404), {1041+ @app.route('/response_headers')1042+ def from_response_headers():1043+ return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1044 "X-Foo": "Bar",1045 "X-Bar": "Foo"1046 }1047 966- c = app.test_client()967- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')968- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')969- rv = c.get('/args')1048+ @app.route('/response_status')1049+ def from_response_status():1050+ return app.response_class('Hello world', 400), 5001051+1052+ @app.route('/wsgi')1053+ def from_wsgi():1054+ return NotFound()1055+1056+ assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1057+ assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1058+1059+ rv = client.get('/full_tuple')1060 assert rv.data == b'Meh'1061 assert rv.headers['X-Foo'] == 'Testing'1062 assert rv.status_code == 4001063 assert rv.mimetype == 'text/plain'974- rv2 = c.get('/two_args')975- assert rv2.data == b'Hello'976- assert rv2.headers['X-Foo'] == 'Test'977- assert rv2.status_code == 200978- assert rv2.mimetype == 'text/plain'979- rv3 = c.get('/args_status')980- assert rv3.data == b'Hi, status!'981- assert rv3.status_code == 400982- assert rv3.mimetype == 'text/html'983- rv4 = c.get('/args_header')984- assert rv4.data == b'Hello world'985- assert rv4.headers['X-Foo'] == 'Bar'986- assert rv4.headers['X-Bar'] == 'Foo'987- assert rv4.status_code == 4041064 1065+ rv = client.get('/text_headers')1066+ assert rv.data == b'Hello'1067+ assert rv.headers['X-Foo'] == 'Test'1068+ assert rv.status_code == 2001069+ assert rv.mimetype == 'text/plain'1070 990-def test_make_response():991- app = flask.Flask(__name__)992- with app.test_request_context():993- rv = flask.make_response()994- assert rv.status_code == 200995- assert rv.data == b''996- assert rv.mimetype == 'text/html'1071+ rv = client.get('/text_status')1072+ assert rv.data == b'Hi, status!'1073+ assert rv.status_code == 4001074+ assert rv.mimetype == 'text/html'1075 998- rv = flask.make_response('Awesome')999- assert rv.status_code == 2001000- assert rv.data == b'Awesome'1001- assert rv.mimetype == 'text/html'1076+ rv = client.get('/response_headers')1077+ assert rv.data == b'Hello world'1078+ assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1079+ assert rv.headers['X-Bar'] == 'Foo'1080+ assert rv.status_code == 4041081 1003- rv = flask.make_response('W00t', 404)1004- assert rv.status_code == 4041005- assert rv.data == b'W00t'1006- assert rv.mimetype == 'text/html'1082+ rv = client.get('/response_status')1083+ assert rv.data == b'Hello world'1084+ assert rv.status_code == 5001085 1086+ rv = client.get('/wsgi')1087+ assert b'Not Found' in rv.data1088+ assert rv.status_code == 4041089 1009-def test_make_response_with_response_instance():1090+1091+def test_response_type_errors():1092 app = flask.Flask(__name__)1011- with app.test_request_context():1012- rv = flask.make_response(1013- flask.jsonify({'msg': 'W00t'}), 400)1014- assert rv.status_code == 4001015- assert rv.data == b'{"msg":"W00t"}\n'1016- assert rv.mimetype == 'application/json'1093+ app.testing = True1094 1018- rv = flask.make_response(1019- flask.Response(''), 400)1020- assert rv.status_code == 4001021- assert rv.data == b''1022- assert rv.mimetype == 'text/html'1095+ @app.route('/none')1096+ def from_none():1097+ pass1098 1024- rv = flask.make_response(1025- flask.Response('', headers={'Content-Type': 'text/html'}),1026- 400, [('X-Foo', 'bar')])1027- assert rv.status_code == 4001028- assert rv.headers['Content-Type'] == 'text/html'1029- assert rv.headers['X-Foo'] == 'bar'1099+ @app.route('/small_tuple')1100+ def from_small_tuple():1101+ return 'Hello',1102 1103+ @app.route('/large_tuple')1104+ def from_large_tuple():1105+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1106 1032-def test_jsonify_no_prettyprint():1033- app = flask.Flask(__name__)1107+ @app.route('/bad_type')1108+ def from_bad_type():1109+ return True1110+1111+ @app.route('/bad_wsgi')1112+ def from_bad_wsgi():1113+ return lambda: None1114+1115+ c = app.test_client()1116+1117+ with pytest.raises(TypeError) as e:1118+ c.get('/none')1119+ assert 'returned None' in str(e)1120+1121+ with pytest.raises(TypeError) as e:1122+ c.get('/small_tuple')1123+ assert 'tuple must have the form' in str(e)1124+1125+ pytest.raises(TypeError, c.get, '/large_tuple')1126+1127+ with pytest.raises(TypeError) as e:1128+ c.get('/bad_type')1129+ assert 'it was a bool' in str(e)1130+1131+ pytest.raises(TypeError, c.get, '/bad_wsgi')1132+1133+1134+def test_make_response(app, req_ctx):1135+ rv = flask.make_response()1136+ assert rv.status_code == 2001137+ assert rv.data == b''1138+ assert rv.mimetype == 'text/html'1139+1140+ rv = flask.make_response('Awesome')1141+ assert rv.status_code == 2001142+ assert rv.data == b'Awesome'1143+ assert rv.mimetype == 'text/html'1144+1145+ rv = flask.make_response('W00t', 404)1146+ assert rv.status_code == 4041147+ assert rv.data == b'W00t'1148+ assert rv.mimetype == 'text/html'1149+1150+1151+def test_make_response_with_response_instance(app, req_ctx):1152+ rv = flask.make_response(1153+ flask.jsonify({'msg': 'W00t'}), 400)1154+ assert rv.status_code == 4001155+ assert rv.data == b'{"msg":"W00t"}\n'1156+ assert rv.mimetype == 'application/json'1157+1158+ rv = flask.make_response(1159+ flask.Response(''), 400)1160+ assert rv.status_code == 4001161+ assert rv.data == b''1162+ assert rv.mimetype == 'text/html'1163+1164+ rv = flask.make_response(1165+ flask.Response('', headers={'Content-Type': 'text/html'}),1166+ 400, [('X-Foo', 'bar')])1167+ assert rv.status_code == 4001168+ assert rv.headers['Content-Type'] == 'text/html'1169+ assert rv.headers['X-Foo'] == 'bar'1170+1171+1172+def test_jsonify_no_prettyprint(app, req_ctx):1173 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1035- with app.test_request_context():1036- compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1037- uncompressed_msg = {1038- "msg": {1039- "submsg": "W00t"1040- },1041- "msg2": "foobar"1042- }1174+ compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1175+ uncompressed_msg = {1176+ "msg": {1177+ "submsg": "W00t"1178+ },1179+ "msg2": "foobar"1180+ }1181 1044- rv = flask.make_response(1045- flask.jsonify(uncompressed_msg), 200)1046- assert rv.data == compressed_msg1182+ rv = flask.make_response(1183+ flask.jsonify(uncompressed_msg), 200)1184+ assert rv.data == compressed_msg1185 1186 1049-def test_jsonify_prettyprint():1050- app = flask.Flask(__name__)1187+def test_jsonify_prettyprint(app, req_ctx):1188 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1052- with app.test_request_context():1053- compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1054- pretty_response =\1055- b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1189+ compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1190+ pretty_response = \1191+ b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1192 1057- rv = flask.make_response(1058- flask.jsonify(compressed_msg), 200)1059- assert rv.data == pretty_response1193+ rv = flask.make_response(1194+ flask.jsonify(compressed_msg), 200)1195+ assert rv.data == pretty_response1196 1197 1062-def test_jsonify_mimetype():1063- app = flask.Flask(__name__)1198+def test_jsonify_mimetype(app, req_ctx):1199 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1065- with app.test_request_context():1066- msg = {1067- "msg": {"submsg": "W00t"},1068- }1069- rv = flask.make_response(1070- flask.jsonify(msg), 200)1071- assert rv.mimetype == 'application/vnd.api+json'1200+ msg = {1201+ "msg": {"submsg": "W00t"},1202+ }1203+ rv = flask.make_response(1204+ flask.jsonify(msg), 200)1205+ assert rv.mimetype == 'application/vnd.api+json'1206 1207 1074-def test_jsonify_args_and_kwargs_check():1075- app = flask.Flask(__name__)1076- with app.test_request_context():1077- with pytest.raises(TypeError) as e:1078- flask.jsonify('fake args', kwargs='fake')1079- assert 'behavior undefined' in str(e.value)1208+def test_jsonify_args_and_kwargs_check(app, req_ctx):1209+ with pytest.raises(TypeError) as e:1210+ flask.jsonify('fake args', kwargs='fake')1211+ assert 'behavior undefined' in str(e.value)1212 1213 1082-def test_url_generation():1083- app = flask.Flask(__name__)1084-1214+def test_url_generation(app, req_ctx):1215 @app.route('/hello/<name>', methods=['POST'])1216 def hello():1217 pass1088- with app.test_request_context():1089- assert flask.url_for('hello', name='test x') == '/hello/test%20x'1090- assert flask.url_for('hello', name='test x', _external=True) == \1091- 'http://localhost/hello/test%20x'1218 1219+ assert flask.url_for('hello', name='test x') == '/hello/test%20x'1220+ assert flask.url_for('hello', name='test x', _external=True) == \1221+ 'http://localhost/hello/test%20x'1222 1094-def test_build_error_handler():1095- app = flask.Flask(__name__)1223 1224+def test_build_error_handler(app):1225 # Test base case, a URL which results in a BuildError.1226 with app.test_request_context():1227 pytest.raises(BuildError, flask.url_for, 'spam')1228 12 unmodified lines1241 # Test a custom handler.1242 def handler(error, endpoint, values):1243 # Just a test.1244 return '/test_handler/'1245+1246 app.url_build_error_handlers.append(handler)1247 with app.test_request_context():1248 assert flask.url_for('spam') == '/test_handler/'1249 1250 1122-def test_build_error_handler_reraise():1123- app = flask.Flask(__name__)1124-1251+def test_build_error_handler_reraise(app):1252 # Test a custom handler which reraises the BuildError1253 def handler_raises_build_error(error, endpoint, values):1254 raise error1255+1256 app.url_build_error_handlers.append(handler_raises_build_error)1257 1258 with app.test_request_context():1259 pytest.raises(BuildError, flask.url_for, 'not.existing')1260 1261 1262+def test_url_for_passes_special_values_to_build_error_handler(app):1263+ @app.url_build_error_handlers.append1264+ def handler(error, endpoint, values):1265+ assert values == {1266+ '_external': False,1267+ '_anchor': None,1268+ '_method': None,1269+ '_scheme': None,1270+ }1271+ return 'handled'1272+1273+ with app.test_request_context():1274+ flask.url_for('/')1275+1276+1134-def test_custom_converters():1277+def test_custom_converters(app, client):1278 from werkzeug.routing import BaseConverter1279 1280 class ListConverter(BaseConverter):1138-1281 def to_python(self, value):1282 return value.split(',')1283 1284 def to_url(self, value):1285 base_to_url = super(ListConverter, self).to_url1286 return ','.join(base_to_url(x) for x in value)1145- app = flask.Flask(__name__)1287+1288 app.url_map.converters['list'] = ListConverter1289 1290 @app.route('/<list:args>')1291 def index(args):1292 return '|'.join(args)1151- c = app.test_client()1152- assert c.get('/1,2,3').data == b'1|2|3'1293 1294+ assert client.get('/1,2,3').data == b'1|2|3'1295 1155-def test_static_files():1156- app = flask.Flask(__name__)1157- app.testing = True1158- rv = app.test_client().get('/static/index.html')1296+1297+def test_static_files(app, client):1298+ rv = client.get('/static/index.html')1299 assert rv.status_code == 2001300 assert rv.data.strip() == b'<h1>Hello World!</h1>'1301 with app.test_request_context():1302 assert flask.url_for('static', filename='index.html') == \1163- '/static/index.html'1303+ '/static/index.html'1304 rv.close()1305 1306 1307 def test_static_path_deprecated(recwarn):19 unmodified lines1327 with app.test_request_context():1328 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1329 1330 1191-def test_none_response():1192- app = flask.Flask(__name__)1193- app.testing = True1331+def test_static_route_with_host_matching():1332+ app = flask.Flask(__name__, host_matching=True, static_host='example.com')1333+ c = app.test_client()1334+ rv = c.get('http://example.com/static/index.html')1335+ assert rv.status_code == 2001336+ rv.close()1337+ with app.test_request_context():1338+ rv = flask.url_for('static', filename='index.html', _external=True)1339+ assert rv == 'http://example.com/static/index.html'1340+ # Providing static_host without host_matching=True should error.1341+ with pytest.raises(Exception):1342+ flask.Flask(__name__, static_host='example.com')1343+ # Providing host_matching=True with static_folder but without static_host should error.1344+ with pytest.raises(Exception):1345+ flask.Flask(__name__, host_matching=True)1346+ # Providing host_matching=True without static_host but with static_folder=None should not error.1347+ flask.Flask(__name__, host_matching=True, static_folder=None)1348 1195- @app.route('/')1196- def test():1197- return None1198- try:1199- app.test_client().get('/')1200- except ValueError as e:1201- assert str(e) == 'View function did not return a response'1202- pass1203- else:1204- assert "Expected ValueError"1349 1206-1350 def test_request_locals():1351 assert repr(flask.g) == '<LocalProxy unbound>'1352 assert not flask.g1353 1354 1212-def test_test_app_proper_environ():1213- app = flask.Flask(__name__)1355+def test_test_app_proper_environ(app, client):1356 app.config.update(1357 SERVER_NAME='localhost.localdomain:5000'1358 )1359 4 unmodified lines1364 @app.route('/', subdomain='foo')1365 def subdomain():1366 return 'Foo SubDomain'1367 1226- rv = app.test_client().get('/')1368+ rv = client.get('/')1369 assert rv.data == b'Foo'1370 1229- rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1371+ rv = client.get('/', 'http://localhost.localdomain:5000')1372 assert rv.data == b'Foo'1373 1232- rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1374+ rv = client.get('/', 'https://localhost.localdomain:5000')1375 assert rv.data == b'Foo'1376 1377 app.config.update(SERVER_NAME='localhost.localdomain')1236- rv = app.test_client().get('/', 'https://localhost.localdomain')1378+ rv = client.get('/', 'https://localhost.localdomain')1379 assert rv.data == b'Foo'1380 1381 try:1382 app.config.update(SERVER_NAME='localhost.localdomain:443')1241- rv = app.test_client().get('/', 'https://localhost.localdomain')1383+ rv = client.get('/', 'https://localhost.localdomain')1384 # Werkzeug 0.81385 assert rv.status_code == 4041386 except ValueError as e:1387 # Werkzeug 0.74 unmodified lines1392 )1393 1394 try:1395 app.config.update(SERVER_NAME='localhost.localdomain')1254- rv = app.test_client().get('/', 'http://foo.localhost')1396+ rv = client.get('/', 'http://foo.localhost')1397 # Werkzeug 0.81398 assert rv.status_code == 4041399 except ValueError as e:1400 # Werkzeug 0.72 unmodified lines1403 "('localhost.localdomain') does not match the "1404 "server name from the WSGI environment ('foo.localhost')"1405 )1406 1265- rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1407+ rv = client.get('/', 'http://foo.localhost.localdomain')1408 assert rv.data == b'Foo SubDomain'1409 1410 1269-def test_exception_propagation():1411+def test_exception_propagation(app, client):1412 def apprunner(config_key):1271- app = flask.Flask(__name__)1413 app.config['LOGGER_HANDLER_POLICY'] = 'never'1414 1415 @app.route('/')1416 def index():1417 1 // 01277- c = app.test_client()1418+1419 if config_key is not None:1420 app.config[config_key] = True1421 with pytest.raises(Exception):1281- c.get('/')1422+ client.get('/')1423 else:1283- assert c.get('/').status_code == 5001424+ assert client.get('/').status_code == 5001425 1426 # we have to run this test in an isolated thread because if the1427 # debug flag is set to true and an exception happens the context is1428 # not torn down. This causes other tests that run after this fail8 unmodified lines1437 @pytest.mark.parametrize('use_debugger', [True, False])1438 @pytest.mark.parametrize('use_reloader', [True, False])1439 @pytest.mark.parametrize('propagate_exceptions', [None, True, False])1440 def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1300- use_reloader, propagate_exceptions):1441+ use_reloader, propagate_exceptions, app):1442 rv = {}1443 1444 # Mocks werkzeug.serving.run_simple method1445 def run_simple_mock(*args, **kwargs):1446 rv['passthrough_errors'] = kwargs.get('passthrough_errors')1447 1307- app = flask.Flask(__name__)1448 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1449 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1450 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1451 1452 1313-def test_max_content_length():1314- app = flask.Flask(__name__)1453+def test_max_content_length(app, client):1454 app.config['MAX_CONTENT_LENGTH'] = 641455 1456 @app.before_request1457 def always_first():8 unmodified lines1466 @app.errorhandler(413)1467 def catcher(error):1468 return '42'1469 1331- c = app.test_client()1332- rv = c.post('/accept', data={'myfile': 'foo' * 100})1470+ rv = client.post('/accept', data={'myfile': 'foo' * 100})1471 assert rv.data == b'42'1472 1473 1336-def test_url_processors():1337- app = flask.Flask(__name__)1474+def test_url_processors(app, client):1475 1476 @app.url_defaults1477 def add_language_code(endpoint, values):1478 if flask.g.lang_code is not None and \1342- app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1479+ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1480 values.setdefault('lang_code', flask.g.lang_code)1481 1482 @app.url_value_preprocessor1483 def pull_lang_code(endpoint, values):10 unmodified lines1494 @app.route('/foo')1495 def something_else():1496 return flask.url_for('about', lang_code='en')1497 1361- c = app.test_client()1498+ assert client.get('/de/').data == b'/de/about'1499+ assert client.get('/de/about').data == b'/foo'1500+ assert client.get('/foo').data == b'/en/about'1501 1363- assert c.get('/de/').data == b'/de/about'1364- assert c.get('/de/about').data == b'/foo'1365- assert c.get('/foo').data == b'/en/about'1502 1367-1368-def test_inject_blueprint_url_defaults():1503+def test_inject_blueprint_url_defaults(app):1369- app = flask.Flask(__name__)1504 bp = flask.Blueprint('foo.bar.baz', __name__,1505 template_folder='template')1506 1507 @bp.url_defaults16 unmodified lines1524 expected = '/login'1525 assert url == expected1526 1527 1394-def test_nonascii_pathinfo():1395- app = flask.Flask(__name__)1396- app.testing = True1397-1528+def test_nonascii_pathinfo(app, client):1529 @app.route(u'/киртест')1530 def index():1531 return 'Hello World!'1532 1402- c = app.test_client()1403- rv = c.get(u'/киртест')1533+ rv = client.get(u'/киртест')1534 assert rv.data == b'Hello World!'1535 1536 1407-def test_debug_mode_complains_after_first_request():1408- app = flask.Flask(__name__)1537+def test_debug_mode_complains_after_first_request(app, client):1538 app.debug = True1539 1540 @app.route('/')1541 def index():1542 return 'Awesome'1543+1544 assert not app.got_first_request1415- assert app.test_client().get('/').data == b'Awesome'1545+ assert client.get('/').data == b'Awesome'1546 with pytest.raises(AssertionError) as e:1547 @app.route('/foo')1548 def broken():1549 return 'Meh'3 unmodified lines1553 1554 @app.route('/foo')1555 def working():1556 return 'Meh'1557+1427- assert app.test_client().get('/foo').data == b'Meh'1558+ assert client.get('/foo').data == b'Meh'1559 assert app.got_first_request1560 1561 1431-def test_before_first_request_functions():1562+def test_before_first_request_functions(app, client):1563 got = []1433- app = flask.Flask(__name__)1564 1565 @app.before_first_request1566 def foo():1567 got.append(42)1438- c = app.test_client()1439- c.get('/')1568+1569+ client.get('/')1570 assert got == [42]1441- c.get('/')1571+ client.get('/')1572 assert got == [42]1573 assert app.got_first_request1574 1575 1446-def test_before_first_request_functions_concurrent():1576+def test_before_first_request_functions_concurrent(app, client):1577 got = []1448- app = flask.Flask(__name__)1578 1579 @app.before_first_request1580 def foo():1581 time.sleep(0.2)1582 got.append(42)1583 1455- c = app.test_client()1456-1584 def get_and_assert():1458- c.get("/")1585+ client.get("/")1586 assert got == [42]1587 1588 t = Thread(target=get_and_assert)1589 t.start()1 unmodified line1591 t.join()1592 assert app.got_first_request1593 1594 1468-def test_routing_redirect_debugging():1469- app = flask.Flask(__name__)1595+def test_routing_redirect_debugging(app, client):1596 app.debug = True1597 1598 @app.route('/foo/', methods=['GET', 'POST'])1599 def foo():1600 return 'success'1475- with app.test_client() as c:1601+1602+ with client:1603 with pytest.raises(AssertionError) as e:1477- c.post('/foo', data={})1604+ client.post('/foo', data={})1605 assert 'http://localhost/foo/' in str(e)1606 assert ('Make sure to directly send '1607 'your POST-request to this URL') in str(e)1608 1482- rv = c.get('/foo', data={}, follow_redirects=True)1609+ rv = client.get('/foo', data={}, follow_redirects=True)1610 assert rv.data == b'success'1611 1612 app.debug = False1486- with app.test_client() as c:1487- rv = c.post('/foo', data={}, follow_redirects=True)1613+ with client:1614+ rv = client.post('/foo', data={}, follow_redirects=True)1615 assert rv.data == b'success'1616 1617 1491-def test_route_decorator_custom_endpoint():1492- app = flask.Flask(__name__)1618+def test_route_decorator_custom_endpoint(app, client):1619 app.debug = True1620 1621 @app.route('/foo/')1622 def foo():11 unmodified lines1634 assert flask.url_for('foo') == '/foo/'1635 assert flask.url_for('bar') == '/bar/'1636 assert flask.url_for('123') == '/bar/123'1637 1512- c = app.test_client()1513- assert c.get('/foo/').data == b'foo'1514- assert c.get('/bar/').data == b'bar'1515- assert c.get('/bar/123').data == b'123'1638+ assert client.get('/foo/').data == b'foo'1639+ assert client.get('/bar/').data == b'bar'1640+ assert client.get('/bar/123').data == b'123'1641 1642 1518-def test_preserve_only_once():1519- app = flask.Flask(__name__)1643+def test_preserve_only_once(app, client):1644 app.debug = True1645 1646 @app.route('/fail')1647 def fail_func():1648 1 // 01649 1526- c = app.test_client()1650 for x in range(3):1651 with pytest.raises(ZeroDivisionError):1529- c.get('/fail')1652+ client.get('/fail')1653 1654 assert flask._request_ctx_stack.top is not None1655 assert flask._app_ctx_stack.top is not None1656 # implicit appctx disappears too1 unmodified line1658 assert flask._request_ctx_stack.top is None1659 assert flask._app_ctx_stack.top is None1660 1661 1539-def test_preserve_remembers_exception():1540- app = flask.Flask(__name__)1662+def test_preserve_remembers_exception(app, client):1663 app.debug = True1664 errors = []1665 1666 @app.route('/fail')7 unmodified lines1674 @app.teardown_request1675 def teardown_handler(exc):1676 errors.append(exc)1677 1556- c = app.test_client()1557-1678 # After this failure we did not yet call the teardown handler1679 with pytest.raises(ZeroDivisionError):1560- c.get('/fail')1680+ client.get('/fail')1681 assert errors == []1682 1683 # But this request triggers it, and it's an error1564- c.get('/success')1684+ client.get('/success')1685 assert len(errors) == 21686 assert isinstance(errors[0], ZeroDivisionError)1687 1688 # At this point another request does nothing.1569- c.get('/success')1689+ client.get('/success')1690 assert len(errors) == 31691 assert errors[1] is None1692 1693 1574-def test_get_method_on_g():1575- app = flask.Flask(__name__)1576- app.testing = True1694+def test_get_method_on_g(app_ctx):1695+ assert flask.g.get('x') is None1696+ assert flask.g.get('x', 11) == 111697+ flask.g.x = 421698+ assert flask.g.get('x') == 421699+ assert flask.g.x == 421700 1578- with app.app_context():1579- assert flask.g.get('x') is None1580- assert flask.g.get('x', 11) == 111581- flask.g.x = 421582- assert flask.g.get('x') == 421583- assert flask.g.x == 421701 1702+def test_g_iteration_protocol(app_ctx):1703+ flask.g.foo = 231704+ flask.g.bar = 421705+ assert 'foo' in flask.g1706+ assert 'foos' not in flask.g1707+ assert sorted(flask.g) == ['bar', 'foo']1708 1586-def test_g_iteration_protocol():1587- app = flask.Flask(__name__)1588- app.testing = True1709 1590- with app.app_context():1591- flask.g.foo = 231592- flask.g.bar = 421593- assert 'foo' in flask.g1594- assert 'foos' not in flask.g1595- assert sorted(flask.g) == ['bar', 'foo']1710+def test_subdomain_basic_support(app, client):1711+ app.config['SERVER_NAME'] = 'localhost.localdomain'1712 1597-1598-def test_subdomain_basic_support():1599- app = flask.Flask(__name__)1600- app.config['SERVER_NAME'] = 'localhost'1601-1713 @app.route('/')1714 def normal_index():1715 return 'normal index'1716 1717 @app.route('/', subdomain='test')1718 def test_index():1719 return 'test index'1720 1610- c = app.test_client()1611- rv = c.get('/', 'http://localhost/')1721+ rv = client.get('/', 'http://localhost.localdomain/')1722 assert rv.data == b'normal index'1723 1614- rv = c.get('/', 'http://test.localhost/')1724+ rv = client.get('/', 'http://test.localhost.localdomain/')1725 assert rv.data == b'test index'1726 1727 1618-def test_subdomain_matching():1619- app = flask.Flask(__name__)1620- app.config['SERVER_NAME'] = 'localhost'1728+def test_subdomain_matching(app, client):1729+ app.config['SERVER_NAME'] = 'localhost.localdomain'1730 1731 @app.route('/', subdomain='<user>')1732 def index(user):1733 return 'index for %s' % user1734 1626- c = app.test_client()1627- rv = c.get('/', 'http://mitsuhiko.localhost/')1735+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1736 assert rv.data == b'index for mitsuhiko'1737 1738 1631-def test_subdomain_matching_with_ports():1632- app = flask.Flask(__name__)1633- app.config['SERVER_NAME'] = 'localhost:3000'1739+def test_subdomain_matching_with_ports(app, client):1740+ app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1741 1742 @app.route('/', subdomain='<user>')1743 def index(user):1744 return 'index for %s' % user1745 1639- c = app.test_client()1640- rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1746+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1747 assert rv.data == b'index for mitsuhiko'1748 1749 1644-def test_multi_route_rules():1645- app = flask.Flask(__name__)1646-1750+def test_multi_route_rules(app, client):1751 @app.route('/')1752 @app.route('/<test>/')1753 def index(test='a'):1754 return test1755 1652- rv = app.test_client().open('/')1756+ rv = client.open('/')1757 assert rv.data == b'a'1654- rv = app.test_client().open('/b/')1758+ rv = client.open('/b/')1759 assert rv.data == b'b'1760 1761 1658-def test_multi_route_class_views():1762+def test_multi_route_class_views(app, client):1763 class View(object):1660-1764 def __init__(self, app):1765 app.add_url_rule('/', 'index', self.index)1766 app.add_url_rule('/<test>/', 'index', self.index)1767 1768 def index(self, test='a'):1769 return test1770 1668- app = flask.Flask(__name__)1771 _ = View(app)1670- rv = app.test_client().open('/')1772+ rv = client.open('/')1773 assert rv.data == b'a'1672- rv = app.test_client().open('/b/')1774+ rv = client.open('/b/')1775 assert rv.data == b'b'1776 1777 1676-def test_run_defaults(monkeypatch):1778+def test_run_defaults(monkeypatch, app):1779 rv = {}1780 1781 # Mocks werkzeug.serving.run_simple method1782 def run_simple_mock(*args, **kwargs):1783 rv['result'] = 'running...'1784 1683- app = flask.Flask(__name__)1785 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1786 app.run()1787 assert rv['result'] == 'running...'1788 1789 1689-def test_run_server_port(monkeypatch):1790+def test_run_server_port(monkeypatch, app):1791 rv = {}1792 1793 # Mocks werkzeug.serving.run_simple method1794 def run_simple_mock(hostname, port, application, *args, **kwargs):1795 rv['result'] = 'running on %s:%s ...' % (hostname, port)1796 1696- app = flask.Flask(__name__)1797 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1798 hostname, port = 'localhost', 80001799 app.run(hostname, port, debug=True)1800 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1801 1802 1803 @pytest.mark.parametrize('host,port,expect_host,expect_port', (1704- (None, None, 'pocoo.org', 8080),1705- ('localhost', None, 'localhost', 8080),1706- (None, 80, 'pocoo.org', 80),1707- ('localhost', 80, 'localhost', 80),1804+ (None, None, 'pocoo.org', 8080),1805+ ('localhost', None, 'localhost', 8080),1806+ (None, 80, 'pocoo.org', 80),1807+ ('localhost', 80, 'localhost', 80),1808 ))1709-def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1809+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1810 def run_simple_mock(hostname, port, *args, **kwargs):1811 assert hostname == expect_host1812 assert port == expect_port1813 1814 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1715- app = flask.Flask(__name__)1815 app.config['SERVER_NAME'] = 'pocoo.org:8080'1816 app.run(host, port)modified:tests/test_blueprints.py+355 added-109 removed
16 unmodified lines17 from werkzeug.http import parse_cache_control_header18 from jinja2 import TemplateNotFound19 20 21-def test_blueprint_specific_error_handling():21+def test_blueprint_specific_error_handling(app, client):22 frontend = flask.Blueprint('frontend', __name__)23 backend = flask.Blueprint('backend', __name__)24 sideend = flask.Blueprint('sideend', __name__)25 16 unmodified lines42 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)45 46- app = flask.Flask(__name__)46 app.register_blueprint(frontend)47 app.register_blueprint(backend)48 app.register_blueprint(sideend)49 50 @app.errorhandler(403)51 def app_forbidden(e):52 return 'application itself says no', 40353 55- c = app.test_client()54+ assert client.get('/frontend-no').data == b'frontend says no'55+ assert client.get('/backend-no').data == b'backend says no'56+ assert client.get('/what-is-a-sideend').data == b'application itself says no'57 57- assert c.get('/frontend-no').data == b'frontend says no'58- assert c.get('/backend-no').data == b'backend says no'59- assert c.get('/what-is-a-sideend').data == b'application itself says no'58 61-def test_blueprint_specific_user_error_handling():59+def test_blueprint_specific_user_error_handling(app, client):60 class MyDecoratorException(Exception):61 pass62+63 class MyFunctionException(Exception):64 pass65 66 blue = flask.Blueprint('blue', __name__)5 unmodified lines72 73 def my_function_exception_handler(e):74 assert isinstance(e, MyFunctionException)75 return 'bam'76+77 blue.register_error_handler(MyFunctionException, my_function_exception_handler)78 79 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()82+83 @blue.route('/function')84 def blue_func_test():85 raise MyFunctionException()86 86- app = flask.Flask(__name__)87 app.register_blueprint(blue)88 89- c = app.test_client()89+ assert client.get('/decorator').data == b'boom'90+ assert client.get('/function').data == b'bam'91 91- assert c.get('/decorator').data == b'boom'92- assert c.get('/function').data == b'bam'92 94-def test_blueprint_url_definitions():93+def test_blueprint_app_error_handling(app, client):94+ errors = flask.Blueprint('errors', __name__)95+96+ @errors.app_errorhandler(403)97+ def forbidden_handler(e):98+ return 'you shall not pass', 40399+100+ @app.route('/forbidden')101+ def app_forbidden():102+ flask.abort(403)103+104+ forbidden_bp = flask.Blueprint('forbidden_bp', __name__)105+106+ @forbidden_bp.route('/nope')107+ def bp_forbidden():108+ flask.abort(403)109+110+ app.register_blueprint(errors)111+ app.register_blueprint(forbidden_bp)112+113+ assert client.get('/forbidden').data == b'you shall not pass'114+ assert client.get('/nope').data == b'you shall not pass'115+116+117+def test_blueprint_url_definitions(app, client):118 bp = flask.Blueprint('test', __name__)119 120 @bp.route('/foo', defaults={'baz': 42})121 def foo(bar, baz):2 unmodified lines124 @bp.route('/bar')125 def bar(bar):126 return text_type(bar)127 105- app = flask.Flask(__name__)128 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})129 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})130 109- c = app.test_client()110- assert c.get('/1/foo').data == b'23/42'111- assert c.get('/2/foo').data == b'19/42'112- assert c.get('/1/bar').data == b'23'113- assert c.get('/2/bar').data == b'19'131+ assert client.get('/1/foo').data == b'23/42'132+ assert client.get('/2/foo').data == b'19/42'133+ assert client.get('/1/bar').data == b'23'134+ assert client.get('/2/bar').data == b'19'135 136+115-def test_blueprint_url_processors():137+def test_blueprint_url_processors(app, client):138 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')139 140 @bp.url_defaults141 def add_language_code(endpoint, values):10 unmodified lines152 @bp.route('/about')153 def about():154 return flask.url_for('.index')155 134- app = flask.Flask(__name__)156 app.register_blueprint(bp)157 137- c = app.test_client()158+ assert client.get('/de/').data == b'/de/about'159+ assert client.get('/de/about').data == b'/de/'160 139- assert c.get('/de/').data == b'/de/about'140- assert c.get('/de/about').data == b'/de/'161 162 def test_templates_and_static(test_apps):163 from blueprintapp import app144- c = app.test_client()164+ client = app.test_client()165 146- rv = c.get('/')166+ rv = client.get('/')167 assert rv.data == b'Hello from the Frontend'148- rv = c.get('/admin/')168+ rv = client.get('/admin/')169 assert rv.data == b'Hello from the Admin'150- rv = c.get('/admin/index2')170+ rv = client.get('/admin/index2')171 assert rv.data == b'Hello from the Admin'152- rv = c.get('/admin/static/test.txt')172+ rv = client.get('/admin/static/test.txt')173 assert rv.data.strip() == b'Admin File'174 rv.close()155- rv = c.get('/admin/static/css/test.css')175+ rv = client.get('/admin/static/css/test.css')176 assert rv.data.strip() == b'/* nested file */'177 rv.close()178 179 # try/finally, in case other tests use this app for Blueprint tests.2 unmodified lines182 expected_max_age = 3600183 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:184 expected_max_age = 7200185 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age166- rv = c.get('/admin/static/css/test.css')186+ rv = client.get('/admin/static/css/test.css')187 cc = parse_cache_control_header(rv.headers['Cache-Control'])188 assert cc.max_age == expected_max_age189 rv.close()190 finally:9 unmodified lines200 201 with flask.Flask(__name__).test_request_context():202 assert flask.render_template('nested/nested.txt') == 'I\'m nested'203 184-def test_default_static_cache_timeout():185- app = flask.Flask(__name__)204+205+def test_default_static_cache_timeout(app):206 class MyBlueprint(flask.Blueprint):207 def get_send_file_max_age(self, filename):208 return 100209 14 unmodified lines224 rv.close()225 finally:226 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default227 228+229 def test_templates_list(test_apps):230 from blueprintapp import app231 templates = sorted(app.jinja_env.list_templates())232 assert templates == ['admin/index.html', 'frontend/index.html']233 234+213-def test_dotted_names():235+def test_dotted_names(app, client):236 frontend = flask.Blueprint('myapp.frontend', __name__)237 backend = flask.Blueprint('myapp.backend', __name__)238 239 @frontend.route('/fe')7 unmodified lines247 @backend.route('/be')248 def backend_index():249 return flask.url_for('myapp.frontend.frontend_index')250 229- app = flask.Flask(__name__)251 app.register_blueprint(frontend)252 app.register_blueprint(backend)253 233- c = app.test_client()234- assert c.get('/fe').data.strip() == b'/be'235- assert c.get('/fe2').data.strip() == b'/fe'236- assert c.get('/be').data.strip() == b'/fe'254+ assert client.get('/fe').data.strip() == b'/be'255+ assert client.get('/fe2').data.strip() == b'/fe'256+ assert client.get('/be').data.strip() == b'/fe'257 238-def test_dotted_names_from_app():239- app = flask.Flask(__name__)240- app.testing = True258+259+def test_dotted_names_from_app(app, client):260 test = flask.Blueprint('test', __name__)261 262 @app.route('/')263 def app_index():4 unmodified lines268 return flask.url_for('app_index')269 270 app.register_blueprint(test)271 253- with app.test_client() as c:254- rv = c.get('/')255- assert rv.data == b'/test/'272+ rv = client.get('/')273+ assert rv.data == b'/test/'274 275+257-def test_empty_url_defaults():276+def test_empty_url_defaults(app, client):277 bp = flask.Blueprint('bp', __name__)278 279 @bp.route('/', defaults={'page': 1})280 @bp.route('/page/<int:page>')281 def something(page):282 return str(page)283 265- app = flask.Flask(__name__)284 app.register_blueprint(bp)285 268- c = app.test_client()269- assert c.get('/').data == b'1'270- assert c.get('/page/2').data == b'2'286+ assert client.get('/').data == b'1'287+ assert client.get('/page/2').data == b'2'288 272-def test_route_decorator_custom_endpoint():289 290+def test_route_decorator_custom_endpoint(app, client):291 bp = flask.Blueprint('bp', __name__)292 293 @bp.route('/foo')294 def foo():10 unmodified lines305 @bp.route('/bar/foo')306 def bar_foo():307 return flask.request.endpoint308 292- app = flask.Flask(__name__)309 app.register_blueprint(bp, url_prefix='/py')310 311 @app.route('/')312 def index():313 return flask.request.endpoint314 299- c = app.test_client()300- assert c.get('/').data == b'index'301- assert c.get('/py/foo').data == b'bp.foo'302- assert c.get('/py/bar').data == b'bp.bar'303- assert c.get('/py/bar/123').data == b'bp.123'304- assert c.get('/py/bar/foo').data == b'bp.bar_foo'315+ assert client.get('/').data == b'index'316+ assert client.get('/py/foo').data == b'bp.foo'317+ assert client.get('/py/bar').data == b'bp.bar'318+ assert client.get('/py/bar/123').data == b'bp.123'319+ assert client.get('/py/bar/foo').data == b'bp.bar_foo'320 321+306-def test_route_decorator_custom_endpoint_with_dots():322+def test_route_decorator_custom_endpoint_with_dots(app, client):323 bp = flask.Blueprint('bp', __name__)324 325 @bp.route('/foo')326 def foo():32 unmodified lines359 bp.route('/bar/123', endpoint='bar.123'),360 lambda: None361 )362 347- app = flask.Flask(__name__)363 app.register_blueprint(bp, url_prefix='/py')364 350- c = app.test_client()351- assert c.get('/py/foo').data == b'bp.foo'365+ assert client.get('/py/foo').data == b'bp.foo'366 # The rule's didn't actually made it through353- rv = c.get('/py/bar')367+ rv = client.get('/py/bar')368 assert rv.status_code == 404355- rv = c.get('/py/bar/123')369+ rv = client.get('/py/bar/123')370 assert rv.status_code == 404371 358-def test_template_filter():372+373+def test_endpoint_decorator(app, client):374+ from werkzeug.routing import Rule375+ app.url_map.add(Rule('/foo', endpoint='bar'))376+377 bp = flask.Blueprint('bp', __name__)378+379+ @bp.endpoint('bar')380+ def foobar():381+ return flask.request.endpoint382+383+ app.register_blueprint(bp, url_prefix='/bp_prefix')384+385+ assert client.get('/foo').data == b'bar'386+ assert client.get('/bp_prefix/bar').status_code == 404387+388+389+def test_template_filter(app):390+ bp = flask.Blueprint('bp', __name__)391+392 @bp.app_template_filter()393 def my_reverse(s):394 return s[::-1]363- app = flask.Flask(__name__)395+396 app.register_blueprint(bp, url_prefix='/py')397 assert 'my_reverse' in app.jinja_env.filters.keys()398 assert app.jinja_env.filters['my_reverse'] == my_reverse399 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'400 401+369-def test_add_template_filter():402+def test_add_template_filter(app):403 bp = flask.Blueprint('bp', __name__)404+405 def my_reverse(s):406 return s[::-1]407+408 bp.add_app_template_filter(my_reverse)374- app = flask.Flask(__name__)409 app.register_blueprint(bp, url_prefix='/py')410 assert 'my_reverse' in app.jinja_env.filters.keys()411 assert app.jinja_env.filters['my_reverse'] == my_reverse412 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'413 414+380-def test_template_filter_with_name():415+def test_template_filter_with_name(app):416 bp = flask.Blueprint('bp', __name__)417+418 @bp.app_template_filter('strrev')419 def my_reverse(s):420 return s[::-1]385- app = flask.Flask(__name__)421+422 app.register_blueprint(bp, url_prefix='/py')423 assert 'strrev' in app.jinja_env.filters.keys()424 assert app.jinja_env.filters['strrev'] == my_reverse425 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'426 427+391-def test_add_template_filter_with_name():428+def test_add_template_filter_with_name(app):429 bp = flask.Blueprint('bp', __name__)430+431 def my_reverse(s):432 return s[::-1]433+434 bp.add_app_template_filter(my_reverse, 'strrev')396- app = flask.Flask(__name__)435 app.register_blueprint(bp, url_prefix='/py')436 assert 'strrev' in app.jinja_env.filters.keys()437 assert app.jinja_env.filters['strrev'] == my_reverse438 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'439 440+402-def test_template_filter_with_template():441+def test_template_filter_with_template(app, client):442 bp = flask.Blueprint('bp', __name__)443+444 @bp.app_template_filter()445 def super_reverse(s):446 return s[::-1]407- app = flask.Flask(__name__)447+448 app.register_blueprint(bp, url_prefix='/py')449+450 @app.route('/')451 def index():452 return flask.render_template('template_filter.html', value='abcd')412- rv = app.test_client().get('/')453+454+ rv = client.get('/')455 assert rv.data == b'dcba'456 415-def test_template_filter_after_route_with_template():416- app = flask.Flask(__name__)457+458+def test_template_filter_after_route_with_template(app, client):459 @app.route('/')460 def index():461 return flask.render_template('template_filter.html', value='abcd')462+463 bp = flask.Blueprint('bp', __name__)464+465 @bp.app_template_filter()466 def super_reverse(s):467 return s[::-1]468+469 app.register_blueprint(bp, url_prefix='/py')425- rv = app.test_client().get('/')470+ rv = client.get('/')471 assert rv.data == b'dcba'472 473+428-def test_add_template_filter_with_template():474+def test_add_template_filter_with_template(app, client):475 bp = flask.Blueprint('bp', __name__)476+477 def super_reverse(s):478 return s[::-1]479+480 bp.add_app_template_filter(super_reverse)433- app = flask.Flask(__name__)481 app.register_blueprint(bp, url_prefix='/py')482+483 @app.route('/')484 def index():485 return flask.render_template('template_filter.html', value='abcd')438- rv = app.test_client().get('/')486+487+ rv = client.get('/')488 assert rv.data == b'dcba'489 490+441-def test_template_filter_with_name_and_template():491+def test_template_filter_with_name_and_template(app, client):492 bp = flask.Blueprint('bp', __name__)493+494 @bp.app_template_filter('super_reverse')495 def my_reverse(s):496 return s[::-1]446- app = flask.Flask(__name__)497+498 app.register_blueprint(bp, url_prefix='/py')499+500 @app.route('/')501 def index():502 return flask.render_template('template_filter.html', value='abcd')451- rv = app.test_client().get('/')503+504+ rv = client.get('/')505 assert rv.data == b'dcba'506 507+454-def test_add_template_filter_with_name_and_template():508+def test_add_template_filter_with_name_and_template(app, client):509 bp = flask.Blueprint('bp', __name__)510+511 def my_reverse(s):512 return s[::-1]513+514 bp.add_app_template_filter(my_reverse, 'super_reverse')459- app = flask.Flask(__name__)515 app.register_blueprint(bp, url_prefix='/py')516+517 @app.route('/')518 def index():519 return flask.render_template('template_filter.html', value='abcd')464- rv = app.test_client().get('/')520+521+ rv = client.get('/')522 assert rv.data == b'dcba'523 524+467-def test_template_test():525+def test_template_test(app):526 bp = flask.Blueprint('bp', __name__)527+528 @bp.app_template_test()529 def is_boolean(value):530 return isinstance(value, bool)472- app = flask.Flask(__name__)531+532 app.register_blueprint(bp, url_prefix='/py')533 assert 'is_boolean' in app.jinja_env.tests.keys()534 assert app.jinja_env.tests['is_boolean'] == is_boolean535 assert app.jinja_env.tests['is_boolean'](False)536 537+478-def test_add_template_test():538+def test_add_template_test(app):539 bp = flask.Blueprint('bp', __name__)540+541 def is_boolean(value):542 return isinstance(value, bool)543+544 bp.add_app_template_test(is_boolean)483- app = flask.Flask(__name__)545 app.register_blueprint(bp, url_prefix='/py')546 assert 'is_boolean' in app.jinja_env.tests.keys()547 assert app.jinja_env.tests['is_boolean'] == is_boolean548 assert app.jinja_env.tests['is_boolean'](False)549 550+489-def test_template_test_with_name():551+def test_template_test_with_name(app):552 bp = flask.Blueprint('bp', __name__)553+554 @bp.app_template_test('boolean')555 def is_boolean(value):556 return isinstance(value, bool)494- app = flask.Flask(__name__)557+558 app.register_blueprint(bp, url_prefix='/py')559 assert 'boolean' in app.jinja_env.tests.keys()560 assert app.jinja_env.tests['boolean'] == is_boolean561 assert app.jinja_env.tests['boolean'](False)562 563+500-def test_add_template_test_with_name():564+def test_add_template_test_with_name(app):565 bp = flask.Blueprint('bp', __name__)566+567 def is_boolean(value):568 return isinstance(value, bool)569+570 bp.add_app_template_test(is_boolean, 'boolean')505- app = flask.Flask(__name__)571 app.register_blueprint(bp, url_prefix='/py')572 assert 'boolean' in app.jinja_env.tests.keys()573 assert app.jinja_env.tests['boolean'] == is_boolean574 assert app.jinja_env.tests['boolean'](False)575 576+511-def test_template_test_with_template():577+def test_template_test_with_template(app, client):578 bp = flask.Blueprint('bp', __name__)579+580 @bp.app_template_test()581 def boolean(value):582 return isinstance(value, bool)516- app = flask.Flask(__name__)583+584 app.register_blueprint(bp, url_prefix='/py')585+586 @app.route('/')587 def index():588 return flask.render_template('template_test.html', value=False)521- rv = app.test_client().get('/')589+590+ rv = client.get('/')591 assert b'Success!' in rv.data592 524-def test_template_test_after_route_with_template():525- app = flask.Flask(__name__)593+594+def test_template_test_after_route_with_template(app, client):595 @app.route('/')596 def index():597 return flask.render_template('template_test.html', value=False)598+599 bp = flask.Blueprint('bp', __name__)600+601 @bp.app_template_test()602 def boolean(value):603 return isinstance(value, bool)604+605 app.register_blueprint(bp, url_prefix='/py')534- rv = app.test_client().get('/')606+ rv = client.get('/')607 assert b'Success!' in rv.data608 609+537-def test_add_template_test_with_template():610+def test_add_template_test_with_template(app, client):611 bp = flask.Blueprint('bp', __name__)612+613 def boolean(value):614 return isinstance(value, bool)615+616 bp.add_app_template_test(boolean)542- app = flask.Flask(__name__)617 app.register_blueprint(bp, url_prefix='/py')618+619 @app.route('/')620 def index():621 return flask.render_template('template_test.html', value=False)547- rv = app.test_client().get('/')622+623+ rv = client.get('/')624 assert b'Success!' in rv.data625 626+550-def test_template_test_with_name_and_template():627+def test_template_test_with_name_and_template(app, client):628 bp = flask.Blueprint('bp', __name__)629+630 @bp.app_template_test('boolean')631 def is_boolean(value):632 return isinstance(value, bool)555- app = flask.Flask(__name__)633+634 app.register_blueprint(bp, url_prefix='/py')635+636 @app.route('/')637 def index():638 return flask.render_template('template_test.html', value=False)560- rv = app.test_client().get('/')639+640+ rv = client.get('/')641 assert b'Success!' in rv.data642 643+563-def test_add_template_test_with_name_and_template():644+def test_add_template_test_with_name_and_template(app, client):645 bp = flask.Blueprint('bp', __name__)646+647 def is_boolean(value):648 return isinstance(value, bool)649+650 bp.add_app_template_test(is_boolean, 'boolean')568- app = flask.Flask(__name__)651 app.register_blueprint(bp, url_prefix='/py')652+653 @app.route('/')654 def index():655 return flask.render_template('template_test.html', value=False)573- rv = app.test_client().get('/')656+657+ rv = client.get('/')658 assert b'Success!' in rv.data659+660+661+def test_context_processing(app, client):662+ answer_bp = flask.Blueprint('answer_bp', __name__)663+664+ template_string = lambda: flask.render_template_string(665+ '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'666+ '{% if answer %}{{ answer }} is the answer.{% endif %}'667+ )668+669+ # App global context processor670+ @answer_bp.app_context_processor671+ def not_answer_context_processor():672+ return {'notanswer': 43}673+674+ # Blueprint local context processor675+ @answer_bp.context_processor676+ def answer_context_processor():677+ return {'answer': 42}678+679+ # Setup endpoints for testing680+ @answer_bp.route('/bp')681+ def bp_page():682+ return template_string()683+684+ @app.route('/')685+ def app_page():686+ return template_string()687+688+ # Register the blueprint689+ app.register_blueprint(answer_bp)690+691+ app_page_bytes = client.get('/').data692+ answer_page_bytes = client.get('/bp').data693+694+ assert b'43' in app_page_bytes695+ assert b'42' not in app_page_bytes696+697+ assert b'42' in answer_page_bytes698+ assert b'43' in answer_page_bytes699+700+701+def test_template_global(app):702+ bp = flask.Blueprint('bp', __name__)703+704+ @bp.app_template_global()705+ def get_answer():706+ return 42707+708+ # Make sure the function is not in the jinja_env already709+ assert 'get_answer' not in app.jinja_env.globals.keys()710+ app.register_blueprint(bp)711+712+ # Tests713+ assert 'get_answer' in app.jinja_env.globals.keys()714+ assert app.jinja_env.globals['get_answer'] is get_answer715+ assert app.jinja_env.globals['get_answer']() == 42716+717+ with app.app_context():718+ rv = flask.render_template_string('{{ get_answer() }}')719+ assert rv == '42'720+721+722+def test_request_processing(app, client):723+ bp = flask.Blueprint('bp', __name__)724+ evts = []725+726+ @bp.before_request727+ def before_bp():728+ evts.append('before')729+730+ @bp.after_request731+ def after_bp(response):732+ response.data += b'|after'733+ evts.append('after')734+ return response735+736+ @bp.teardown_request737+ def teardown_bp(exc):738+ evts.append('teardown')739+740+ # Setup routes for testing741+ @bp.route('/bp')742+ def bp_endpoint():743+ return 'request'744+745+ app.register_blueprint(bp)746+747+ assert evts == []748+ rv = client.get('/bp')749+ assert rv.data == b'request|after'750+ assert evts == ['before', 'after', 'teardown']751+752+753+def test_app_request_processing(app, client):754+ bp = flask.Blueprint('bp', __name__)755+ evts = []756+757+ @bp.before_app_first_request758+ def before_first_request():759+ evts.append('first')760+761+ @bp.before_app_request762+ def before_app():763+ evts.append('before')764+765+ @bp.after_app_request766+ def after_app(response):767+ response.data += b'|after'768+ evts.append('after')769+ return response770+771+ @bp.teardown_app_request772+ def teardown_app(exc):773+ evts.append('teardown')774+775+ app.register_blueprint(bp)776+777+ # Setup routes for testing778+ @app.route('/')779+ def bp_endpoint():780+ return 'request'781+782+ # before first request783+ assert evts == []784+785+ # first request786+ resp = client.get('/').data787+ assert resp == b'request|after'788+ assert evts == ['first', 'before', 'after', 'teardown']789+790+ # second request791+ resp = client.get('/').data792+ assert resp == b'request|after'793+ assert evts == ['first'] + ['before', 'after', 'teardown'] * 2794+795+796+def test_app_url_processors(app, client):797+ bp = flask.Blueprint('bp', __name__)798+799+ # Register app-wide url defaults and preprocessor on blueprint800+ @bp.app_url_defaults801+ def add_language_code(endpoint, values):802+ values.setdefault('lang_code', flask.g.lang_code)803+804+ @bp.app_url_value_preprocessor805+ def pull_lang_code(endpoint, values):806+ flask.g.lang_code = values.pop('lang_code')807+808+ # Register route rules at the app level809+ @app.route('/<lang_code>/')810+ def index():811+ return flask.url_for('about')812+813+ @app.route('/<lang_code>/about')814+ def about():815+ return flask.url_for('index')816+817+ app.register_blueprint(bp)818+819+ assert client.get('/de/').data == b'/de/about'820+ assert client.get('/de/about').data == b'/de/'modified:tests/test_cli.py+157 added-21 removed
12 unmodified lines13 #14 from __future__ import absolute_import, print_function15 import os16 import sys17+from functools import partial18 19 import click20 import pytest21 from click.testing import CliRunner22 from flask import Flask, current_app23 23-from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24+from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version27 28 29+@pytest.fixture30+def runner():31+ return CliRunner()32+33+34 def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name38 39 40 def test_find_best_app(test_apps):41 """Test if `find_best_app` behaves as expected with different combinations of input."""42+ script_info = ScriptInfo()43+44 class Module:45 app = Flask('appname')38- assert find_best_app(Module) == Module.app46 47+ assert find_best_app(script_info, Module) == Module.app48+49 class Module:50 application = Flask('appname')42- assert find_best_app(Module) == Module.application51 52+ assert find_best_app(script_info, Module) == Module.application53+54 class Module:55 myapp = Flask('appname')46- assert find_best_app(Module) == Module.myapp56 57+ assert find_best_app(script_info, Module) == Module.myapp58+59 class Module:60+ @staticmethod61+ def create_app():62+ return Flask('appname')63+64+ assert isinstance(find_best_app(script_info, Module), Flask)65+ assert find_best_app(script_info, Module).name == 'appname'66+67+ class Module:68+ @staticmethod69+ def create_app(foo):70+ return Flask('appname')71+72+ assert isinstance(find_best_app(script_info, Module), Flask)73+ assert find_best_app(script_info, Module).name == 'appname'74+75+ class Module:76+ @staticmethod77+ def create_app(foo=None, script_info=None):78+ return Flask('appname')79+80+ assert isinstance(find_best_app(script_info, Module), Flask)81+ assert find_best_app(script_info, Module).name == 'appname'82+83+ class Module:84+ @staticmethod85+ def make_app():86+ return Flask('appname')87+88+ assert isinstance(find_best_app(script_info, Module), Flask)89+ assert find_best_app(script_info, Module).name == 'appname'90+91+ class Module:92+ myapp = Flask('appname1')93+94+ @staticmethod95+ def create_app():96+ return Flask('appname2')97+98+ assert find_best_app(script_info, Module) == Module.myapp99+100+ class Module:101+ myapp = Flask('appname1')102+103+ @staticmethod104+ def create_app():105+ return Flask('appname2')106+107+ assert find_best_app(script_info, Module) == Module.myapp108+109+ class Module:110 pass50- pytest.raises(NoAppException, find_best_app, Module)111 112+ pytest.raises(NoAppException, find_best_app, script_info, Module)113+114 class Module:115 myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')55- pytest.raises(NoAppException, find_best_app, Module)117 118+ pytest.raises(NoAppException, find_best_app, script_info, Module)119 120+ class Module:121+ @staticmethod122+ def create_app(foo, bar):123+ return Flask('appname2')124+125+ pytest.raises(NoAppException, find_best_app, script_info, Module)126+127+128 def test_prepare_exec_for_file(test_apps):129 """Expect the correct path to be set and the correct module name to be returned.130 131 :func:`prepare_exec_for_file` has a side effect, where14 unmodified lines146 147 148 def test_locate_app(test_apps):149 """Test of locate_app."""80- assert locate_app("cliapp.app").name == "testapp"81- assert locate_app("cliapp.app:testapp").name == "testapp"82- assert locate_app("cliapp.multiapp:app1").name == "app1"83- pytest.raises(NoAppException, locate_app, "notanpp.py")84- pytest.raises(NoAppException, locate_app, "cliapp/app")85- pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")86- pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")150+ script_info = ScriptInfo()151+ assert locate_app(script_info, "cliapp.app").name == "testapp"152+ assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153+ assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"154+ pytest.raises(NoAppException, locate_app,155+ script_info, "notanpp.py")156+ pytest.raises(NoAppException, locate_app,157+ script_info, "cliapp/app")158+ pytest.raises(RuntimeError, locate_app,159+ script_info, "cliapp.app:notanapp")160+ pytest.raises(NoAppException, locate_app,161+ script_info, "cliapp.importerrorapp")162 163 164 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):165 """Test of find_default_import_path."""11 unmodified lines177 def test_get_version(test_apps, capsys):178 """Test of get_version."""179 from flask import __version__ as flask_ver180 from sys import version as py_ver181+182 class MockCtx(object):183 resilient_parsing = False184 color = None185+186 def exit(self): return187+188 ctx = MockCtx()189 get_version(ctx, None, "test")190 out, err = capsys.readouterr()191 assert flask_ver in out14 unmodified lines206 assert app.name == "createapp"207 assert obj.load_app() == app208 209 132-def test_with_appcontext():210+def test_with_appcontext(runner):211 """Test of with_appcontext."""212+213 @click.command()214 @with_appcontext215 def testcmd():216 click.echo(current_app.name)217 218 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))219 141- runner = CliRunner()220 result = runner.invoke(testcmd, obj=obj)221 assert result.exit_code == 0222 assert result.output == 'testapp\n'223 224 147-def test_appgroup():225+def test_appgroup(runner):226 """Test of with_appcontext."""227+228 @click.group(cls=AppGroup)229 def cli():230 pass231 10 unmodified lines242 click.echo(current_app.name)243 244 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))245 167- runner = CliRunner()246 result = runner.invoke(cli, ['test'], obj=obj)247 assert result.exit_code == 0248 assert result.output == 'testappgroup\n'249 1 unmodified line251 assert result.exit_code == 0252 assert result.output == 'testappgroup\n'253 254 177-def test_flaskgroup():255+def test_flaskgroup(runner):256 """Test FlaskGroup."""257+258 def create_app(info):259 return Flask("flaskgroup")260 261 @click.group(cls=FlaskGroup, create_app=create_app)3 unmodified lines265 @cli.command()266 def test():267 click.echo(current_app.name)268 190- runner = CliRunner()269 result = runner.invoke(cli, ['test'])270 assert result.exit_code == 0271 assert result.output == 'flaskgroup\n'272 273 196-def test_print_exceptions():274+def test_print_exceptions(runner):275 """Print the stacktrace if the CLI."""276+277 def create_app(info):278 raise Exception("oh no")279 return Flask("flaskgroup")280 281 @click.group(cls=FlaskGroup, create_app=create_app)282 def cli(**params):283 pass284 206- runner = CliRunner()285 result = runner.invoke(cli, ['--help'])286 assert result.exit_code == 0287 assert 'Exception: oh no' in result.output288 assert 'Traceback' in result.output289+290+291+class TestRoutes:292+ @pytest.fixture293+ def invoke(self, runner):294+ def create_app(info):295+ app = Flask(__name__)296+ app.testing = True297+298+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])299+ def yyy_get_post(x, y):300+ pass301+302+ @app.route('/zzz_post', methods=['POST'])303+ def aaa_post():304+ pass305+306+ return app307+308+ cli = FlaskGroup(create_app=create_app)309+ return partial(runner.invoke, cli)310+311+ def expect_order(self, order, output):312+ # skip the header and match the start of each row313+ for expect, line in zip(order, output.splitlines()[2:]):314+ # do this instead of startswith for nicer pytest output315+ assert line[:len(expect)] == expect316+317+ def test_simple(self, invoke):318+ result = invoke(['routes'])319+ assert result.exit_code == 0320+ self.expect_order(321+ ['aaa_post', 'static', 'yyy_get_post'],322+ result.output323+ )324+325+ def test_sort(self, invoke):326+ default_output = invoke(['routes']).output327+ endpoint_output = invoke(['routes', '-s', 'endpoint']).output328+ assert default_output == endpoint_output329+ self.expect_order(330+ ['static', 'yyy_get_post', 'aaa_post'],331+ invoke(['routes', '-s', 'methods']).output332+ )333+ self.expect_order(334+ ['yyy_get_post', 'static', 'aaa_post'],335+ invoke(['routes', '-s', 'rule']).output336+ )337+ self.expect_order(338+ ['aaa_post', 'yyy_get_post', 'static'],339+ invoke(['routes', '-s', 'match']).output340+ )341+342+ def test_all_methods(self, invoke):343+ output = invoke(['routes']).output344+ assert 'GET, HEAD, OPTIONS, POST' not in output345+ output = invoke(['routes', '--all-methods']).output346+ assert 'GET, HEAD, OPTIONS, POST' in outputmodified:tests/test_deprecations.py+4 added-11 removed
13 unmodified lines14 import flask15 16 17 class TestRequestDeprecation(object):18-19- def test_request_json(self, recwarn):18+ def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""21- app = flask.Flask(__name__)22- app.testing = True20 21 @app.route('/', methods=['POST'])22 def index():23 assert flask.request.json == {'spam': 42}24 print(flask.request.json)25 return 'OK'26 30- c = app.test_client()31- c.post('/', data='{"spam": 42}', content_type='application/json')27+ client.post('/', data='{"spam": 42}', content_type='application/json')28 recwarn.pop(DeprecationWarning)29 34- def test_request_module(self, recwarn):30+ def test_request_module(self, recwarn, app, client):31 """Request.module is deprecated"""36- app = flask.Flask(__name__)37- app.testing = True32 33 @app.route('/')34 def index():35 assert flask.request.module is None36 return 'OK'37 44- c = app.test_client()45- c.get('/')38+ client.get('/')39 recwarn.pop(DeprecationWarning)modified:tests/test_ext.py+10 added-12 removed
19 unmodified lines20 from flask._compat import PY221 22 23 @pytest.fixture(autouse=True)24-def disable_extwarnings(request, recwarn):24+def disable_extwarnings(recwarn):25 from flask.exthook import ExtDeprecationWarning26 27- def inner():28- assert set(w.category for w in recwarn.list) \29- <= set([ExtDeprecationWarning])30- recwarn.clear()27+ yield28 32- request.addfinalizer(inner)29+ assert set(w.category for w in recwarn.list) \30+ <= set([ExtDeprecationWarning])31+ recwarn.clear()32 33 34 @pytest.fixture(autouse=True)36-def importhook_setup(monkeypatch, request):35+def importhook_setup(monkeypatch):36 # we clear this out for various reasons. The most important one is37 # that a real flaskext could be in there which would disable our38 # fake package. Secondly we want to make sure that the flaskext39 # import hook does not break on reloading.16 unmodified lines56 cls.__name__ == 'ExtensionImporter':57 import_hooks += 158 assert import_hooks == 159 61- def teardown():62- from flask import ext63- for key in ext.__dict__:64- assert '.' not in key60+ yield61 66- request.addfinalizer(teardown)62+ from flask import ext63+ for key in ext.__dict__:64+ assert '.' not in key65 66 67 @pytest.fixture68 def newext_simple(modules_tmpdir):129 unmodified linesmodified:tests/test_helpers.py+377 added-336 removed
20 unmodified lines21 from werkzeug.exceptions import BadRequest, NotFound22 from werkzeug.http import parse_cache_control_header, parse_options_header23 from werkzeug.http import http_date24 from flask._compat import StringIO, text_type25+from flask.helpers import get_debug_flag, make_response26 27 28 def has_encoding(name):29 try:4 unmodified lines34 return False35 36 37 class TestJSON(object):37-38- def test_ignore_cached_json(self):38+ def test_ignore_cached_json(self, app):39- app = flask.Flask(__name__)39 with app.test_request_context('/', method='POST', data='malformed',40 content_type='application/json'):41 assert flask.request.get_json(silent=True, cache=True) is None42 with pytest.raises(BadRequest):43 flask.request.get_json(silent=False, cache=False)44 46- def test_post_empty_json_adds_exception_to_response_content_in_debug(self):47- app = flask.Flask(__name__)45+ def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):46 app.config['DEBUG'] = True47+48 @app.route('/json', methods=['POST'])49 def post_json():50 flask.request.get_json()51 return None53- c = app.test_client()54- rv = c.post('/json', data=None, content_type='application/json')52+53+ rv = client.post('/json', data=None, content_type='application/json')54 assert rv.status_code == 40055 assert b'Failed to decode JSON object' in rv.data56 58- def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):59- app = flask.Flask(__name__)57+ def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):58 app.config['DEBUG'] = False59+60 @app.route('/json', methods=['POST'])61 def post_json():62 flask.request.get_json()63 return None65- c = app.test_client()66- rv = c.post('/json', data=None, content_type='application/json')64+65+ rv = client.post('/json', data=None, content_type='application/json')66 assert rv.status_code == 40067 assert b'Failed to decode JSON object' not in rv.data68 70- def test_json_bad_requests(self):71- app = flask.Flask(__name__)69+ def test_json_bad_requests(self, app, client):70+71 @app.route('/json', methods=['POST'])72 def return_json():73 return flask.jsonify(foo=text_type(flask.request.get_json()))75- c = app.test_client()76- rv = c.post('/json', data='malformed', content_type='application/json')74+75+ rv = client.post('/json', data='malformed', content_type='application/json')76 assert rv.status_code == 40077 79- def test_json_custom_mimetypes(self):80- app = flask.Flask(__name__)78+ def test_json_custom_mimetypes(self, app, client):79+80 @app.route('/json', methods=['POST'])81 def return_json():82 return flask.request.get_json()84- c = app.test_client()85- rv = c.post('/json', data='"foo"', content_type='application/x+json')83+84+ rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'86 88- def test_json_body_encoding(self):89- app = flask.Flask(__name__)90- app.testing = True87+ def test_json_body_encoding(self, app, client):88+89 @app.route('/')90 def index():91 return flask.request.get_json()92 95- c = app.test_client()96- resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),97- content_type='application/json; charset=iso-8859-15')93+ resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),94+ content_type='application/json; charset=iso-8859-15')95 assert resp.data == u'Hällo Wörld'.encode('utf-8')96 100- def test_json_as_unicode(self):101- app = flask.Flask(__name__)97+ @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])98+ def test_json_as_unicode(self, test_value, expected, app, app_ctx):99 103- app.config['JSON_AS_ASCII'] = True104- with app.app_context():105- rv = flask.json.dumps(u'\N{SNOWMAN}')106- assert rv == '"\\u2603"'100+ app.config['JSON_AS_ASCII'] = test_value101+ rv = flask.json.dumps(u'\N{SNOWMAN}')102+ assert rv == expected103 108- app.config['JSON_AS_ASCII'] = False109- with app.app_context():110- rv = flask.json.dumps(u'\N{SNOWMAN}')111- assert rv == u'"\u2603"'112-113- def test_json_dump_to_file(self):104+ def test_json_dump_to_file(self, app, app_ctx):114- app = flask.Flask(__name__)105 test_data = {'name': 'Flask'}106 out = StringIO()107 118- with app.app_context():119- flask.json.dump(test_data, out)120- out.seek(0)121- rv = flask.json.load(out)122- assert rv == test_data108+ flask.json.dump(test_data, out)109+ out.seek(0)110+ rv = flask.json.load(out)111+ assert rv == test_data112 113 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])125- def test_jsonify_basic_types(self, test_value):114+ def test_jsonify_basic_types(self, test_value, app, client):115 """Test jsonify with basic types."""127- app = flask.Flask(__name__)128- c = app.test_client()116 117 url = '/jsonify_basic_types'118 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))132- rv = c.get(url)119+ rv = client.get(url)120 assert rv.mimetype == 'application/json'121 assert flask.json.loads(rv.data) == test_value122 136- def test_jsonify_dicts(self):123+ def test_jsonify_dicts(self, app, client):124 """Test jsonify with dicts and kwargs unpacking."""138- d = dict(139- a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,140- h=['test list', 10, False],141- i={'test':'dict'}142- )143- app = flask.Flask(__name__)125+ d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',126+ 'e': 'Hi', 'f': True, 'g': False,127+ 'h': ['test list', 10, False],128+ 'i': {'test': 'dict'}}129+130 @app.route('/kw')131 def return_kwargs():132 return flask.jsonify(**d)133+134 @app.route('/dict')135 def return_dict():136 return flask.jsonify(d)150- c = app.test_client()137+138 for url in '/kw', '/dict':152- rv = c.get(url)139+ rv = client.get(url)140 assert rv.mimetype == 'application/json'141 assert flask.json.loads(rv.data) == d142 156- def test_jsonify_arrays(self):143+ def test_jsonify_arrays(self, app, client):144 """Test jsonify of lists and args unpacking."""145 l = [146 0, 42, 3.14, 't', 'hello', True, False,147 ['test list', 2, False],161- {'test':'dict'}148+ {'test': 'dict'}149 ]163- app = flask.Flask(__name__)150+151 @app.route('/args_unpack')152 def return_args_unpack():153 return flask.jsonify(*l)154+155 @app.route('/array')156 def return_array():157 return flask.jsonify(l)170- c = app.test_client()158+159 for url in '/args_unpack', '/array':172- rv = c.get(url)160+ rv = client.get(url)161 assert rv.mimetype == 'application/json'162 assert flask.json.loads(rv.data) == l163 176- def test_jsonify_date_types(self):164+ def test_jsonify_date_types(self, app, client):165 """Test jsonify with datetime.date and datetime.datetime types."""166 test_dates = (167 datetime.datetime(1973, 3, 11, 6, 30, 45),168 datetime.date(1975, 1, 5)169 )182- app = flask.Flask(__name__)183- c = app.test_client()170 171 for i, d in enumerate(test_dates):172 url = '/datetest{0}'.format(i)173 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))188- rv = c.get(url)174+ rv = client.get(url)175 assert rv.mimetype == 'application/json'176 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())177 192- def test_jsonify_uuid_types(self):178+ def test_jsonify_uuid_types(self, app, client):179 """Test jsonify with uuid.UUID types"""180 181 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196- app = flask.Flask(__name__)182 url = '/uuid_test'183 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))184 200- c = app.test_client()201- rv = c.get(url)185+ rv = client.get(url)186 187 rv_x = flask.json.loads(rv.data)['x']188 assert rv_x == str(test_uuid)189 rv_uuid = uuid.UUID(rv_x)190 assert rv_uuid == test_uuid191 208- def test_json_attr(self):209- app = flask.Flask(__name__)192+ def test_json_attr(self, app, client):193+194 @app.route('/add', methods=['POST'])195 def add():196 json = flask.request.get_json()197 return text_type(json['a'] + json['b'])214- c = app.test_client()215- rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),216- content_type='application/json')198+199+ rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),200+ content_type='application/json')201 assert rv.data == b'3'202 219- def test_template_escaping(self):220- app = flask.Flask(__name__)203+ def test_template_escaping(self, app, req_ctx):204 render = flask.render_template_string222- with app.test_request_context():223- rv = flask.json.htmlsafe_dumps('</script>')224- assert rv == u'"\\u003c/script\\u003e"'225- assert type(rv) == text_type226- rv = render('{{ "</script>"|tojson }}')227- assert rv == '"\\u003c/script\\u003e"'228- rv = render('{{ "<\0/script>"|tojson }}')229- assert rv == '"\\u003c\\u0000/script\\u003e"'230- rv = render('{{ "<!--<script>"|tojson }}')231- assert rv == '"\\u003c!--\\u003cscript\\u003e"'232- rv = render('{{ "&"|tojson }}')233- assert rv == '"\\u0026"'234- rv = render('{{ "\'"|tojson }}')235- assert rv == '"\\u0027"'236- rv = render("<a ng-data='{{ data|tojson }}'></a>",237- data={'x': ["foo", "bar", "baz'"]})238- assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'205+ rv = flask.json.htmlsafe_dumps('</script>')206+ assert rv == u'"\\u003c/script\\u003e"'207+ assert type(rv) == text_type208+ rv = render('{{ "</script>"|tojson }}')209+ assert rv == '"\\u003c/script\\u003e"'210+ rv = render('{{ "<\0/script>"|tojson }}')211+ assert rv == '"\\u003c\\u0000/script\\u003e"'212+ rv = render('{{ "<!--<script>"|tojson }}')213+ assert rv == '"\\u003c!--\\u003cscript\\u003e"'214+ rv = render('{{ "&"|tojson }}')215+ assert rv == '"\\u0026"'216+ rv = render('{{ "\'"|tojson }}')217+ assert rv == '"\\u0027"'218+ rv = render("<a ng-data='{{ data|tojson }}'></a>",219+ data={'x': ["foo", "bar", "baz'"]})220+ assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'221 240- def test_json_customization(self):222+ def test_json_customization(self, app, client):223 class X(object):224 def __init__(self, val):225 self.val = val226+227 class MyEncoder(flask.json.JSONEncoder):228 def default(self, o):229 if isinstance(o, X):230 return '<%d>' % o.val231 return flask.json.JSONEncoder.default(self, o)232+233 class MyDecoder(flask.json.JSONDecoder):234 def __init__(self, *args, **kwargs):235 kwargs.setdefault('object_hook', self.object_hook)236 flask.json.JSONDecoder.__init__(self, *args, **kwargs)237+238 def object_hook(self, obj):239 if len(obj) == 1 and '_foo' in obj:240 return X(obj['_foo'])241 return obj257- app = flask.Flask(__name__)258- app.testing = True242+243 app.json_encoder = MyEncoder244 app.json_decoder = MyDecoder245+246 @app.route('/', methods=['POST'])247 def index():248 return flask.json.dumps(flask.request.get_json()['x'])264- c = app.test_client()265- rv = c.post('/', data=flask.json.dumps({249+250+ rv = client.post('/', data=flask.json.dumps({251 'x': {'_foo': 42}252 }), content_type='application/json')253 assert rv.data == b'"<42>"'254 255+ def test_blueprint_json_customization(self, app, client):256+ class X(object):257+ def __init__(self, val):258+ self.val = val259+260+ class MyEncoder(flask.json.JSONEncoder):261+ def default(self, o):262+ if isinstance(o, X):263+ return '<%d>' % o.val264+265+ return flask.json.JSONEncoder.default(self, o)266+267+ class MyDecoder(flask.json.JSONDecoder):268+ def __init__(self, *args, **kwargs):269+ kwargs.setdefault('object_hook', self.object_hook)270+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)271+272+ def object_hook(self, obj):273+ if len(obj) == 1 and '_foo' in obj:274+ return X(obj['_foo'])275+276+ return obj277+278+ bp = flask.Blueprint('bp', __name__)279+ bp.json_encoder = MyEncoder280+ bp.json_decoder = MyDecoder281+282+ @bp.route('/bp', methods=['POST'])283+ def index():284+ return flask.json.dumps(flask.request.get_json()['x'])285+286+ app.register_blueprint(bp)287+288+ rv = client.post('/bp', data=flask.json.dumps({289+ 'x': {'_foo': 42}290+ }), content_type='application/json')291+ assert rv.data == b'"<42>"'292+270- def test_modified_url_encoding(self):293+ def test_modified_url_encoding(self, app, client):294 class ModifiedRequest(flask.Request):295 url_charset = 'euc-kr'273- app = flask.Flask(__name__)274- app.testing = True296+297 app.request_class = ModifiedRequest298 app.url_map.charset = 'euc-kr'299 300 @app.route('/')301 def index():302 return flask.request.args['foo']303 282- rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))304+ rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))305 assert rv.status_code == 200306 assert rv.data == u'정상처리'.encode('utf-8')307 308 if not has_encoding('euc-kr'):309 test_modified_url_encoding = None310 289- def test_json_key_sorting(self):290- app = flask.Flask(__name__)291- app.testing = True311+ def test_json_key_sorting(self, app, client):312 app.debug = True313 314 assert app.config['JSON_SORT_KEYS'] == True315 d = dict.fromkeys(range(20), 'foo')1 unmodified line317 @app.route('/')318 def index():319 return flask.jsonify(values=d)320 301- c = app.test_client()302- rv = c.get('/')321+ rv = client.get('/')322 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]323 sorted_by_str = [324 '{',325 '"values": {',51 unmodified lines377 assert lines == sorted_by_int378 except AssertionError:379 assert lines == sorted_by_str380 381+382 class TestSendfile(object):383+ def test_send_file_regular(self, app, req_ctx):384+ rv = flask.send_file('static/index.html')385+ assert rv.direct_passthrough386+ assert rv.mimetype == 'text/html'387+ with app.open_resource('static/index.html') as f:388+ rv.direct_passthrough = False389+ assert rv.data == f.read()390+ rv.close()391 364- def test_send_file_regular(self):365- app = flask.Flask(__name__)366- with app.test_request_context():367- rv = flask.send_file('static/index.html')368- assert rv.direct_passthrough369- assert rv.mimetype == 'text/html'370- with app.open_resource('static/index.html') as f:371- rv.direct_passthrough = False372- assert rv.data == f.read()373- rv.close()374-375- def test_send_file_xsendfile(self, catch_deprecation_warnings):392+ def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):376- app = flask.Flask(__name__)393 app.use_x_sendfile = True378- with app.test_request_context():379- rv = flask.send_file('static/index.html')380- assert rv.direct_passthrough381- assert 'x-sendfile' in rv.headers382- assert rv.headers['x-sendfile'] == \383- os.path.join(app.root_path, 'static/index.html')384- assert rv.mimetype == 'text/html'385- rv.close()394+ rv = flask.send_file('static/index.html')395+ assert rv.direct_passthrough396+ assert 'x-sendfile' in rv.headers397+ assert rv.headers['x-sendfile'] == \398+ os.path.join(app.root_path, 'static/index.html')399+ assert rv.mimetype == 'text/html'400+ rv.close()401 387- def test_send_file_last_modified(self):388- app = flask.Flask(__name__)402+ def test_send_file_last_modified(self, app, client):403 last_modified = datetime.datetime(1999, 1, 1)404 405 @app.route('/')406 def index():407 return flask.send_file(StringIO("party like it's"),408 last_modified=last_modified,409 mimetype='text/plain')410 397- c = app.test_client()398- rv = c.get('/')411+ rv = client.get('/')412 assert rv.last_modified == last_modified413 401- def test_send_file_object_without_mimetype(self):402- app = flask.Flask(__name__)414+ def test_send_file_object_without_mimetype(self, app, req_ctx):415+ with pytest.raises(ValueError) as excinfo:416+ flask.send_file(StringIO("LOL"))417+ assert 'Unable to infer MIME-type' in str(excinfo)418+ assert 'no filename is available' in str(excinfo)419 404- with app.test_request_context():405- with pytest.raises(ValueError) as excinfo:406- flask.send_file(StringIO("LOL"))420+ flask.send_file(StringIO("LOL"), attachment_filename='filename')407- assert 'Unable to infer MIME-type' in str(excinfo)408- assert 'no filename is available' in str(excinfo)421 410- with app.test_request_context():411- flask.send_file(StringIO("LOL"), attachment_filename='filename')422+ def test_send_file_object(self, app, req_ctx):423+ with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:424+ rv = flask.send_file(f, mimetype='text/html')425+ rv.direct_passthrough = False426+ with app.open_resource('static/index.html') as f:427+ assert rv.data == f.read()428+ assert rv.mimetype == 'text/html'429+ rv.close()430 413- def test_send_file_object(self):414- app = flask.Flask(__name__)415-416- with app.test_request_context():417- with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:418- rv = flask.send_file(f, mimetype='text/html')419- rv.direct_passthrough = False420- with app.open_resource('static/index.html') as f:421- assert rv.data == f.read()422- assert rv.mimetype == 'text/html'423- rv.close()424-431 app.use_x_sendfile = True432 427- with app.test_request_context():428- with open(os.path.join(app.root_path, 'static/index.html')) as f:429- rv = flask.send_file(f, mimetype='text/html')430- assert rv.mimetype == 'text/html'431- assert 'x-sendfile' not in rv.headers432- rv.close()433+ with open(os.path.join(app.root_path, 'static/index.html')) as f:434+ rv = flask.send_file(f, mimetype='text/html')435+ assert rv.mimetype == 'text/html'436+ assert 'x-sendfile' not in rv.headers437+ rv.close()438 439 app.use_x_sendfile = False435- with app.test_request_context():436- f = StringIO('Test')437- rv = flask.send_file(f, mimetype='application/octet-stream')438- rv.direct_passthrough = False439- assert rv.data == b'Test'440- assert rv.mimetype == 'application/octet-stream'441- rv.close()440+ f = StringIO('Test')441+ rv = flask.send_file(f, mimetype='application/octet-stream')442+ rv.direct_passthrough = False443+ assert rv.data == b'Test'444+ assert rv.mimetype == 'application/octet-stream'445+ rv.close()446 443- class PyStringIO(object):444- def __init__(self, *args, **kwargs):445- self._io = StringIO(*args, **kwargs)446- def __getattr__(self, name):447- return getattr(self._io, name)448- f = PyStringIO('Test')449- f.name = 'test.txt'450- rv = flask.send_file(f, attachment_filename=f.name)451- rv.direct_passthrough = False452- assert rv.data == b'Test'453- assert rv.mimetype == 'text/plain'454- rv.close()447+ class PyStringIO(object):448+ def __init__(self, *args, **kwargs):449+ self._io = StringIO(*args, **kwargs)450 456- f = StringIO('Test')457- rv = flask.send_file(f, mimetype='text/plain')458- rv.direct_passthrough = False459- assert rv.data == b'Test'460- assert rv.mimetype == 'text/plain'461- rv.close()451+ def __getattr__(self, name):452+ return getattr(self._io, name)453 454+ f = PyStringIO('Test')455+ f.name = 'test.txt'456+ rv = flask.send_file(f, attachment_filename=f.name)457+ rv.direct_passthrough = False458+ assert rv.data == b'Test'459+ assert rv.mimetype == 'text/plain'460+ rv.close()461+462+ f = StringIO('Test')463+ rv = flask.send_file(f, mimetype='text/plain')464+ rv.direct_passthrough = False465+ assert rv.data == b'Test'466+ assert rv.mimetype == 'text/plain'467+ rv.close()468+469 app.use_x_sendfile = True470 465- with app.test_request_context():466- f = StringIO('Test')467- rv = flask.send_file(f, mimetype='text/html')468- assert 'x-sendfile' not in rv.headers469- rv.close()471+ f = StringIO('Test')472+ rv = flask.send_file(f, mimetype='text/html')473+ assert 'x-sendfile' not in rv.headers474+ rv.close()475 476 @pytest.mark.skipif(477 not callable(getattr(Range, 'to_content_range_header', None)),478 reason="not implement within werkzeug"479 )475- def test_send_file_range_request(self):476- app = flask.Flask(__name__)477-480+ def test_send_file_range_request(self, app, client):481 @app.route('/')482 def index():483 return flask.send_file('static/index.html', conditional=True)484 482- c = app.test_client()483-484- rv = c.get('/', headers={'Range': 'bytes=4-15'})485+ rv = client.get('/', headers={'Range': 'bytes=4-15'})486 assert rv.status_code == 206487 with app.open_resource('static/index.html') as f:488 assert rv.data == f.read()[4:16]489 rv.close()490 490- rv = c.get('/', headers={'Range': 'bytes=4-'})491+ rv = client.get('/', headers={'Range': 'bytes=4-'})492 assert rv.status_code == 206493 with app.open_resource('static/index.html') as f:494 assert rv.data == f.read()[4:]495 rv.close()496 496- rv = c.get('/', headers={'Range': 'bytes=4-1000'})497+ rv = client.get('/', headers={'Range': 'bytes=4-1000'})498 assert rv.status_code == 206499 with app.open_resource('static/index.html') as f:500 assert rv.data == f.read()[4:]501 rv.close()502 502- rv = c.get('/', headers={'Range': 'bytes=-10'})503+ rv = client.get('/', headers={'Range': 'bytes=-10'})504 assert rv.status_code == 206505 with app.open_resource('static/index.html') as f:506 assert rv.data == f.read()[-10:]507 rv.close()508 508- rv = c.get('/', headers={'Range': 'bytes=1000-'})509+ rv = client.get('/', headers={'Range': 'bytes=1000-'})510 assert rv.status_code == 416511 rv.close()512 512- rv = c.get('/', headers={'Range': 'bytes=-'})513+ rv = client.get('/', headers={'Range': 'bytes=-'})514 assert rv.status_code == 416515 rv.close()516 516- rv = c.get('/', headers={'Range': 'somethingsomething'})517+ rv = client.get('/', headers={'Range': 'somethingsomething'})518 assert rv.status_code == 416519 rv.close()520 520- last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(521+ last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(522 os.path.join(app.root_path, 'static/index.html'))).replace(523 microsecond=0)524 524- rv = c.get('/', headers={'Range': 'bytes=4-15',525- 'If-Range': http_date(last_modified)})525+ rv = client.get('/', headers={'Range': 'bytes=4-15',526+ 'If-Range': http_date(last_modified)})527 assert rv.status_code == 206528 rv.close()529 529- rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(530+ rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(531 datetime.datetime(1999, 1, 1))})532 assert rv.status_code == 200533 rv.close()534 534- def test_attachment(self):535- app = flask.Flask(__name__)536- with app.test_request_context():537- with open(os.path.join(app.root_path, 'static/index.html')) as f:538- rv = flask.send_file(f, as_attachment=True,539- attachment_filename='index.html')540- value, options = \541- parse_options_header(rv.headers['Content-Disposition'])542- assert value == 'attachment'543- rv.close()535+ def test_attachment(self, app, req_ctx):536 545- with app.test_request_context():546- assert options['filename'] == 'index.html'547- rv = flask.send_file('static/index.html', as_attachment=True)548- value, options = parse_options_header(rv.headers['Content-Disposition'])537+ with open(os.path.join(app.root_path, 'static/index.html')) as f:538+ rv = flask.send_file(f, as_attachment=True,539+ attachment_filename='index.html')540+ value, options = \541+ parse_options_header(rv.headers['Content-Disposition'])542 assert value == 'attachment'543 assert options['filename'] == 'index.html'544+ assert 'filename*' not in rv.headers['Content-Disposition']545 rv.close()546 553- with app.test_request_context():554- rv = flask.send_file(StringIO('Test'), as_attachment=True,555- attachment_filename='index.txt',556- add_etags=False)557- assert rv.mimetype == 'text/plain'558- value, options = parse_options_header(rv.headers['Content-Disposition'])559- assert value == 'attachment'560- assert options['filename'] == 'index.txt'561- rv.close()547+ rv = flask.send_file('static/index.html', as_attachment=True)548+ value, options = parse_options_header(rv.headers['Content-Disposition'])549+ assert value == 'attachment'550+ assert options['filename'] == 'index.html'551+ rv.close()552 563- def test_static_file(self):564- app = flask.Flask(__name__)553+ rv = flask.send_file(StringIO('Test'), as_attachment=True,554+ attachment_filename='index.txt',555+ add_etags=False)556+ assert rv.mimetype == 'text/plain'557+ value, options = parse_options_header(rv.headers['Content-Disposition'])558+ assert value == 'attachment'559+ assert options['filename'] == 'index.txt'560+ rv.close()561+562+ def test_attachment_with_utf8_filename(self, app, req_ctx):563+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')564+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))565+ assert content_disposition == set((566+ 'attachment',567+ 'filename="Nandu/pinguino.txt"',568+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"569+ ))570+ rv.close()571+572+ def test_static_file(self, app, req_ctx):573 # default cache timeout is 12 hours566- with app.test_request_context():567- # Test with static file handler.568- rv = app.send_static_file('index.html')569- cc = parse_cache_control_header(rv.headers['Cache-Control'])570- assert cc.max_age == 12 * 60 * 60571- rv.close()572- # Test again with direct use of send_file utility.573- rv = flask.send_file('static/index.html')574- cc = parse_cache_control_header(rv.headers['Cache-Control'])575- assert cc.max_age == 12 * 60 * 60576- rv.close()574+575+ # Test with static file handler.576+ rv = app.send_static_file('index.html')577+ cc = parse_cache_control_header(rv.headers['Cache-Control'])578+ assert cc.max_age == 12 * 60 * 60579+ rv.close()580+ # Test again with direct use of send_file utility.581+ rv = flask.send_file('static/index.html')582+ cc = parse_cache_control_header(rv.headers['Cache-Control'])583+ assert cc.max_age == 12 * 60 * 60584+ rv.close()585 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600578- with app.test_request_context():579- # Test with static file handler.580- rv = app.send_static_file('index.html')581- cc = parse_cache_control_header(rv.headers['Cache-Control'])582- assert cc.max_age == 3600583- rv.close()584- # Test again with direct use of send_file utility.585- rv = flask.send_file('static/index.html')586- cc = parse_cache_control_header(rv.headers['Cache-Control'])587- assert cc.max_age == 3600588- rv.close()586+587+ # Test with static file handler.588+ rv = app.send_static_file('index.html')589+ cc = parse_cache_control_header(rv.headers['Cache-Control'])590+ assert cc.max_age == 3600591+ rv.close()592+ # Test again with direct use of send_file utility.593+ rv = flask.send_file('static/index.html')594+ cc = parse_cache_control_header(rv.headers['Cache-Control'])595+ assert cc.max_age == 3600596+ rv.close()597+598 class StaticFileApp(flask.Flask):599 def get_send_file_max_age(self, filename):600 return 10601+602 app = StaticFileApp(__name__)603 with app.test_request_context():604 # Test with static file handler.605 rv = app.send_static_file('index.html')5 unmodified lines611 cc = parse_cache_control_header(rv.headers['Cache-Control'])612 assert cc.max_age == 10613 rv.close()614 605- def test_send_from_directory(self):606- app = flask.Flask(__name__)607- app.testing = True615+ def test_send_from_directory(self, app, req_ctx):616 app.root_path = os.path.join(os.path.dirname(__file__),617 'test_apps', 'subdomaintestmodule')610- with app.test_request_context():611- rv = flask.send_from_directory('static', 'hello.txt')612- rv.direct_passthrough = False613- assert rv.data.strip() == b'Hello Subdomain'614- rv.close()618+ rv = flask.send_from_directory('static', 'hello.txt')619+ rv.direct_passthrough = False620+ assert rv.data.strip() == b'Hello Subdomain'621+ rv.close()622 616- def test_send_from_directory_bad_request(self):617- app = flask.Flask(__name__)618- app.testing = True623+ def test_send_from_directory_bad_request(self, app, req_ctx):624 app.root_path = os.path.join(os.path.dirname(__file__),625 'test_apps', 'subdomaintestmodule')621- with app.test_request_context():622- with pytest.raises(BadRequest):623- flask.send_from_directory('static', 'bad\x00')626 625-class TestLogging(object):627+ with pytest.raises(BadRequest):628+ flask.send_from_directory('static', 'bad\x00')629 630+631+class TestLogging(object):632 def test_logger_cache(self):633 app = flask.Flask(__name__)634 logger1 = app.logger635 assert app.logger is logger1636 assert logger1.name == __name__637 app.logger_name = __name__ + '/test_logger_cache'638 assert app.logger is not logger1639 635- def test_debug_log(self, capsys):636- app = flask.Flask(__name__)640+ def test_debug_log(self, capsys, app, client):641 app.debug = True642 643 @app.route('/')644 def index():4 unmodified lines649 @app.route('/exc')650 def exc():651 1 // 0652 649- with app.test_client() as c:650- c.get('/')653+ with client:654+ client.get('/')655 out, err = capsys.readouterr()656 assert 'WARNING in test_helpers [' in err657 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err658 assert 'the standard library is dead' in err659 assert 'this is a debug statement' in err660 661 with pytest.raises(ZeroDivisionError):658- c.get('/exc')662+ client.get('/exc')663 660- def test_debug_log_override(self):661- app = flask.Flask(__name__)664+ def test_debug_log_override(self, app):665 app.debug = True666 app.logger_name = 'flask_tests/test_debug_log_override'667 app.logger.level = 10668 assert app.logger.level == 10669 667- def test_exception_logging(self):670+ def test_exception_logging(self, app, client):671 out = StringIO()669- app = flask.Flask(__name__)672 app.config['LOGGER_HANDLER_POLICY'] = 'never'673 app.logger_name = 'flask_tests/test_exception_logging'674 app.logger.addHandler(StreamHandler(out))675+ app.testing = False676 677 @app.route('/')678 def index():679 1 // 0680 678- rv = app.test_client().get('/')681+ rv = client.get('/')682 assert rv.status_code == 500683 assert b'Internal Server Error' in rv.data684 685 err = out.getvalue()1 unmodified line687 assert 'Traceback (most recent call last):' in err688 assert '1 // 0' in err689 assert 'ZeroDivisionError:' in err690 688- def test_processor_exceptions(self):689- app = flask.Flask(__name__)691+ def test_processor_exceptions(self, app, client):692 app.config['LOGGER_HANDLER_POLICY'] = 'never'693+ app.testing = False694+695 @app.before_request696 def before_request():697 if trigger == 'before':698 1 // 0699+700 @app.after_request701 def after_request(response):702 if trigger == 'after':703 1 // 0704 return response705+706 @app.route('/')707 def index():708 return 'Foo'709+710 @app.errorhandler(500)711 def internal_server_error(e):712 return 'Hello Server Error', 500713+714 for trigger in 'before', 'after':707- rv = app.test_client().get('/')715+ rv = client.get('/')716 assert rv.status_code == 500717 assert rv.data == b'Hello Server Error'718 711- def test_url_for_with_anchor(self):712- app = flask.Flask(__name__)719+ def test_url_for_with_anchor(self, app, req_ctx):720+721 @app.route('/')722 def index():723 return '42'716- with app.test_request_context():717- assert flask.url_for('index', _anchor='x y') == '/#x%20y'724 719- def test_url_for_with_scheme(self):720- app = flask.Flask(__name__)725+ assert flask.url_for('index', _anchor='x y') == '/#x%20y'726+727+ def test_url_for_with_scheme(self, app, req_ctx):728+729 @app.route('/')730 def index():731 return '42'724- with app.test_request_context():725- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'732 727- def test_url_for_with_scheme_not_external(self):728- app = flask.Flask(__name__)733+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'734+735+ def test_url_for_with_scheme_not_external(self, app, req_ctx):736+737 @app.route('/')738 def index():739 return '42'732- with app.test_request_context():733- pytest.raises(ValueError,734- flask.url_for,735- 'index',736- _scheme='https')740 738- def test_url_for_with_alternating_schemes(self):739- app = flask.Flask(__name__)741+ pytest.raises(ValueError,742+ flask.url_for,743+ 'index',744+ _scheme='https')745+746+ def test_url_for_with_alternating_schemes(self, app, req_ctx):747+748 @app.route('/')749 def index():750 return '42'743- with app.test_request_context():744- assert flask.url_for('index', _external=True) == 'http://localhost/'745- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'746- assert flask.url_for('index', _external=True) == 'http://localhost/'751 752+ assert flask.url_for('index', _external=True) == 'http://localhost/'753+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'754+ assert flask.url_for('index', _external=True) == 'http://localhost/'755+748- def test_url_with_method(self):756+ def test_url_with_method(self, app, req_ctx):757 from flask.views import MethodView750- app = flask.Flask(__name__)758+759 class MyView(MethodView):760 def get(self, id=None):761 if id is None:762 return 'List'763 return 'Get %d' % id764+765 def post(self):766 return 'Create'767+768 myview = MyView.as_view('myview')769 app.add_url_rule('/myview/', methods=['GET'],770 view_func=myview)771 app.add_url_rule('/myview/<int:id>', methods=['GET'],772 view_func=myview)773 app.add_url_rule('/myview/create', methods=['POST'],774 view_func=myview)775 766- with app.test_request_context():767- assert flask.url_for('myview', _method='GET') == '/myview/'768- assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'769- assert flask.url_for('myview', _method='POST') == '/myview/create'776+ assert flask.url_for('myview', _method='GET') == '/myview/'777+ assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'778+ assert flask.url_for('myview', _method='POST') == '/myview/create'779 780 781 class TestNoImports(object):782 """Test Flasks are created without import.14 unmodified lines797 assert False, 'Flask(import_name) is importing import_name.'798 799 800 class TestStreaming(object):801+ def test_streaming_with_context(self, app, client):802 793- def test_streaming_with_context(self):794- app = flask.Flask(__name__)795- app.testing = True803 @app.route('/')804 def index():805 def generate():806 yield 'Hello '807 yield flask.request.args['name']808 yield '!'809+810 return flask.Response(flask.stream_with_context(generate()))803- c = app.test_client()804- rv = c.get('/?name=World')811+812+ rv = client.get('/?name=World')813 assert rv.data == b'Hello World!'814 807- def test_streaming_with_context_as_decorator(self):808- app = flask.Flask(__name__)809- app.testing = True815+ def test_streaming_with_context_as_decorator(self, app, client):816+817 @app.route('/')818 def index():819 @flask.stream_with_context820 def generate(hello):821 yield hello822 yield flask.request.args['name']823 yield '!'824+825 return flask.Response(generate('Hello '))818- c = app.test_client()819- rv = c.get('/?name=World')826+827+ rv = client.get('/?name=World')828 assert rv.data == b'Hello World!'829 822- def test_streaming_with_context_and_custom_close(self):823- app = flask.Flask(__name__)824- app.testing = True830+ def test_streaming_with_context_and_custom_close(self, app, client):831 called = []832+833 class Wrapper(object):834 def __init__(self, gen):835 self._gen = gen836+837 def __iter__(self):838 return self839+840 def close(self):841 called.append(42)842+843 def __next__(self):844 return next(self._gen)845+846 next = __next__847+848 @app.route('/')849 def index():850 def generate():851 yield 'Hello '852 yield flask.request.args['name']853 yield '!'854+855 return flask.Response(flask.stream_with_context(856 Wrapper(generate())))844- c = app.test_client()845- rv = c.get('/?name=World')857+858+ rv = client.get('/?name=World')859 assert rv.data == b'Hello World!'860 assert called == [42]861 862 863 class TestSafeJoin(object):851-864 def test_safe_join(self):865 # Valid combinations of *args and expected joined paths.866 passing = (855- (('a/b/c', ), 'a/b/c'),856- (('/', 'a/', 'b/', 'c/', ), '/a/b/c'),857- (('a', 'b', 'c', ), 'a/b/c'),858- (('/a', 'b/c', ), '/a/b/c'),859- (('a/b', 'X/../c'), 'a/b/c', ),860- (('/a/b', 'c/X/..'), '/a/b/c', ),867+ (('a/b/c',), 'a/b/c'),868+ (('/', 'a/', 'b/', 'c/'), '/a/b/c'),869+ (('a', 'b', 'c'), 'a/b/c'),870+ (('/a', 'b/c'), '/a/b/c'),871+ (('a/b', 'X/../c'), 'a/b/c'),872+ (('/a/b', 'c/X/..'), '/a/b/c'),873 # If last path is '' add a slash862- (('/a/b/c', '', ), '/a/b/c/', ),874+ (('/a/b/c', ''), '/a/b/c/'),875 # Preserve dot slash864- (('/a/b/c', './', ), '/a/b/c/.', ),865- (('a/b/c', 'X/..'), 'a/b/c/.', ),876+ (('/a/b/c', './'), '/a/b/c/.'),877+ (('a/b/c', 'X/..'), 'a/b/c/.'),878 # Base directory is always considered safe879 (('../', 'a/b/c'), '../a/b/c'),868- (('/..', ), '/..'),880+ (('/..',), '/..'),881 )882 883 for args, expected in passing:884 assert flask.safe_join(*args) == expected2 unmodified lines887 # Should raise werkzeug.exceptions.NotFound on unsafe joins.888 failing = (889 # path.isabs and ``..'' checks890 ('/a', 'b', '/c'),879- ('/a', '../b/c', ),891+ ('/a', '../b/c'),892 ('/a', '..', 'b/c'),893 # Boundaries violations after path normalization882- ('/a', 'b/../b/../../c', ),894+ ('/a', 'b/../b/../../c'),895 ('/a', 'b', 'c/../..'),884- ('/a', 'b/../../c', ),896+ ('/a', 'b/../../c'),897 )898 899 for args in failing:900 with pytest.raises(NotFound):901 print(flask.safe_join(*args))902+903+class TestHelpers(object):904+905+ @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [906+ ('', None, True),907+ ('0', False, False),908+ ('False', False, False),909+ ('No', False, False),910+ ('True', True, True)911+ ])912+ def test_get_debug_flag(self, monkeypatch, debug, expected_flag, expected_default_flag):913+ monkeypatch.setenv('FLASK_DEBUG', debug)914+ if expected_flag is None:915+ assert get_debug_flag() is None916+ else:917+ assert get_debug_flag() == expected_flag918+ assert get_debug_flag(default=True) == expected_default_flag919+920+ def test_make_response(self):921+ app = flask.Flask(__name__)922+ with app.test_request_context():923+ rv = flask.helpers.make_response()924+ assert rv.status_code == 200925+ assert rv.mimetype == 'text/html'926+927+ rv = flask.helpers.make_response('Hello')928+ assert rv.status_code == 200929+ assert rv.data == b'Hello'930+ assert rv.mimetype == 'text/html'modified:tests/test_regression.py+4 added-7 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-14-import os12 import gc13 import sys17-import flask14 import threading15+16+import pytest17 from werkzeug.exceptions import NotFound18 19+import flask20 21 _gc_lock = threading.Lock()22 23 51 unmodified lines75 with pytest.raises(NotFound):76 safe_join('/foo', '..')77 78 80-def test_aborting():79+def test_aborting(app):80 class Foo(Exception):81 whatever = 4283- app = flask.Flask(__name__)84- app.testing = True82 83 @app.errorhandler(Foo)84 def handle_foo(e):85 return str(e.whatever)14 unmodified linesmodified:tests/test_reqctx.py+85 added-53 removed
10 unmodified lines11 12 import pytest13 14 import flask15+from flask.sessions import SessionInterface16 17 try:18 from greenlet import greenlet19 except ImportError:20 greenlet = None21 22 22-def test_teardown_on_pop():23+def test_teardown_on_pop(app):24 buffer = []24- app = flask.Flask(__name__)25+26 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)29 2 unmodified lines32 assert buffer == []33 ctx.pop()34 assert buffer == [None]35 36+35-def test_teardown_with_previous_exception():37+def test_teardown_with_previous_exception(app):38 buffer = []37- app = flask.Flask(__name__)39+40 @app.teardown_request41 def end_of_request(exception):42 buffer.append(exception)43 5 unmodified lines49 with app.test_request_context():50 assert buffer == []51 assert buffer == [None]52 53+51-def test_teardown_with_handled_exception():54+def test_teardown_with_handled_exception(app):55 buffer = []53- app = flask.Flask(__name__)56+57 @app.teardown_request58 def end_of_request(exception):59 buffer.append(exception)60 4 unmodified lines65 except Exception:66 pass67 assert buffer == [None]68 66-def test_proper_test_request_context():67- app = flask.Flask(__name__)69+70+def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )74 6 unmodified lines81 return None82 83 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \82- 'http://localhost.localdomain:5000/'85+ 'http://localhost.localdomain:5000/'86 87 with app.test_request_context('/'):88 assert flask.url_for('sub', _external=True) == \86- 'http://foo.localhost.localdomain:5000/'89+ 'http://foo.localhost.localdomain:5000/'90 91 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93 pass11 unmodified lines105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107 pass108 106-def test_context_binding():107- app = flask.Flask(__name__)109+110+def test_context_binding(app):111 @app.route('/')112 def index():113 return 'Hello %s!' % flask.request.args['name']114+115 @app.route('/meh')116 def meh():117 return flask.request.url118 2 unmodified lines121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'123 assert flask._request_ctx_stack.top is None124 121-def test_context_test():122- app = flask.Flask(__name__)125+126+def test_context_test(app):127 assert not flask.request128 assert not flask.has_request_context()129 ctx = app.test_request_context()130 ctx.push()2 unmodified lines133 assert flask.has_request_context()134 finally:135 ctx.pop()136 133-def test_manual_context_binding():134- app = flask.Flask(__name__)137+138+def test_manual_context_binding(app):139 @app.route('/')140 def index():141 return 'Hello %s!' % flask.request.args['name']142 3 unmodified lines146 ctx.pop()147 with pytest.raises(RuntimeError):148 index()149 150+151 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')147-def test_greenlet_context_copying():148- app = flask.Flask(__name__)149- greenlets = []152+class TestGreenletContextCopying(object):153 154+ def test_greenlet_context_copying(self, app, client):155+ greenlets = []156+157+ @app.route('/')151- @app.route('/')152- def index():153- reqctx = flask._request_ctx_stack.top.copy()154- def g():155- assert not flask.request156- assert not flask.current_app157- with reqctx:158+ def index():159+ reqctx = flask._request_ctx_stack.top.copy()160+161+ def g():162+ assert not flask.request163+ assert not flask.current_app164+ with reqctx:165+ assert flask.request166+ assert flask.current_app == app167+ assert flask.request.path == '/'168+ assert flask.request.args['foo'] == 'bar'169+ assert not flask.request170+ return 42171+172+ greenlets.append(greenlet(g))173+ return 'Hello World!'174+175+ rv = client.get('/?foo=bar')176+ assert rv.data == b'Hello World!'177+178+ result = greenlets[0].run()179+ assert result == 42180+181+ def test_greenlet_context_copying_api(self, app, client):182+ greenlets = []183+184+ @app.route('/')185+ def index():186+ reqctx = flask._request_ctx_stack.top.copy()187+188+ @flask.copy_current_request_context189+ def g():190 assert flask.request191 assert flask.current_app == app192 assert flask.request.path == '/'193 assert flask.request.args['foo'] == 'bar'162- assert not flask.request163- return 42194+ return 42164- greenlets.append(greenlet(g))165- return 'Hello World!'195 167- rv = app.test_client().get('/?foo=bar')168- assert rv.data == b'Hello World!'196+ greenlets.append(greenlet(g))197+ return 'Hello World!'198 170- result = greenlets[0].run()171- assert result == 42199+ rv = client.get('/?foo=bar')200+ assert rv.data == b'Hello World!'201 173-@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')174-def test_greenlet_context_copying_api():175- app = flask.Flask(__name__)176- greenlets = []202+ result = greenlets[0].run()203+ assert result == 42204 205+206+def test_session_error_pops_context():207+ class SessionError(Exception):208+ pass209+210+ class FailingSessionInterface(SessionInterface):211+ def open_session(self, app, request):212+ raise SessionError()213+214+ class CustomFlask(flask.Flask):215+ session_interface = FailingSessionInterface()216+217+ app = CustomFlask(__name__)218+219 @app.route('/')220 def index():180- reqctx = flask._request_ctx_stack.top.copy()181- @flask.copy_current_request_context182- def g():183- assert flask.request184- assert flask.current_app == app185- assert flask.request.path == '/'186- assert flask.request.args['foo'] == 'bar'187- return 42188- greenlets.append(greenlet(g))189- return 'Hello World!'221+ # shouldn't get here222+ assert False223 191- rv = app.test_client().get('/?foo=bar')192- assert rv.data == b'Hello World!'193-194- result = greenlets[0].run()195- assert result == 42224+ response = app.test_client().get('/')225+ assert response.status_code == 500226+ assert not flask.request227+ assert not flask.current_appmodified:tests/test_signals.py+8 added-4 removed
16 unmodified lines17 blinker = None18 19 import flask20 21-21 pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'24 )25 27-def test_template_rendered():28- app = flask.Flask(__name__)26 27+def test_template_rendered(app, client):28 @app.route('/')29 def index():30 return flask.render_template('simple_template.html', whiskey=42)31 3 unmodified lines35 recorded.append((template, context))36 37 flask.template_rendered.connect(record, app)38 try:41- app.test_client().get('/')39+ client.get('/')40 assert len(recorded) == 141 template, context = recorded[0]42 assert template.name == 'simple_template.html'43 assert context['whiskey'] == 4244 finally:45 flask.template_rendered.disconnect(record, app)46 47+48 def test_before_render_template():49 app = flask.Flask(__name__)50 51 @app.route('/')16 unmodified lines68 assert rv.data == b'<h1>43</h1>'69 finally:70 flask.before_render_template.disconnect(record, app)71 72+73 def test_request_signals():74 app = flask.Flask(__name__)75 calls = []76 31 unmodified lines108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111 112+113 def test_request_exception_signal():114 app = flask.Flask(__name__)115 recorded = []116 11 unmodified lines128 assert isinstance(recorded[0], ZeroDivisionError)129 finally:130 flask.got_request_exception.disconnect(record, app)131 132+133 def test_appcontext_signals():134 app = flask.Flask(__name__)135 recorded = []136 18 unmodified lines155 finally:156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158 159+160 def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163 18 unmodified lines182 assert category == 'notice'183 finally:184 flask.message_flashed.disconnect(record, app)185 186+187 def test_appcontext_tearing_down_signal():188 app = flask.Flask(__name__)189 recorded = []190 16 unmodified linesmodified:tests/test_templating.py+128 added-86 removed
14 unmodified lines15 import logging16 from jinja2 import TemplateNotFound17 18 19-def test_context_processing():20- app = flask.Flask(__name__)19+def test_context_processing(app, client):20 @app.context_processor21 def context_processor():22 return {'injected_value': 42}23+24 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27- rv = app.test_client().get('/')27+28+ rv = client.get('/')29 assert rv.data == b'<p>23|42'30 30-def test_original_win():31- app = flask.Flask(__name__)31+32+def test_original_win(app, client):33 @app.route('/')34 def index():35 return flask.render_template_string('{{ config }}', config=42)35- rv = app.test_client().get('/')36+37+ rv = client.get('/')38 assert rv.data == b'42'39 38-def test_request_less_rendering():39- app = flask.Flask(__name__)40+41+def test_request_less_rendering(app, app_ctx):42 app.config['WORLD_NAME'] = 'Special World'43+44 @app.context_processor45 def context_processor():46 return dict(foo=42)47 45- with app.app_context():46- rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47- '{{ foo }}')48- assert rv == 'Hello Special World 42'48+ rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '49+ '{{ foo }}')50+ assert rv == 'Hello Special World 42'51 50-def test_standard_context():51- app = flask.Flask(__name__)52+53+def test_standard_context(app, client):54 app.secret_key = 'development key'55+56 @app.route('/')57 def index():58 flask.g.foo = 2359 flask.session['test'] = 'aha'2 unmodified lines62 {{ g.foo }}63 {{ config.DEBUG }}64 {{ session.test }}65 ''')66+63- rv = app.test_client().get('/?foo=42')67+ rv = client.get('/?foo=42')68 assert rv.data.split() == [b'42', b'23', b'False', b'aha']69 70+66-def test_escaping():71+def test_escaping(app, client):72 text = '<p>Hello World!'68- app = flask.Flask(__name__)73+74 @app.route('/')75 def index():76 return flask.render_template('escaping_template.html', text=text,77 html=flask.Markup(text))78+73- lines = app.test_client().get('/').data.splitlines()79+ lines = client.get('/').data.splitlines()80 assert lines == [81 b'<p>Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!',1 unmodified line85 b'<p>Hello World!',86 b'<p>Hello World!'87 ]88 89+83-def test_no_escaping():90+def test_no_escaping(app, client):91 text = '<p>Hello World!'85- app = flask.Flask(__name__)92+93 @app.route('/')94 def index():95 return flask.render_template('non_escaping_template.txt', text=text,96 html=flask.Markup(text))97+90- lines = app.test_client().get('/').data.splitlines()98+ lines = client.get('/').data.splitlines()99 assert lines == [100 b'<p>Hello World!',101 b'<p>Hello World!',102 b'<p>Hello World!',3 unmodified lines106 b'<p>Hello World!',107 b'<p>Hello World!'108 ]109 102-def test_escaping_without_template_filename():103- app = flask.Flask(__name__)104- with app.test_request_context():105- assert flask.render_template_string(106- '{{ foo }}', foo='<test>') == '<test>'107- assert flask.render_template('mail.txt', foo='<test>') == \108- '<test> Mail'110 110-def test_macros():111- app = flask.Flask(__name__)112- with app.test_request_context():113- macro = flask.get_template_attribute('_macro.html', 'hello')114- assert macro('World') == 'Hello World!'111+def test_escaping_without_template_filename(app, client, req_ctx):112+ assert flask.render_template_string(113+ '{{ foo }}', foo='<test>') == '<test>'114+ assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'115 116-def test_template_filter():117- app = flask.Flask(__name__)116+117+def test_macros(app, req_ctx):118+ macro = flask.get_template_attribute('_macro.html', 'hello')119+ assert macro('World') == 'Hello World!'120+121+122+def test_template_filter(app):123 @app.template_filter()124 def my_reverse(s):125 return s[::-1]126+127 assert 'my_reverse' in app.jinja_env.filters.keys()128 assert app.jinja_env.filters['my_reverse'] == my_reverse129 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'130 125-def test_add_template_filter():126- app = flask.Flask(__name__)131+132+def test_add_template_filter(app):133 def my_reverse(s):134 return s[::-1]135+136 app.add_template_filter(my_reverse)137 assert 'my_reverse' in app.jinja_env.filters.keys()138 assert app.jinja_env.filters['my_reverse'] == my_reverse139 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'140 134-def test_template_filter_with_name():135- app = flask.Flask(__name__)141+142+def test_template_filter_with_name(app):143 @app.template_filter('strrev')144 def my_reverse(s):145 return s[::-1]146+147 assert 'strrev' in app.jinja_env.filters.keys()148 assert app.jinja_env.filters['strrev'] == my_reverse149 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'150 143-def test_add_template_filter_with_name():144- app = flask.Flask(__name__)151+152+def test_add_template_filter_with_name(app):153 def my_reverse(s):154 return s[::-1]155+156 app.add_template_filter(my_reverse, 'strrev')157 assert 'strrev' in app.jinja_env.filters.keys()158 assert app.jinja_env.filters['strrev'] == my_reverse159 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'160 152-def test_template_filter_with_template():153- app = flask.Flask(__name__)161+162+def test_template_filter_with_template(app, client):163 @app.template_filter()164 def super_reverse(s):165 return s[::-1]166+167 @app.route('/')168 def index():169 return flask.render_template('template_filter.html', value='abcd')160- rv = app.test_client().get('/')170+171+ rv = client.get('/')172 assert rv.data == b'dcba'173 163-def test_add_template_filter_with_template():164- app = flask.Flask(__name__)174+175+def test_add_template_filter_with_template(app, client):176 def super_reverse(s):177 return s[::-1]178+179 app.add_template_filter(super_reverse)180+181 @app.route('/')182 def index():183 return flask.render_template('template_filter.html', value='abcd')171- rv = app.test_client().get('/')184+185+ rv = client.get('/')186 assert rv.data == b'dcba'187 174-def test_template_filter_with_name_and_template():175- app = flask.Flask(__name__)188+189+def test_template_filter_with_name_and_template(app, client):190 @app.template_filter('super_reverse')191 def my_reverse(s):192 return s[::-1]193+194 @app.route('/')195 def index():196 return flask.render_template('template_filter.html', value='abcd')182- rv = app.test_client().get('/')197+198+ rv = client.get('/')199 assert rv.data == b'dcba'200 185-def test_add_template_filter_with_name_and_template():186- app = flask.Flask(__name__)201+202+def test_add_template_filter_with_name_and_template(app, client):203 def my_reverse(s):204 return s[::-1]205+206 app.add_template_filter(my_reverse, 'super_reverse')207+208 @app.route('/')209 def index():210 return flask.render_template('template_filter.html', value='abcd')193- rv = app.test_client().get('/')211+212+ rv = client.get('/')213 assert rv.data == b'dcba'214 196-def test_template_test():197- app = flask.Flask(__name__)215+216+def test_template_test(app):217 @app.template_test()218 def boolean(value):219 return isinstance(value, bool)220+221 assert 'boolean' in app.jinja_env.tests.keys()222 assert app.jinja_env.tests['boolean'] == boolean223 assert app.jinja_env.tests['boolean'](False)224 205-def test_add_template_test():206- app = flask.Flask(__name__)225+226+def test_add_template_test(app):227 def boolean(value):228 return isinstance(value, bool)229+230 app.add_template_test(boolean)231 assert 'boolean' in app.jinja_env.tests.keys()232 assert app.jinja_env.tests['boolean'] == boolean233 assert app.jinja_env.tests['boolean'](False)234 214-def test_template_test_with_name():215- app = flask.Flask(__name__)235+236+def test_template_test_with_name(app):237 @app.template_test('boolean')238 def is_boolean(value):239 return isinstance(value, bool)240+241 assert 'boolean' in app.jinja_env.tests.keys()242 assert app.jinja_env.tests['boolean'] == is_boolean243 assert app.jinja_env.tests['boolean'](False)244 223-def test_add_template_test_with_name():224- app = flask.Flask(__name__)245+246+def test_add_template_test_with_name(app):247 def is_boolean(value):248 return isinstance(value, bool)249+250 app.add_template_test(is_boolean, 'boolean')251 assert 'boolean' in app.jinja_env.tests.keys()252 assert app.jinja_env.tests['boolean'] == is_boolean253 assert app.jinja_env.tests['boolean'](False)254 232-def test_template_test_with_template():233- app = flask.Flask(__name__)255+256+def test_template_test_with_template(app, client):257 @app.template_test()258 def boolean(value):259 return isinstance(value, bool)260+261 @app.route('/')262 def index():263 return flask.render_template('template_test.html', value=False)240- rv = app.test_client().get('/')264+265+ rv = client.get('/')266 assert b'Success!' in rv.data267 243-def test_add_template_test_with_template():244- app = flask.Flask(__name__)268+269+def test_add_template_test_with_template(app, client):270 def boolean(value):271 return isinstance(value, bool)272+273 app.add_template_test(boolean)274+275 @app.route('/')276 def index():277 return flask.render_template('template_test.html', value=False)251- rv = app.test_client().get('/')278+279+ rv = client.get('/')280 assert b'Success!' in rv.data281 254-def test_template_test_with_name_and_template():255- app = flask.Flask(__name__)282+283+def test_template_test_with_name_and_template(app, client):284 @app.template_test('boolean')285 def is_boolean(value):286 return isinstance(value, bool)287+288 @app.route('/')289 def index():290 return flask.render_template('template_test.html', value=False)262- rv = app.test_client().get('/')291+292+ rv = client.get('/')293 assert b'Success!' in rv.data294 265-def test_add_template_test_with_name_and_template():266- app = flask.Flask(__name__)295+296+def test_add_template_test_with_name_and_template(app, client):297 def is_boolean(value):298 return isinstance(value, bool)299+300 app.add_template_test(is_boolean, 'boolean')301+302 @app.route('/')303 def index():304 return flask.render_template('template_test.html', value=False)273- rv = app.test_client().get('/')305+306+ rv = client.get('/')307 assert b'Success!' in rv.data308 276-def test_add_template_global():277- app = flask.Flask(__name__)309+310+def test_add_template_global(app, app_ctx):311 @app.template_global()312 def get_stuff():313 return 42314+315 assert 'get_stuff' in app.jinja_env.globals.keys()316 assert app.jinja_env.globals['get_stuff'] == get_stuff317 assert app.jinja_env.globals['get_stuff'](), 42284- with app.app_context():285- rv = flask.render_template_string('{{ get_stuff() }}')286- assert rv == '42'318 319+ rv = flask.render_template_string('{{ get_stuff() }}')320+ assert rv == '42'321+322+288-def test_custom_template_loader():323+def test_custom_template_loader(client):324 class MyFlask(flask.Flask):325 def create_global_jinja_loader(self):326 from jinja2 import DictLoader327 return DictLoader({'index.html': 'Hello Custom World!'})328+329 app = MyFlask(__name__)330+331 @app.route('/')332 def index():333 return flask.render_template('index.html')334+335 c = app.test_client()336 rv = c.get('/')337 assert rv.data == b'Hello Custom World!'338 301-def test_iterable_loader():302- app = flask.Flask(__name__)339+340+def test_iterable_loader(app, client):341 @app.context_processor342 def context_processor():343 return {'whiskey': 'Jameson'}344+345 @app.route('/')346 def index():347 return flask.render_template(348 ['no_template.xml', # should skip this one310- 'simple_template.html', # should render this311- 'context_template.html'],349+ 'simple_template.html', # should render this350+ 'context_template.html'],351 value=23)352 314- rv = app.test_client().get('/')353+ rv = client.get('/')354 assert rv.data == b'<h1>Jameson</h1>'355 356+317-def test_templates_auto_reload():357+def test_templates_auto_reload(app):358 # debug is False, config option is None319- app = flask.Flask(__name__)359 assert app.debug is False360 assert app.config['TEMPLATES_AUTO_RELOAD'] is None361 assert app.jinja_env.auto_reload is False362 # debug is False, config option is False21 unmodified lines384 app.config['DEBUG'] = True385 app.config['TEMPLATES_AUTO_RELOAD'] = True386 assert app.jinja_env.auto_reload is True387 388+389 def test_template_loader_debugging(test_apps):390 from blueprintapp import app391 392 called = []393+394 class _TestHandler(logging.Handler):395 def handle(x, record):396 called.append(True)397 text = str(record.msg)23 unmodified lines421 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting422 423 assert len(called) == 1424 425+426 def test_custom_jinja_env():427 class CustomEnvironment(flask.templating.Environment):428 pass429 5 unmodified linesmodified:tests/test_testing.py+83 added-89 removed
14 unmodified lines15 16 from flask._compat import text_type17 18 19-def test_environ_defaults_from_config():20- app = flask.Flask(__name__)21- app.testing = True19+def test_environ_defaults_from_config(app, client):20 app.config['SERVER_NAME'] = 'example.com:1234'21 app.config['APPLICATION_ROOT'] = '/foo'22+23 @app.route('/')24 def index():25 return flask.request.url26 27 ctx = app.test_request_context()28 assert ctx.request.url == 'http://example.com:1234/foo/'30- with app.test_client() as c:31- rv = c.get('/')32- assert rv.data == b'http://example.com:1234/foo/'29 34-def test_environ_defaults():35- app = flask.Flask(__name__)36- app.testing = True30+ rv = client.get('/')31+ assert rv.data == b'http://example.com:1234/foo/'32+33+34+def test_environ_defaults(app, client, app_ctx, req_ctx):35 @app.route('/')36 def index():37 return flask.request.url38 39 ctx = app.test_request_context()40 assert ctx.request.url == 'http://localhost/'43- with app.test_client() as c:44- rv = c.get('/')41+ with client:42+ rv = client.get('/')43 assert rv.data == b'http://localhost/'44 47-def test_environ_base_default():48- app = flask.Flask(__name__)49- app.testing = True45+46+def test_environ_base_default(app, client, app_ctx):47 @app.route('/')48 def index():49 flask.g.user_agent = flask.request.headers["User-Agent"]50 return flask.request.remote_addr51 55- with app.test_client() as c:56- rv = c.get('/')57- assert rv.data == b'127.0.0.1'58- assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__52+ rv = client.get('/')53+ assert rv.data == b'127.0.0.1'54+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__55 60-def test_environ_base_modified():61- app = flask.Flask(__name__)62- app.testing = True56+57+def test_environ_base_modified(app, client, app_ctx):58 @app.route('/')59 def index():60 flask.g.user_agent = flask.request.headers["User-Agent"]61 return flask.request.remote_addr62 68- with app.test_client() as c:69- c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70- c.environ_base['HTTP_USER_AGENT'] = 'Foo'71- rv = c.get('/')72- assert rv.data == b'0.0.0.0'73- assert flask.g.user_agent == 'Foo'63+ client.environ_base['REMOTE_ADDR'] = '0.0.0.0'64+ client.environ_base['HTTP_USER_AGENT'] = 'Foo'65+ rv = client.get('/')66+ assert rv.data == b'0.0.0.0'67+ assert flask.g.user_agent == 'Foo'68 75- c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76- c.environ_base['HTTP_USER_AGENT'] = 'Bar'77- rv = c.get('/')78- assert rv.data == b'0.0.0.1'79- assert flask.g.user_agent == 'Bar'69+ client.environ_base['REMOTE_ADDR'] = '0.0.0.1'70+ client.environ_base['HTTP_USER_AGENT'] = 'Bar'71+ rv = client.get('/')72+ assert rv.data == b'0.0.0.1'73+ assert flask.g.user_agent == 'Bar'74 81-def test_redirect_keep_session():82- app = flask.Flask(__name__)75+76+def test_redirect_keep_session(app, client, app_ctx):77 app.secret_key = 'testing'78 79 @app.route('/', methods=['GET', 'POST'])80 def index():5 unmodified lines86 @app.route('/getsession')87 def get_session():88 return flask.session.get('data', '<missing>')89 96- with app.test_client() as c:97- rv = c.get('/getsession')90+ with client:91+ rv = client.get('/getsession')92 assert rv.data == b'<missing>'93 100- rv = c.get('/')94+ rv = client.get('/')95 assert rv.data == b'index'96 assert flask.session.get('data') == 'foo'103- rv = c.post('/', data={}, follow_redirects=True)97+ rv = client.post('/', data={}, follow_redirects=True)98 assert rv.data == b'foo'99 100 # This support requires a new Werkzeug version107- if not hasattr(c, 'redirect_client'):101+ if not hasattr(client, 'redirect_client'):102 assert flask.session.get('data') == 'foo'103 110- rv = c.get('/getsession')104+ rv = client.get('/getsession')105 assert rv.data == b'foo'106 113-def test_session_transactions():114- app = flask.Flask(__name__)115- app.testing = True107+108+def test_session_transactions(app, client):109 app.secret_key = 'testing'110 111 @app.route('/')112 def index():113 return text_type(flask.session['foo'])114 122- with app.test_client() as c:123- with c.session_transaction() as sess:115+ with client:116+ with client.session_transaction() as sess:117 assert len(sess) == 0118 sess['foo'] = [42]119 assert len(sess) == 1127- rv = c.get('/')120+ rv = client.get('/')121 assert rv.data == b'[42]'129- with c.session_transaction() as sess:122+ with client.session_transaction() as sess:123 assert len(sess) == 1124 assert sess['foo'] == [42]125 126+127 def test_session_transactions_no_null_sessions():128 app = flask.Flask(__name__)129 app.testing = True130 2 unmodified lines133 with c.session_transaction() as sess:134 pass135 assert 'Session backend did not open a session' in str(e.value)136 143-def test_session_transactions_keep_context():144- app = flask.Flask(__name__)145- app.testing = True137+138+def test_session_transactions_keep_context(app, client, req_ctx):139 app.secret_key = 'testing'140 148- with app.test_client() as c:149- rv = c.get('/')150- req = flask.request._get_current_object()151- assert req is not None152- with c.session_transaction():153- assert req is flask.request._get_current_object()141+ rv = client.get('/')142+ req = flask.request._get_current_object()143+ assert req is not None144+ with client.session_transaction():145+ assert req is flask.request._get_current_object()146 155-def test_session_transaction_needs_cookies():156- app = flask.Flask(__name__)157- app.testing = True147+148+def test_session_transaction_needs_cookies(app):149 c = app.test_client(use_cookies=False)150 with pytest.raises(RuntimeError) as e:151 with c.session_transaction() as s:152 pass153 assert 'cookies' in str(e.value)154 164-def test_test_client_context_binding():165- app = flask.Flask(__name__)155+156+def test_test_client_context_binding(app, client):157 app.config['LOGGER_HANDLER_POLICY'] = 'never'158+ app.testing = False159+160 @app.route('/')161 def index():162 flask.g.value = 42163 return 'Hello World!'1 unmodified line165 @app.route('/other')166 def other():167 1 // 0168 176- with app.test_client() as c:177- resp = c.get('/')169+ with client:170+ resp = client.get('/')171 assert flask.g.value == 42172 assert resp.data == b'Hello World!'173 assert resp.status_code == 200174 182- resp = c.get('/other')175+ resp = client.get('/other')176 assert not hasattr(flask.g, 'value')177 assert b'Internal Server Error' in resp.data178 assert resp.status_code == 500179 flask.g.value = 234 unmodified lines184 pass185 else:186 raise AssertionError('some kind of exception expected')187 195-def test_reuse_client():196- app = flask.Flask(__name__)197- c = app.test_client()188 189+def test_reuse_client(client):190+ c = client191+192 with c:200- assert c.get('/').status_code == 404193+ assert client.get('/').status_code == 404194 195 with c:203- assert c.get('/').status_code == 404196+ assert client.get('/').status_code == 404197 205-def test_test_client_calls_teardown_handlers():206- app = flask.Flask(__name__)198+199+def test_test_client_calls_teardown_handlers(app, client):200 called = []201+202 @app.teardown_request203 def remember(error):204 called.append(error)205 212- with app.test_client() as c:206+ with client:207 assert called == []214- c.get('/')208+ client.get('/')209 assert called == []210 assert called == [None]211 212 del called[:]219- with app.test_client() as c:213+ with client:214 assert called == []221- c.get('/')215+ client.get('/')216 assert called == []223- c.get('/')217+ client.get('/')218 assert called == [None]219 assert called == [None, None]220 227-def test_full_url_request():228- app = flask.Flask(__name__)229- app.testing = True221 222+def test_full_url_request(app, client):223 @app.route('/action', methods=['POST'])224 def action():225 return 'x'226 235- with app.test_client() as c:236- rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})227+ with client:228+ rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})229 assert rv.status_code == 200230 assert 'gin' in flask.request.form231 assert 'vodka' in flask.request.args232 241-def test_subdomain():242- app = flask.Flask(__name__)233+234+def test_subdomain(app, client):235 app.config['SERVER_NAME'] = 'example.com'236+237 @app.route('/', subdomain='<company_id>')238 def view(company_id):239 return company_id240 241 with app.test_request_context():242 url = flask.url_for('view', company_id='xxx')243 251- with app.test_client() as c:252- response = c.get(url)244+ with client:245+ response = client.get(url)246 247 assert 200 == response.status_code248 assert b'xxx' == response.data249 257-def test_nosubdomain():258- app = flask.Flask(__name__)250+251+def test_nosubdomain(app, client):252 app.config['SERVER_NAME'] = 'example.com'253+254 @app.route('/<company_id>')255 def view(company_id):256 return company_id257 258 with app.test_request_context():259 url = flask.url_for('view', company_id='xxx')260 267- with app.test_client() as c:268- response = c.get(url)261+ with client:262+ response = client.get(url)263 264 assert 200 == response.status_code265 assert b'xxx' == response.datamodified:tests/test_user_error_handler.py+63 added-16 removed
1 # -*- coding: utf-8 -*-2-from werkzeug.exceptions import Forbidden, InternalServerError2+from werkzeug.exceptions import (3+ Forbidden,4+ InternalServerError,5+ HTTPException,6+ NotFound7+ )8 import flask9 10 6-def test_error_handler_no_match():7- app = flask.Flask(__name__)11+def test_error_handler_no_match(app, client):12 13 class CustomException(Exception):14 pass15 13 unmodified lines29 @app.route('/keyerror')30 def key_error():31 raise KeyError()32 29- c = app.test_client()33+ app.testing = False34+ assert client.get('/custom').data == b'custom'35+ assert client.get('/keyerror').data == b'KeyError'36 31- assert c.get('/custom').data == b'custom'32- assert c.get('/keyerror').data == b'KeyError'37 34-35-def test_error_handler_subclass():38+def test_error_handler_subclass(app):36- app = flask.Flask(__name__)37-39 class ParentException(Exception):40 pass41 42 class ChildExceptionUnregistered(ParentException):30 unmodified lines73 assert c.get('/child-unregistered').data == b'parent'74 assert c.get('/child-registered').data == b'child-registered'75 76 76-def test_error_handler_http_subclass():77- app = flask.Flask(__name__)78-77+def test_error_handler_http_subclass(app):78 class ForbiddenSubclassRegistered(Forbidden):79 pass80 81 class ForbiddenSubclassUnregistered(Forbidden):27 unmodified lines109 assert c.get('/forbidden-unregistered').data == b'forbidden'110 assert c.get('/forbidden-registered').data == b'forbidden-registered'111 112 114-def test_error_handler_blueprint():113+def test_error_handler_blueprint(app):114 bp = flask.Blueprint('bp', __name__)115 116 @bp.errorhandler(500)117 def bp_exception_handler(e):2 unmodified lines120 @bp.route('/error')121 def bp_test():122 raise InternalServerError()123 125- app = flask.Flask(__name__)126-124 @app.errorhandler(500)125 def app_exception_handler(e):126 return 'app-error'127 6 unmodified lines134 c = app.test_client()135 136 assert c.get('/error').data == b'app-error'137 assert c.get('/bp/error').data == b'bp-error'138+139+140+def test_default_error_handler():141+ bp = flask.Blueprint('bp', __name__)142+143+ @bp.errorhandler(HTTPException)144+ def bp_exception_handler(e):145+ assert isinstance(e, HTTPException)146+ assert isinstance(e, NotFound)147+ return 'bp-default'148+149+ @bp.errorhandler(Forbidden)150+ def bp_exception_handler(e):151+ assert isinstance(e, Forbidden)152+ return 'bp-forbidden'153+154+ @bp.route('/undefined')155+ def bp_registered_test():156+ raise NotFound()157+158+ @bp.route('/forbidden')159+ def bp_forbidden_test():160+ raise Forbidden()161+162+ app = flask.Flask(__name__)163+164+ @app.errorhandler(HTTPException)165+ def catchall_errorhandler(e):166+ assert isinstance(e, HTTPException)167+ assert isinstance(e, NotFound)168+ return 'default'169+170+ @app.errorhandler(Forbidden)171+ def catchall_errorhandler(e):172+ assert isinstance(e, Forbidden)173+ return 'forbidden'174+175+ @app.route('/forbidden')176+ def forbidden():177+ raise Forbidden()178+179+ app.register_blueprint(bp, url_prefix='/bp')180+181+ c = app.test_client()182+ assert c.get('/bp/undefined').data == b'bp-default'183+ assert c.get('/bp/forbidden').data == b'bp-forbidden'184+ assert c.get('/undefined').data == b'default'185+ assert c.get('/forbidden').data == b'forbidden'186+187+modified:tests/test_views.py+102 added-25 removed
14 unmodified lines15 import flask.views16 17 from werkzeug.http import parse_set_header18 19+20 def common_test(app):21 c = app.test_client()22 23 assert c.get('/').data == b'GET'1 unmodified line25 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 28-def test_basic_view():29- app = flask.Flask(__name__)29 30+def test_basic_view(app):31 class Index(flask.views.View):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'))38 common_test(app)39 39-def test_method_based_view():40- app = flask.Flask(__name__)40 41+def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'45+46 def post(self):47 return 'POST'48 49 app.add_url_rule('/', view_func=Index.as_view('index'))50 51 common_test(app)52 52-def test_view_patching():53- app = flask.Flask(__name__)53 54+def test_view_patching(app):55 class Index(flask.views.MethodView):56 def get(self):57 1 // 058+59 def post(self):60 1 // 061 62 class Other(Index):63 def get(self):64 return 'GET'65+66 def post(self):67 return 'POST'68 69 view = Index.as_view('index')70 view.view_class = Other71 app.add_url_rule('/', view_func=view)72 common_test(app)73 72-def test_view_inheritance():73- app = flask.Flask(__name__)74 75+def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79+80 def post(self):81 return 'POST'82 83 class BetterIndex(Index):84 def delete(self):85 return 'DELETE'86 87 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))86- c = app.test_client()88 88- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89+ meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']91 91-def test_view_decorators():92- app = flask.Flask(__name__)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'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'107 108 app.add_url_rule('/', view_func=Index.as_view('index'))107- c = app.test_client()108- rv = c.get('/')109+ rv = client.get('/')110 assert rv.headers['X-Parachute'] == 'awesome'111 assert rv.data == b'Awesome'112 112-def test_implicit_head():113+114+def test_view_provide_automatic_options_attr():115 app = flask.Flask(__name__)116 117+ class Index1(flask.views.View):118+ provide_automatic_options = False119+120+ def dispatch_request(self):121+ return 'Hello World!'122+123+ app.add_url_rule('/', view_func=Index1.as_view('index'))124+ c = app.test_client()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']132+ provide_automatic_options = True133+134+ def dispatch_request(self):135+ return 'Hello World!'136+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']141+142+ app = flask.Flask(__name__)143+144+ class Index3(flask.views.View):145+ def dispatch_request(self):146+ return 'Hello World!'147+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.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 })160 161 app.add_url_rule('/', view_func=Index.as_view('index'))122- c = app.test_client()123- rv = c.get('/')162+ rv = client.get('/')163 assert rv.data == b'Blub'164 assert rv.headers['X-Method'] == 'GET'126- rv = c.head('/')165+ rv = client.head('/')166 assert rv.data == b''167 assert rv.headers['X-Method'] == 'HEAD'168 130-def test_explicit_head():131- app = flask.Flask(__name__)169 170+def test_explicit_head(app, client):171 class Index(flask.views.MethodView):172 def get(self):173 return 'GET'174+175 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})177 178 app.add_url_rule('/', view_func=Index.as_view('index'))140- c = app.test_client()141- rv = c.get('/')179+ rv = client.get('/')180 assert rv.data == b'GET'143- rv = c.head('/')181+ rv = client.head('/')182 assert rv.data == b''183 assert rv.headers['X-Method'] == 'HEAD'184 147-def test_endpoint_override():148- app = flask.Flask(__name__)185+186+def test_endpoint_override(app):187 app.debug = True188 189 class Index(flask.views.View):190 methods = ['GET', 'POST']191+192 def dispatch_request(self):193 return flask.request.method194 195 app.add_url_rule('/', view_func=Index.as_view('index'))2 unmodified lines198 app.add_url_rule('/', view_func=Index.as_view('index'))199 200 # But these tests should still pass. We just log a warning.201 common_test(app)202+203+204+def test_multiple_inheritance(app, client):205+ class GetView(flask.views.MethodView):206+ def get(self):207+ return 'GET'208+209+ class DeleteView(flask.views.MethodView):210+ def delete(self):211+ return 'DELETE'212+213+ class GetDeleteView(GetView, DeleteView):214+ pass215+216+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))217+218+ assert client.get('/').data == b'GET'219+ assert client.delete('/').data == b'DELETE'220+ assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']221+222+223+def test_remove_method_from_parent(app, client):224+ class GetView(flask.views.MethodView):225+ def get(self):226+ return 'GET'227+228+ class OtherView(flask.views.MethodView):229+ def post(self):230+ return 'POST'231+232+ class View(GetView, OtherView):233+ methods = ['GET']234+235+ app.add_url_rule('/', view_func=View.as_view('index'))236+237+ assert client.get('/').data == b'GET'238+ assert client.post('/').status_code == 405239+ assert sorted(View.methods) == ['GET']added:.coveragerc+11 added
1+[run]2+branch = True3+source =4+ flask5+ tests6+7+[paths]8+source =9+ flask10+ .tox/*/lib/python*/site-packages/flask11+ .tox/pypy/site-packages/flaskdeleted:.gitmodules-3 removed
1-[submodule "docs/_themes"]2- path = docs/_themes3- url = https://github.com/mitsuhiko/flask-sphinx-themes.gitmodified:.travis.yml+49 added-40 removed
1 sudo: false2 language: python3 4-python:5- - "2.6"6- - "2.7"7- - "pypy"8- - "3.3"9- - "3.4"10- - "3.5"11- - "3.6"12-13-env:14- - REQUIREMENTS=lowest15- - REQUIREMENTS=lowest-simplejson16- - REQUIREMENTS=release17- - REQUIREMENTS=release-simplejson18- - REQUIREMENTS=devel19- - REQUIREMENTS=devel-simplejson20-4 matrix:22- exclude:23- # Python 3 support currently does not work with lowest requirements24- - python: "3.3"25- env: REQUIREMENTS=lowest26- - python: "3.3"27- env: REQUIREMENTS=lowest-simplejson28- - python: "3.4"29- env: REQUIREMENTS=lowest30- - python: "3.4"31- env: REQUIREMENTS=lowest-simplejson32- - python: "3.5"33- env: REQUIREMENTS=lowest34- - python: "3.5"35- env: REQUIREMENTS=lowest-simplejson36- - python: "3.6"37- env: REQUIREMENTS=lowest38- - python: "3.6"39- env: REQUIREMENTS=lowest-simplejson5+ include:6+ - python: 3.67+ env: TOXENV=py-release,codecov8+ - python: 3.59+ env: TOXENV=py-release,codecov10+ - python: 3.411+ env: TOXENV=py-release,codecov12+ - python: 3.313+ env: TOXENV=py-release,codecov14+ - python: 2.715+ env: TOXENV=py-release,codecov16+ - python: 2.617+ env: TOXENV=py-release,codecov18+ - python: pypy19+ env: TOXENV=py-release,codecov20+ - python: nightly21+ env: TOXENV=py-release22+ - python: 3.623+ env: TOXENV=docs-html24+ - python: 3.625+ env: TOXENV=py-release-simplejson,codecov26+ - python: 2.727+ env: TOXENV=py-release-simplejson,codecov28+ - python: pypy29+ env: TOXENV=py-release-simplejson,codecov30+ - python: 3.631+ env: TOXENV=py-devel,codecov32+ - python: 3.333+ env: TOXENV=py-devel,codecov34+ - python: 2.735+ env: TOXENV=py-devel,codecov36+ - python: 2.637+ env: TOXENV=py-devel,codecov38+ - python: pypy39+ env: TOXENV=py-devel,codecov40+ - python: 3.641+ env: TOXENV=py-lowest,codecov42+ - python: 3.343+ env: TOXENV=py-lowest,codecov44+ - python: 2.745+ env: TOXENV=py-lowest,codecov46+ - python: 2.647+ env: TOXENV=py-lowest,codecov48+ - python: pypy49+ env: TOXENV=py-lowest,codecov50 51 install:42- - pip install tox52+ - pip install tox53 54 script:45- - tox -e py-$REQUIREMENTS55+ - tox56 47-branches:48- except:49- - website57+cache:58+ - pip59 60 notifications:61 email: false62 irc:6 unmodified linesmodified:AUTHORS+1 added
19 unmodified lines20 - Edmond Burnett21 - Florent Xicluna22 - Georg Brandl23 - Jeff Widman @jeffwidman24+- Joshua Bronson @jab25 - Justin Quick26 - Kenneth Reitz27 - Keyan Pishdadian28 - Marian Sigler10 unmodified linesmodified:CHANGES+53 added
12 unmodified lines13 was confusing to debug for newcomers.14 - Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15 method returns compressed response by default, and pretty response in16 debug mode.17+- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18+ and ``static_host``. This enables ``host_matching`` to be set properly by the19+ time the constructor adds the static route, and enables the static route to20+ be properly associated with the required host. (``#1559``)21+- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)22+- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.23+ (`#2017`_)24+- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable25+ adding OPTIONS method when the ``view_func`` argument is not a class.26+ (`#1489`_).27+- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)28+- Errors caused while opening the session at the beginning of the request are29+ handled by the app's error handlers. (`#2254`_)30+- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31+ override the app's encoder and decoder. (`#1898`_)32+- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33+ bad response types. The error messages have been improved to describe why the34+ type is invalid. (`#2256`_)35+- Add ``routes`` CLI command to output routes registered on the application.36+ (`#2259`_)37+- Show warning when session cookie domain is a bare hostname or an IP38+ address, as these may not behave properly in some browsers, such as Chrome.39+ (`#2282`_)40+- Allow IP address as exact session cookie domain. (`#2282`_)41+- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.42+ (`#2282`_)43+- Auto-detect zero-argument app factory called ``create_app`` or ``make_app``44+ from ``FLASK_APP``. (`#2297`_)45+- Factory functions are not required to take a ``script_info`` parameter to46+ work with the ``flask`` command. If they take a single parameter or a47+ parameter named ``script_info``, the ``ScriptInfo`` object will be passed.48+ (`#2319`_)49 50+.. _#1489: https://github.com/pallets/flask/pull/148951+.. _#1898: https://github.com/pallets/flask/pull/189852+.. _#1936: https://github.com/pallets/flask/pull/193653+.. _#2017: https://github.com/pallets/flask/pull/201754+.. _#2223: https://github.com/pallets/flask/pull/222355+.. _#2254: https://github.com/pallets/flask/pull/225456+.. _#2256: https://github.com/pallets/flask/pull/225657+.. _#2259: https://github.com/pallets/flask/pull/225958+.. _#2282: https://github.com/pallets/flask/pull/228259+.. _#2297: https://github.com/pallets/flask/pull/229760+.. _#2319: https://github.com/pallets/flask/pull/231961+62+Version 0.12.263+--------------64+65+Released on May 16 201766+67+- Fix a bug in `safe_join` on Windows.68+69 Version 0.12.170 --------------71 72 Bugfix release, released on March 31st 2017110 unmodified lines183 ``#1326``).184 - Don't leak exception info of already catched exceptions to context teardown185 handlers (pull request ``#1393``).186 - Allow custom Jinja environment subclasses (pull request ``#1422``).187+- Updated extension dev guidelines.188+189 - ``flask.g`` now has ``pop()`` and ``setdefault`` methods.190 - Turn on autoescape for ``flask.templating.render_template_string`` by default191 (pull request ``#1515``).192 - ``flask.ext`` is now deprecated (pull request ``#1484``).489 unmodified linesmodified:CONTRIBUTING.rst+52 added-1 removed
29 unmodified lines30 31 - Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.33 34+First time setup35+----------------36 37+- Download and install the `latest version of git`_.38+- Configure git with your `username`_ and `email`_.39+- Make sure you have a `GitHub account`_.40+- Fork Flask to your GitHub account by clicking the `Fork`_ button.41+- `Clone`_ your GitHub fork locally.42+- Add the main repository as a remote to update later.43+ ``git remote add pallets https://github.com/pallets/flask``44+45+.. _GitHub account: https://github.com/join46+.. _latest version of git: https://git-scm.com/downloads47+.. _username: https://help.github.com/articles/setting-your-username-in-git/48+.. _email: https://help.github.com/articles/setting-your-email-in-git/49+.. _Fork: https://github.com/pallets/flask/pull/2305#fork-destination-box50+.. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork51+52+Start coding53+------------54+55+- Create a branch to identify the issue you would like to work on (e.g.56+ ``2287-dry-test-suite``)57+- Using your favorite editor, make your changes, `committing as you go`_.58+- Try to follow `PEP8`_, but you may ignore the line length limit if following59+ it would make the code uglier.60+- Include tests that cover any code changes you make. Make sure the test fails61+ without your patch. `Run the tests. <contributing-testsuite_>`_.62+- Push your commits to GitHub and `create a pull request`_.63+- Celebrate 🎉64+65+.. _committing as you go: http://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes66+.. _PEP8: https://pep8.org/67+.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/68+69+.. _contributing-testsuite:70+71 Running the testsuite72 ---------------------73 74 You probably want to set up a `virtualenv12 unmodified lines87 88 cd flask89 pip install --editable .90 91+Running the testsuite92+---------------------93+94+The minimal requirement for running the testsuite is ``pytest``. You can95+install it with::96+97+ pip install pytest98+99 Then you can run the testsuite with::100 57- pytest101+ pytest tests/102 103+**Shortcut**: ``make test`` will ensure ``pytest`` is installed, and run it.104+105 With only pytest installed, a large part of the testsuite will get skipped106 though. Whether this is relevant depends on which part of Flask you're working107 on. Travis is set up to run the full testsuite when you submit your pull108 request anyways.5 unmodified lines114 115 The ``tox`` command will then run all tests against multiple combinations116 Python versions and dependency versions.117 118+**Shortcut**: ``make tox-test`` will ensure ``tox`` is installed, and run it.119+120 Running test coverage121 ---------------------122 Generating a report of lines that do not have unit test coverage can indicate where123 to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``10 unmodified lines134 pytest --cov-report html --cov=flask tests/135 136 Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io137 138+**Shortcut**: ``make cov`` will ensure ``pytest-cov`` is installed, run it, display the results, *and* save the HTML report.139+140+141 Caution142 =======143 pushing144 -------21 unmodified linesmodified:Makefile+4 added
4 unmodified lines5 test:6 pip install -r test-requirements.txt7 tox -e py-release8 9+cov:10+ pip install -r test-requirements.txt -q11+ FLASK_DEBUG= py.test --cov-report term --cov-report html --cov=flask --cov=examples tests examples12+13 audit:14 python setup.py audit15 16 release:29 unmodified linesmodified:setup.cfg+2 added-1 removed
6 unmodified lines7 [metadata]8 license_file = LICENSE9 10 [tool:pytest]11-norecursedirs = .* *.egg *.egg-info env* artwork docs11+minversion = 3.012+testpaths = testsmodified:setup.py+2 added-2 removed
69 unmodified lines70 include_package_data=True,71 zip_safe=False,72 platforms='any',73 install_requires=[74- 'Werkzeug>=0.7',74+ 'Werkzeug>=0.9',75 'Jinja2>=2.4',76 'itsdangerous>=0.21',77- 'click>=2.0',77+ 'click>=4.0',78 ],79 classifiers=[80 'Development Status :: 4 - Beta',81 'Environment :: Web Environment',19 unmodified linesmodified:test-requirements.txt+2 added
1 tox2+pytest3+pytest-covmodified:tox.ini+53 added-21 removed
1 [tox]2-envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}2+envlist =3+ py{36,35,34,33,27,26,py}-release4+ py{36,27,py}-release-simplejson5+ py{36,33,27,26,py}-devel6+ py{36,33,27,26,py}-lowest7+ docs-html8+ coverage-report9 4-5-10 [testenv]11 passenv = LANG8-usedevelop=true9-commands =10- # We need to install those after Flask is installed.11- pip install -e examples/flaskr12- pip install -e examples/minitwit13- pip install -e examples/patterns/largerapp14- pytest --cov=flask --cov-report html []15-deps=16- pytest17- pytest-cov12+usedevelop = true13+deps =14+ pytest>=315+ coverage16 greenlet17+ blinker18 20- lowest: Werkzeug==0.719+ lowest: Werkzeug==0.920 lowest: Jinja2==2.421 lowest: itsdangerous==0.2123- lowest: blinker==1.024- release: blinker25- devel: git+https://github.com/pallets/werkzeug.git26- devel: git+https://github.com/pallets/jinja.git27- devel: git+https://github.com/pallets/itsdangerous.git28- devel: git+https://github.com/jek/blinker.git22+ lowest: Click==4.023+24+ devel: https://github.com/pallets/werkzeug/archive/master.tar.gz25+ devel: https://github.com/pallets/markupsafe/archive/master.tar.gz26+ devel: https://github.com/pallets/jinja/archive/master.tar.gz27+ devel: https://github.com/pallets/itsdangerous/archive/master.tar.gz28+ devel: https://github.com/pallets/click/archive/master.tar.gz29+30 simplejson: simplejson31+commands =32+ # the examples need to be installed to test successfully33+ pip install -e examples/flaskr -q34+ pip install -e examples/minitwit -q35+ pip install -e examples/patterns/largerapp -q36 37+ # pytest-cov doesn't seem to play nice with -p38+ coverage run -p -m pytest39+31-[testenv:docs]40+[testenv:docs-html]41+deps =42+ sphinx43+ flask-sphinx-themes44+commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html45+46+[testenv:docs-linkcheck]47 deps = sphinx48 commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck49+50+[testenv:coverage-report]51+deps = coverage52+skip_install = true53+commands =54+ coverage combine55+ coverage report56+ coverage html57+58+[testenv:codecov]59+passenv = CI TRAVIS TRAVIS_*60+deps = codecov61+skip_install = true62+commands =63+ coverage combine64+ coverage report65+ codecov