Flask MongoDB错误:"在应用程序上下文之外工作"

ryz*_*hiy 4 python unit-testing mongodb pymongo flask

我一直在尝试测试使用PyMongo的Flask应用程序.应用程序工作正常,但是当我执行单元测试时,我不断收到一条错误消息"工作在应用程序上下文之外".每次运行需要访问Mongo数据库的任何单元测试时,都会抛出此消息.

我一直在关注这个单元测试指南:http: //flask.pocoo.org/docs/testing/

我的应用程序的设计很简单,类似于标准的Flask教程.

有没有人有同样的问题?

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()
Run Code Online (Sandbox Code Playgroud)

ryz*_*hiy 5

我终于解决了问题,这是由应用程序上下文引起的.似乎在使用PyMongo时,因为它为您管理连接,所以必须在初始化PyMongo实例的同一上下文中使用连接对象.

我不得不修改代码,因此PyMongo实例在testable对象中初始化.稍后,通过公共方法返回此实例.

因此,要解决此问题,必须在with语句下执行单元测试中的所有数据库请求 .示例如下

with testable.app.app_context():
    # within this block, current_app points to app.
    testable.dbinstance.find_one({"user": user})
Run Code Online (Sandbox Code Playgroud)