Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 烧瓶MongoDB错误:";“在应用程序上下文之外工作”;_Python_Unit Testing_Mongodb_Flask_Pymongo - Fatal编程技术网

Python 烧瓶MongoDB错误:";“在应用程序上下文之外工作”;

Python 烧瓶MongoDB错误:";“在应用程序上下文之外工作”;,python,unit-testing,mongodb,flask,pymongo,Python,Unit Testing,Mongodb,Flask,Pymongo,我一直在尝试测试使用PyMongo的Flask应用程序。应用程序工作正常,但当我执行单元测试时,我经常收到一条错误消息,上面写着“在应用程序上下文之外工作”。每当我运行任何需要访问Mongo数据库的单元测试时,都会抛出此消息 我一直遵循这个单元测试指南: 我的应用程序的设计是直接的,类似于标准的烧瓶教程 有人已经有同样的问题了吗 class BonjourlaVilleTestCase(unittest.TestCase): container = {} def registe

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

我一直遵循这个单元测试指南:

我的应用程序的设计是直接的,类似于标准的烧瓶教程

有人已经有同样的问题了吗

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实例在可测试对象中初始化。稍后,通过公共方法返回该实例

因此,为了解决这个问题,单元测试中的所有my DB请求都必须在with语句下执行。下面是一个例子

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

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