I'm lost with trying to write tests to my Flask application I'm lost with trying to write tests to my Flask application flask flask

I'm lost with trying to write tests to my Flask application


The db fixture provided by flask-cookiecutter is prone to locking up, and this is probably what's hanging your tests (this was the case for me when I first started writing tests for a flask-cookiecutter based app).

Here's a better db fixture (to replace the one in your tests/conftest.py file):

@pytest.yield_fixture(scope='function')def db(app):    _db.app = app    with app.app_context():        _db.session.remove()        _db.drop_all()        _db.create_all()    yield _db    _db.session.remove()    _db.drop_all()    ## This dispose() call is needed to avoid the DB locking    ## between tests.    ## Thanks to:    ## http://stackoverflow.com/a/18293157/2066849    _db.get_engine(_db.app).dispose()

Could also be an issue with the app context, but that isn't prone to completely hang the tests as much as the DB session is.

You should also consider changing this fixture (and most of the other fixtures) to scope='session', so the DB doesn't have to be re-created for each individual test (and so the app doesn't have to be re-instantiated, although that's trivial overhead compared to the DB). But then you have to do some cleanup manually, after individual tests that modify DB records.


You need to use the right app context

 def test_create_admin_user(db, testapp):    with app.app_context():      password = bcrypt.generate_password_hash('test')      User.create(            uid='00000000000000000000',            email='john@doe.com',            password=password,            active=1        )      user = User.query.filter_by(email='j@d.com').first()      assert user.email == 'j@d.com'

See https://github.com/Leo-G/Flask-Scaffold/blob/master/scaffold/app/tests.py for a full example