Reputation: 343
I've been trying to test my Flask application that uses PyMongo. The application works fine, but when I execute unit tests, I constantly get an error message saying "working outside of application context". This message is thrown every time I run any unit test that requires access to the Mongo database.
I've been following this guide for unit testing: http://flask.pocoo.org/docs/testing/
My application's design is straight forward, similar to the standard Flask tutorial.
Did anyone already have the same issue?
class BonjourlaVilleTestCase(unittest.TestCase):
container = {}
def register(self, nickname, password, email, agerange):
"""Helper function to register a user"""
return self.app.post('/doregister', data={
'nickname' : nickname,
'agerange' : agerange,
'password': password,
'email': email
}, follow_redirects=True)
def setUp(self):
app.config.from_envvar('app_settings_unittests', silent=True)
for x in app.config.iterkeys():
print "Conf Key=%s, Value=%s" % (x, app.config[x])
self.app = app.test_client()
self.container["mongo"] = PyMongo(app)
self.container["mailer"] = Mailer(app)
self.container["mongo"].safe = True
app.container = self.container
def tearDown(self):
self.container["mongo"].db.drop()
pass
def test_register(self):
nickname = "test_nick"
password = "test_password"
email = "[email protected]"
agerange = "1"
rv = self.register(nickname, password, email, agerange)
assert "feed" in rv.data
if __name__ == '__main__':
unittest.main()
Upvotes: 4
Views: 3393
Reputation: 343
I've finally fixed the issue, which was due to the application context. It seems that when using PyMongo, as it manages the connection for you, the connection object must be used within the same context which initialized the PyMongo instance.
I had to modify the code, thus the PyMongo instance is initialized in the testable object. Later, this instance is returned via a public method.
Thus, to resolve the issue, all my DB requests in the unit tests must be executed under the with statement. Example follows
with testable.app.app_context():
# within this block, current_app points to app.
testable.dbinstance.find_one({"user": user})
Upvotes: 5
Reputation: 3402
Review Context Locals and test_request_context(): http://flask.pocoo.org/docs/quickstart/#context-locals
Upvotes: 1