【发布时间】:2020-10-08 05:21:54
【问题描述】:
我正在 python 中使用 unittest 和 pytest 为一个文件编写一个单元测试用例。在众多功能中,我无法理解为什么它不能作为成功通过的测试用例执行。 这是一个显示设置页面的函数,调用成功后会显示一个html页面。
@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
global application_inst
if request.method == 'POST':
print("Setting changed")
return render_template('settings.html', user=session['user'], application=application_inst)
函数的单元测试用例如下:
class MyApp(unittest.TestCase):
def setUp(self):
self.app = create_app(db)
self.client = self.app.test_client(self)
with self.app.app_context():
# create all tables
db.create_all()
def tearDown(self):
pass
def test_settings_passed(self):
response = self.client.get('/settings', follow_redirects=True)
self.assertEqual(response.status_code, 200)
我在堆栈跟踪中得到的错误是:
test_app.py::MyApp::test_settings_passed FAILED [100%]ENV :default
############ INIT ############
############ INIT ############
############ INIT ############
200 != 404
Expected :404
Actual :200
<Click to see difference>
请帮帮我。
【问题讨论】:
-
您正在比较相同的状态代码两次,并期望第二次得到不同的输出?同样
with pytest.raises(AssertionError)在那一点上没有意义,也许你想做别的事情?顺便说一句 - 不要混合 unittest 和 pytest - 其中一些可能有效,有些则不会。改用其中之一。 -
即使我在遇到相同错误时检查相同的状态代码。我想看看我对 /settings 的调用是否让我得到状态码 200。 @MrBeanBremen
-
啊,好吧,您在
assertEqual中反转了预期和实际参数,我没有注意到。所以你期待 200,但得到 404。 -
你是对的!为什么它会以它发生的方式发生? @MrBeanBremen
-
@SimeonNedkov RuntimeError:应用程序无法为请求独立的 URL 生成创建 URL 适配器。您可以通过设置 SERVER_NAME 配置变量来解决此问题。
标签: python unit-testing flask python-unittest