Browse Source

Clarified how to test with click

pull/1040/head
Armin Ronacher 11 years ago
parent
commit
b9013ede22
  1. 3
      docs/testing.rst
  2. 13
      docs/tutorial/dbinit.rst

3
docs/testing.rst

@ -43,7 +43,8 @@ In order to test the application, we add a second module
self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
flaskr.app.config['TESTING'] = True flaskr.app.config['TESTING'] = True
self.app = flaskr.app.test_client() self.app = flaskr.app.test_client()
flaskr.init_db() with flaskr.app.app_context():
flaskr.init_db()
def tearDown(self): def tearDown(self):
os.close(self.db_fd) os.close(self.db_fd)

13
docs/tutorial/dbinit.rst

@ -24,13 +24,16 @@ To do this we can create a function and hook it into the ``flask`` command
that initializes the database. Let me show you the code first. Just add that initializes the database. Let me show you the code first. Just add
this function below the `connect_db` function in `flaskr.py`:: this function below the `connect_db` function in `flaskr.py`::
@app.cli.command() def init_db():
def initdb():
"""Initializes the database."""
db = get_db() db = get_db()
with app.open_resource('schema.sql', mode='r') as f: with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read()) db.cursor().executescript(f.read())
db.commit() db.commit()
@app.cli.command('initdb')
def initdb_command():
"""Initializes the database."""
init_db()
print 'Initialized the database.' print 'Initialized the database.'
The ``app.cli.command()`` decorator registers a new command with the The ``app.cli.command()`` decorator registers a new command with the
@ -40,6 +43,10 @@ Within the function we can then access :attr:`flask.g` and other things as
we would expect. When the script ends, the application context tears down we would expect. When the script ends, the application context tears down
and the database connection is released. and the database connection is released.
We want to keep an actual functions around that initializes the database
though so that we can easily create databases in unittests later. (For
more information see :ref:`testing`.)
The :func:`~flask.Flask.open_resource` method of the application object The :func:`~flask.Flask.open_resource` method of the application object
is a convenient helper function that will open a resource that the is a convenient helper function that will open a resource that the
application provides. This function opens a file from the resource application provides. This function opens a file from the resource

Loading…
Cancel
Save