0

我现在正在我的烧瓶项目中设置单元测试。我的测试文件如下:

import flask_testing
import unittest
from flask import Flask
from flask_testing import TestCase

class MyTest(TestCase):

    def setUp(self):
        pass # Executed before each test

    def tearDown(self):
        pass # Executed after each test

    def create_app(self):
        app = Flask(__name__)
        # app.config['TESTING'] = True
        return app

    def test_greeting(self):
        response = self.client.get('/')
        print("should return 404 on landing page")
        self.assertTemplateUsed('index.html')
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()

当我运行这些测试时,assertTemplateUsed不返回模板并且response.status_code是 404。我想这是因为 self 实际上不是我的应用程序出于某种原因?当我运行应用程序时,根地址肯定会返回 index.html。

我设置create_app错了吗?任何帮助表示赞赏。

4

2 回答 2

1

您需要在setUp()函数中创建 Flask 应用程序实例。目前该create_app()函数根本没有被调用。

像这样更改您的代码:

import flask_testing
import unittest
from flask import Flask
from flask_testing import TestCase

class MyTest(TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client(use_cookie=True)

    def tearDown(self):
        self.app_context.pop()

    def test_greeting(self):
        response = self.client.get('/')
        print("should return 404 on landing page")
        self.assertTemplateUsed('index.html')
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()

setUp()函数在每个测试函数之前被调用。首先,您将创建 Flask 应用程序的新实例。如果您想访问应用程序上下文中的项目,最好将其推送到您的setUp()函数中并将其弹出到您的tearDown()函数中。如果您不从您的测试函数访问 app_context 项目(如数据库会话对象),您可以忽略它。最后,您需要在setUp()函数中创建测试客户端。您在帖子中错过了那部分,但我猜您在代码的其他地方做了。

于 2017-03-24T09:37:45.200 回答
1

在您的 setUp 函数中,您需要提供一个测试客户端来发出请求。尝试这样的事情。

def setUp(self):
    # this test client is what flask-testing will use to make your requests
    self.app = app.test_client()

查看更多信息如何测试 Flask 应用程序

于 2018-01-24T03:39:58.567 回答