We are extending the Flask-cli with some custom commands. The command test
is one of them:
# run.py: specified by FLASK_APP
# This is the Flask application object
app = create_app(os.getenv('FLASK_ENV') or 'default')
@app.cli.command()
def test():
"""Run the unit tests."""
tests = unittest.TestLoader().discover('tests')
test_runner = unittest.TextTestRunner()
test_runner.run(tests)
However a typical test (using Python's built-in unittest module) looks like this which is based on the style described here.
# some-tests.py: unittest-based test case.
class SomeTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
def tearDown(self):
self.app_context.pop()
def test_load(self):
pass
I am clearly hitting an anti-pattern here: I have initialized a flask object with the default(development
) configuration because I need it for the @app.cli.command()
decorator which all happens in run.py
. However once I run the test setUp function in some-tests.py
I somehow have to obtain a Flask object utilizing the testing
configuration, e.g. by recreating a Flask app with the testing
configuration like what happens now.
I would like to have pointers on how one goes about to implement a flask-cli
test command in which only one Flask
object is created which is reused amongst the various test cases without having the need of explicitely setting the environment to testing
before I run flask test
on the command line.