Skip to content
Myr

Doc updates and typo fixes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 03148db · Browse files · 4 files+127 added−11 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+127 added−11 removed

  • other:+127 added−11 removed

4 files+127 added−11 removed

added:docs/testing.rst+116 added
1.. _testing:23Testing Flask Applications4==========================56 **Something that is untested is broken.**78Not sure where that is coming from, and it's not entirely correct, but9also not that far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application however has automated tests you12can savely change things and you will instantly know if your change broke13something.1415Flask gives you a couple of ways to test applications. It mainly does16that by exposing the Werkzeug test :class:`~werkzeug.Client` class to your17code and handling the context locals for you. You can then use that with18your favourite testing solution. In this documentation we will us the19:mod:`unittest` package that comes preinstalled with each Python20installation.2122The Application23---------------2425First we need an application to test for functionality. Let's start26simple with a Hello World application (`hello.py`)::2728 from flask import Flask, render_template_string29 app = Flask(__name__)3031 @app.route('/')32 @app.route('/<name>')33 def hello(name='World'):34 return render_template_string('''35 <!doctype html>36 <title>Hello {{ name }}!</title>37 <h1>Hello {{ name }}!</h1>38 ''', name=name)3940The Testing Skeleton41--------------------4243In order to test that, we add a second module (44`hello_tests.py`) and create a unittest skeleton there::4546 import unittest47 import hello4849 class HelloWorldTestCase(unittest.TestCase):5051 def setUp(self):52 self.app = hello.app.test_client()5354 if __name__ == '__main__':55 unittest.main()5657The code in the `setUp` function creates a new test client. That function58is called before each individual test function. What the test client does59for us is giving us a simple interface to the application. We can trigger60test requests to the application and the client will also keep track of61cookies for us.6263If we now run that testsuite, we should see the following output::6465 $ python hello_tests.py6667 ----------------------------------------------------------------------68 Ran 0 tests in 0.000s69 70 OK7172Even though it did not run any tests, we already know that our hello73application is syntactically valid, otherwise the import would have died74with an exception.7576The First Test77--------------7879Now we can add the first test. Let's check that the application greets us80with "Hello World" if we access it on ``/``. For that we modify our81created test case class so that it looks like this::8283 class HelloWorldTestCase(unittest.TestCase):8485 def setUp(self):86 self.app = hello.app.test_client()8788 def test_hello_world(self):89 rv = self.app.get('/')90 assert 'Hello World!' in rv.data9192Test functions begin with the word `test`. Every function named like that93will be picked up automatically. By using `self.app.get` we can send an94HTTP `GET` request to the application with the given path. The return95value will be a :class:`~flask.Flask.response_class` object. We can now96use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the97return value (as string) from the application. In this case, we ensure98that ``'Hello World!'`` is part of the output.99100Run it again and you should see one passing test. Let's add a second test101here::102103 def test_hello_name(self):104 rv = self.app.get('/Peter')105 assert 'Hello Peter!' in rv.data106107Of course you can submit forms with the test client as well. For that and108other features of the test client, check the documentation of the Werkzeug109test :class:`~werkzeug.Client` and the tests of the MiniTwit example110application:111112- Werkzeug Test :class:`~werkzeug.Client`113- `MiniTwit Example`_114115.. _MiniTwit Example:116 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/
modified:examples/minitwit/templates/timeline.html+1 added-1 removed
modified:examples/minitwit/minitwit.py+9 added-9 removed
29 unmodified lines
30app = Flask(__name__)313233def connect_db():34 """Returns a new database connection to the database."""34 """Returns a new connection to the database."""35 return sqlite3.connect(DATABASE)363738def init_db():
12 unmodified lines
51 return (rv[0] if rv else None) if one else rv525354def get_user_id(username):55 """Convenience method to look up the id for a username"""55 """Convenience method to look up the id for a username."""56 rv = g.db.execute('select user_id from user where username = ?',57 [username]).fetchone()58 return rv[0] if rv else None596061def format_datetime(timestamp):62 """Format a timestamp for display"""62 """Format a timestamp for display."""63 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')646566def gravatar_url(email, size=80):67 """Return the gravatar image for the given email address"""67 """Return the gravatar image for the given email address."""68 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \69 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)7071
65 unmodified lines
137138139@app.route('/<username>/follow')140def follow_user(username):141 """Adds the current user as follower of the given user"""141 """Adds the current user as follower of the given user."""142 if not g.user:143 abort(401)144 whom_id = get_user_id(username)145 if whom_id is None:
6 unmodified lines
152153154@app.route('/<username>/unfollow')155def unfollow_user(username):156 """Removes the current user as follower of the given user"""156 """Removes the current user as follower of the given user."""157 if not g.user:158 abort(401)159 whom_id = get_user_id(username)160 if whom_id is None:
6 unmodified lines
167168169@app.route('/add_message', methods=['POST'])170def add_message():171 """Registers a new message for the user"""171 """Registers a new message for the user."""172 if 'user_id' not in session:173 abort(401)174 if request.form['text']:175 g.db.execute('''insert into message (author_id, text, pub_date)
5 unmodified lines
181182183@app.route('/login', methods=['GET', 'POST'])184def login():185 """Logs the user in"""185 """Logs the user in."""186 if g.user:187 return redirect(url_for('timeline'))188 error = None189 if request.method == 'POST':
12 unmodified lines
202203204@app.route('/register', methods=['GET', 'POST'])205def register():206 """Registers the user"""206 """Registers the user."""207 if g.user:208 return redirect(url_for('timeline'))209 error = None210 if request.method == 'POST':
40 unmodified lines
modified:examples/minitwit/README+1 added-1 removed
8 unmodified lines
9 A SQLite and Flask powered twitter clone1011 ~ How do I use it?1213 1. edit the configurtion in the minitwit.py file13 1. edit the configuration in the minitwit.py file1415 2. fire up a python shell and run this:1617 >>> from minitwit import init_db; init_db()
9 unmodified lines