Skip to content
Myr

Clarified how to test with click

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 d2d8e66 · Browse files · 2 files+12 added−4 removed
This commit

State

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

Diff stats

2 files+12 added−4 removed

  • other:+12 added−4 removed

2 files+12 added−4 removed

modified:docs/tutorial/dbinit.rst+10 added-3 removed
22 unmodified lines
23To do this we can create a function and hook it into the ``flask`` command24that initializes the database. Let me show you the code first. Just add25this function below the `connect_db` function in `flaskr.py`::2627 @app.cli.command()28 def initdb():27 def init_db():29 """Initializes the database."""28 db = get_db()29 with app.open_resource('schema.sql', mode='r') as f:30 db.cursor().executescript(f.read())31 db.commit()3233 @app.cli.command('initdb')34 def initdb_command():35 """Initializes the database."""36 init_db()37 print 'Initialized the database.'3839The ``app.cli.command()`` decorator registers a new command with the40``flask`` script. When the command executes Flask will automatically
1 unmodified line
42Within the function we can then access :attr:`flask.g` and other things as43we would expect. When the script ends, the application context tears down44and the database connection is released.4546We want to keep an actual functions around that initializes the database47though so that we can easily create databases in unittests later. (For48more information see :ref:`testing`.)4950The :func:`~flask.Flask.open_resource` method of the application object51is a convenient helper function that will open a resource that the52application provides. This function opens a file from the resource53location (your `flaskr` folder) and allows you to read from it. We are
19 unmodified lines
modified:docs/testing.rst+2 added-1 removed
41 unmodified lines
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():46 flaskr.init_db()47 flaskr.init_db()4849 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])
302 unmodified lines