在我的Flask应用程序中运行python的unittest
时,使用多个TestCase
类时,我返回了404状态代码。
我已经尝试过flask_testing
并遇到了类似的问题。我之所以选择unittest
,是因为它在在线查找文档方面更受欢迎并且更易于使用。
test_global.py
from server import create_app
class Global(unittest.TestCase):
def setUp(self):
self.app = create_app(testing=True)
self.client = self.app.test_client()
self.client.testing = True
# tests different cookie redirect
def test_different_cookie_redirect(self):
self.client.set_cookie('127.0.0.1', 'lang', 'en')
response = self.client.get('/fr')
# this passes
self.assertEqual(response.status_code, 302)
以上内容按预期工作。如果cookie不同,则页面应重定向。当我想添加另一个类时,会发生问题。
class Index(unittest.TestCase):
def setUp(self):
self.app = create_app(testing=True)
self.client = self.app.test_client()
self.client.testing = True
# tests same cookie redirect
def test_same_cookie_redirect(self):
self.client.set_cookie('127.0.0.1', 'lang', 'fr')
response = self.client.get('/fr')
# this returns a 404 and fails the test
self.assertEqual(response.status_code, 200)
这是错误
Traceback (most recent call last):
File "/test_global.py", line 55, in test_same_cookie_redirect
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
如果我删除Global
类,则Index
测试将起作用,并返回status_code
中的200
。为什么两个都不能同时工作?
我选择使用多个类的原因是能够将代码拆分到不同的文件中,并运行python -m unittest discover
来处理所有这些文件。