From b9013ede2213e463c1b6d49b3651c796debc1ea4 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Fri, 2 May 2014 11:50:00 +0100 Subject: [PATCH] Clarified how to test with click --- docs/testing.rst | 3 ++- docs/tutorial/dbinit.rst | 13 ++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/testing.rst b/docs/testing.rst index d31be217..95b2021a 100644 --- a/docs/testing.rst +++ b/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() flaskr.app.config['TESTING'] = True self.app = flaskr.app.test_client() - flaskr.init_db() + with flaskr.app.app_context(): + flaskr.init_db() def tearDown(self): os.close(self.db_fd) diff --git a/docs/tutorial/dbinit.rst b/docs/tutorial/dbinit.rst index 0d92f5be..10404b3a 100644 --- a/docs/tutorial/dbinit.rst +++ b/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 this function below the `connect_db` function in `flaskr.py`:: - @app.cli.command() - def initdb(): - """Initializes the database.""" + def init_db(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() + + @app.cli.command('initdb') + def initdb_command(): + """Initializes the database.""" + init_db() print 'Initialized the database.' 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 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 is a convenient helper function that will open a resource that the application provides. This function opens a file from the resource