[英]Why am I expecting a status code of 200 but got a status code of 404 while unit testing in python?
我正在使用文件的 unittest 和 pytest 在 python 中編寫單元測試用例。 在眾多函數中,我無法理解為什么它不能作為成功通過的測試用例執行。 這是顯示設置頁面的函數,成功調用后它會顯示一個 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>
請幫我解決這個問題。
嘗試更改以便self.client
將在app_context()
執行,例如
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):
with self.app.app_context():
response = self.client.get('/settings', follow_redirects=True)
self.assertEqual(response.status_code, 200)
我創建了相同的場景,它適用於和不app_context
對我來說。 我也使用這個命令來執行測試:
python -m unittest tests/test_the_test.py
這也取決於您如何設置應用程序。 例如下面使用python3.7
。
我的是這樣的:
├── app.py
├── index
│ ├── __init__.py
│ └── routes.py
└── tests
└── test_the_test.py
我的app.py
是這樣的:
from flask import Flask
def create_app():
app = Flask(__name__)
from index import bp
app.register_blueprint(bp)
return app
我的index/__init__.py
像這樣:
from flask import Blueprint
bp = Blueprint(__name__, '/')
from index import routes
我的index/routes.py
像這樣:
from index import bp
from flask import jsonify
@bp.route('/test')
def test():
print('goes here?')
return jsonify({'result': True})
我的tests/test_the_test.py
像這樣:
import unittest
from app import create_app
class MyApp(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.client = self.app.test_client(self)
def tearDown(self):
pass
def test_settings_passed(self):
response = self.client.get('/test', follow_redirects=True)
self.assertEqual(response.status_code, 200)
def test_settings_failed(self):
response = self.client.get('/test_not_exist', follow_redirects=True)
self.assertEqual(response.status_code, 404)
執行這個命令:
python -m unittest tests/test_the_test.py
我的設置工作正常,進行測試並在端點存在和不存在時給出正確的結果。
結果:
python -m unittest tests/test_the_test.py
.goes here?
.
----------------------------------------------------------------------
Ran 2 tests in 0.006s
OK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.