4

我一直在尝试测试使用 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()
4

2 回答 2

5

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

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

因此,为了解决这个问题,我在单元测试中的所有数据库请求都必须在 with语句下执行。示例如下

with testable.app.app_context():
    # within this block, current_app points to app.
    testable.dbinstance.find_one({"user": user})
于 2012-11-12T09:14:03.373 回答
1

查看 Context Locals 和 test_request_context(): http: //flask.pocoo.org/docs/quickstart/#context-locals

于 2012-11-09T00:02:13.847 回答