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
Provenance
- Commit
2f5a4f8- Tree
014eeb9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
03148db
4 files changed+127 added−11 removed
added:docs/testing.rst+116 added
1+.. _testing:2+3+Testing Flask Applications4+==========================5+6+ **Something that is untested is broken.**7+8+Not sure where that is coming from, and it's not entirely correct, but9+also not that 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 however has automated tests you12+can savely change things and you will instantly know if your change broke13+something.14+15+Flask gives you a couple of ways to test applications. It mainly does16+that by exposing the Werkzeug test :class:`~werkzeug.Client` class to your17+code and handling the context locals for you. You can then use that with18+your favourite testing solution. In this documentation we will us the19+:mod:`unittest` package that comes preinstalled with each Python20+installation.21+22+The Application23+---------------24+25+First we need an application to test for functionality. Let's start26+simple with a Hello World application (`hello.py`)::27+28+ from flask import Flask, render_template_string29+ app = Flask(__name__)30+31+ @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)39+40+The Testing Skeleton41+--------------------42+43+In order to test that, we add a second module (44+`hello_tests.py`) and create a unittest skeleton there::45+46+ import unittest47+ import hello48+49+ class HelloWorldTestCase(unittest.TestCase):50+51+ def setUp(self):52+ self.app = hello.app.test_client()53+54+ if __name__ == '__main__':55+ unittest.main()56+57+The code in the `setUp` function creates a new test client. That function58+is called before each individual test function. What the test client does59+for us is giving us a simple interface to the application. We can trigger60+test requests to the application and the client will also keep track of61+cookies for us.62+63+If we now run that testsuite, we should see the following output::64+65+ $ python hello_tests.py66+67+ ----------------------------------------------------------------------68+ Ran 0 tests in 0.000s69+ 70+ OK71+72+Even though it did not run any tests, we already know that our hello73+application is syntactically valid, otherwise the import would have died74+with an exception.75+76+The First Test77+--------------78+79+Now we can add the first test. Let's check that the application greets us80+with "Hello World" if we access it on ``/``. For that we modify our81+created test case class so that it looks like this::82+83+ class HelloWorldTestCase(unittest.TestCase):84+85+ def setUp(self):86+ self.app = hello.app.test_client()87+88+ def test_hello_world(self):89+ rv = self.app.get('/')90+ assert 'Hello World!' in rv.data91+92+Test functions begin with the word `test`. Every function named like that93+will be picked up automatically. By using `self.app.get` we can send an94+HTTP `GET` request to the application with the given path. The return95+value will be a :class:`~flask.Flask.response_class` object. We can now96+use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the97+return value (as string) from the application. In this case, we ensure98+that ``'Hello World!'`` is part of the output.99+100+Run it again and you should see one passing test. Let's add a second test101+here::102+103+ def test_hello_name(self):104+ rv = self.app.get('/Peter')105+ assert 'Hello Peter!' in rv.data106+107+Of course you can submit forms with the test client as well. For that and108+other features of the test client, check the documentation of the Werkzeug109+test :class:`~werkzeug.Client` and the tests of the MiniTwit example110+application:111+112+- Werkzeug Test :class:`~werkzeug.Client`113+- `MiniTwit Example`_114+115+.. _MiniTwit Example:116+ http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/modified:examples/minitwit/templates/timeline.html+1 added-1 removed
41 unmodified lines42434445464647484941 unmodified lines }}">{{ message.username }}</a></strong> {{ message.text }} <small>— {{ message.pub_date|datetimeformat }}</small> {% else %} <li><em>There are no messages so far.</em> <li><em>There's no message so far.</em> {% endfor %} </ul>{% endblock %}modified:examples/minitwit/minitwit.py+9 added-9 removed
29 unmodified lines30 app = Flask(__name__)31 32 33 def connect_db():34- """Returns a new database connection to the database."""34+ """Returns a new connection to the database."""35 return sqlite3.connect(DATABASE)36 37 38 def init_db():12 unmodified lines51 return (rv[0] if rv else None) if one else rv52 53 54 def 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 None59 60 61 def 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')64 65 66 def 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)70 71 65 unmodified lines137 138 139 @app.route('/<username>/follow')140 def 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 lines152 153 154 @app.route('/<username>/unfollow')155 def 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 lines167 168 169 @app.route('/add_message', methods=['POST'])170 def 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 lines181 182 183 @app.route('/login', methods=['GET', 'POST'])184 def 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 lines202 203 204 @app.route('/register', methods=['GET', 'POST'])205 def 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 linesmodified:examples/minitwit/README+1 added-1 removed
8 unmodified lines9 A SQLite and Flask powered twitter clone10 11 ~ How do I use it?12 13- 1. edit the configurtion in the minitwit.py file13+ 1. edit the configuration in the minitwit.py file14 15 2. fire up a python shell and run this:16 17 >>> from minitwit import init_db; init_db()9 unmodified lines