Context
I'm creating Flask
app connected to mongodb
using MongoEngine via flask-mongoengine extension. I create my app using application factory pattern
as specified in configuration instructions.
Problem
While running test(s), I specified testing database named datazilla_test
which is passed to mongo
instance via mongo.init_app(app)
. Even though my app.config['MONGODB_DB']
and mongo.app.config['MONGODB_DB']
instance has correct value (datazilla_test
), this value is not reflected in mongo
instance. Thus, when I run assertion assert mongo.get_db().name == mongo.app.config['MONGODB_DB']
this error is triggered AssertionError: assert 'datazzilla' == 'datazzilla_test'
Question
What am I doing wrong? Why database connection persist with default database datazzilla
rather, than datazilla_test
? How to fix it?
Source Code
# __init__.py
from flask_mongoengine import MongoEngine
mongo = MongoEngine()
def create_app(config=None):
app = Flask(__name__)
app.config['MONGODB_HOST'] = 'localhost'
app.config['MONGODB_PORT'] = '27017'
app.config['MONGODB_DB'] = 'datazzilla'
# override default config
if config is not None:
app.config.from_mapping(config)
mongo.init_app(app)
return app
# conftest.py
import pytest
from app import mongo
from app import create_app
@pytest.fixture
def app():
app = create_app({
'MONGODB_DB': 'datazzilla_test',
})
assert mongo.get_db().name == mongo.app.config['MONGODB_DB']
# AssertionError: assert 'datazzilla' == 'datazzilla_test'
return app