我一直在尝试测试使用pymongo的烧瓶应用程序。该应用程序工作正常,但是当我执行单元测试时,我会不断收到一条错误消息,上面写着"在应用程序上下文之外工作"。每次我运行任何需要访问Mongo数据库的单位测试时,都会抛出此消息。
我一直在遵循本指南进行单元测试:http://flask.pocoo.org/docs/testing/
我的应用程序的设计很简单,类似于标准瓶教程。
有人已经遇到了同样的问题吗?
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 = "test@email.com"
agerange = "1"
rv = self.register(nickname, password, email, agerange)
assert "feed" in rv.data
if __name__ == '__main__':
unittest.main()
我终于解决了问题,这是由于应用程序上下文所致。看来,当使用Pymongo时,当它为您管理连接时,必须在初始化Pymongo实例的相同上下文中使用连接对象。
我必须修改代码,因此Pymongo实例在可测试的对象中初始化。后来,通过公共方法返回此实例。
因此,要解决问题,我的所有DB请求必须在下执行语句。示例遵循
with testable.app.app_context():
# within this block, current_app points to app.
testable.dbinstance.find_one({"user": user})
评论上下文当地人和test_request_context():http://flask.pocoo.org/docs/quickstart/#context-locals