【问题标题】:Flask MongoDB error: "working outside of application context"烧瓶 MongoDB 错误:“在应用程序上下文之外工作”
【发布时间】:2012-10-29 05:58:22
【问题描述】:

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

【问题讨论】:

  • 你能发一个单元测试让我们看看吗?

标签: python unit-testing mongodb flask pymongo


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    查看上下文局部变量和 test_request_context(): http://flask.pocoo.org/docs/quickstart/#context-locals

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多