Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.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 Flask应用程序运行,但初始单元测试失败_Python_Testing_Flask - Fatal编程技术网

Python Flask应用程序运行,但初始单元测试失败

Python Flask应用程序运行,但初始单元测试失败,python,testing,flask,Python,Testing,Flask,我刚刚开始对我的flask应用程序进行单元测试,测试时它无法返回200状态代码,尽管它工作得很好 以下是单元测试代码: # dev-environment/test_basic.py import unittest from application import application, db TEST_DB = "test.db" class BasicTests(unittest.TestCase): def setUp(self): application.c

我刚刚开始对我的flask应用程序进行单元测试,测试时它无法返回200状态代码,尽管它工作得很好

以下是单元测试代码:

# dev-environment/test_basic.py

import unittest
from application import application, db

TEST_DB = "test.db"

class BasicTests(unittest.TestCase):
    def setUp(self):
        application.config['TESTING'] = True
        application.config['DEBUG'] = False
        application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + TEST_DB
        self.application = application.test_client()
        db.drop_all()
        db.create_all()

        self.assertEqual(application.debug, False)

    def tearDown(self):
        pass

    def test_main_page(self):
        response = self.application.get("/welcome", follow_redirects=True)
        self.assertEqual(response.status_code, 200)


if __name__ == "__main__":
    unittest.main()
下面是application.py中我的“/欢迎”视图:

# dev-environment/application.py

@application.route("/welcome")
def welcome():
    return render_template("welcome.html")
运行单元测试文件时,我得到以下堆栈跟踪:

======================================================================
FAIL: test_main_page (__main__.BasicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_basic.py", line 22, in test_main_page
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.475s

FAILED (failures=1)

我无法重现
断言错误
错误。这实际上应该抛出一个
运行时错误
,因为没有应用程序绑定到当前上下文。添加类似于
application.app\u context().push()的内容作为
设置
函数的第一行。另外,您可能应该有类似于
self.client=application.test\u client()
的内容,而不是
self.application=application.test\u client()
。我刚刚做了这些更改,得到了相同的断言错误。但是,当我运行应用程序时,我可以很好地进入欢迎页面。通过将
print(app.url\u map)
添加到
test\u主页
@LukeKenworthy,检查你的应用程序中是否存在unittest上下文中的路由,这是你的代码的我的版本,测试通过得很好。