[英]Unit test POST methods
我正在嘗試對以下內容進行單元測試
@app.route('/questionSearch', methods=['POST'])
def search():
body = request.get_json()
search_result = Question.query.filter(Question.question.ilike('%'+body['searchTerm']+'%')).all()
total_questions = Question.query.all()
formated_result = [result.format() for result in search_result]
return jsonify({
'success':True,
'questions': formated_result,
'totalQuestions': len(total_questions)
#'currentCategory': categories
})
我測試的方式是:
def test_add_question(self):
res =self.client().post('/questions',
json= {"question": "new Test question?", "answer":"Test answer", "difficulty":1, "category":1 })
data=json.loads(res.data)
self.assertEqual(res.status_code, 200)
self.assertEqual(data['success'],True)
它有效,但我如何避免向數據庫添加一百萬個問題,目前每次我運行測試腳本時,它都會向測試數據庫添加一個新問題。
我應該在拆解中寫一個刪除命令嗎?
您可以嘗試使用mock.patch重寫您的測試來模擬數據庫(並避免接觸數據庫),如下所示:
from unittest import mock
QUESTIONS = {"question": "new Test question?", "answer":"Test answer", "difficulty":1, "category":1 }
class TestRequestMethods(unittest.TestCase):
@mock.patch("yourapp.db_models.Question", return_value = QUESTIONS) # <- your package with Question data base model
def test_add_question(self, mock_question):
with app.test_client() as client:
res = client.post('/questions', json=QUESTIONS)
data=json.loads(res.data)
self.assertEqual(res.status_code, 200)
self.assertEqual(data['success'],True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.