python - Flask-Script loads app before running unittests -


i'm using flask-script run tests on application important bit of manage.py file looks this:

import unittest  flask.ext.script import manager project import app  manager = manager(app)  @manager.command def test():     """run unit tests."""     app.config.from_object('config.test')     tests = unittest.testloader().discover('tests', pattern='*.py')     unittest.texttestrunner(verbosity=1).run(tests) 

but when run python manage.py test tries initialise entire application if, example, haven't set environment variables throws keyerror project's __init__.py file so:

file "project/__init__.py", line 19, in <module> app.config.from_object(os.environ['project_settings'])

or if have set environment variable error missing database tables.

surely app should initialise once tests running , configuration variables have been set in test() function.

there few things need work.

  1. set missing environmental variables (like said).

  2. create test database tests use , have tests include setup , teardown function create tables , remove them respectively.

to around step 1 suggest using flask application factory pattern allows encapsulate application creation inside function. allow pass in whatever variables, etc necessary run application under test environment i.e.

def create_application(is_test=false):     app = flask(__name__)     if not is_test:        setup_app_not_for_test(app)     else:        setup_test_for_app(app)      return app 

in regards step number 2, if using pytest or nose or sort of testing framework uses fixtures can add setup , teardown functions add/drop database tables. additionally, if using orm sqlalchemy can create sqlite in memory database run tests against.

# create db instance app.config["sqlalchemy_database_uri"] = "sqlite://:memory:"  # create tables db.create_all()  # drop tables db.drop_all() 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -