[英]How to write a unit test using Pytest for the main function in Python
[英]How to unit test “request.form” in python using pytest?
我有一個 function 在 if 條件中有一個“request.form”,在測試它時,我發現它們下面的語句缺少語句。 這是來自 function function 片段的片段
if 'industry' in request.form:
industry_sele = request.form['industry']
country_sele = request.form['country']
size_sele = request.form['size']
if not request.form.get('open'):
filters['open'] = False
if 'open' in status_list:
status_list.remove('open')
if not request.form.get('assign'):
filters['assign'] = False
if 'allocated' in status_list:
status_list.remove('allocated')
if not request.form.get('closed'):
filters['closed'] = False
if 'converted' in status_list:
status_list.remove('converted')
if 'not converted' in status_list:
status_list.remove('not converted')
當我使用python3 -m pytest --cov-report term-missing --cov=projfolder/
檢查覆蓋率時,“如果 request.form 中的'industry':”之后的所有行都丟失了這就是我編寫單元測試用例的方式. test_function.py
def test_get_list_csv_manager(self):
with self.client.session_transaction() as session:
session['role'] = 'manager'
session['id'] = 2
res = self.client.get("/getListCSV", follow_redirects=True)
self.assertEqual(res.status_code, 200)
這段單元測試代碼運行成功,但沒有覆蓋上面的代碼塊。 如何對 request.form 進行單元測試? 請幫忙!!
最后,我找到了這段代碼的答案。 我所做的是編寫了兩個單獨的函數來處理兩個 if 語句。
def test_request_form_csv(self):
with self.client.session_transaction() as session:
session['role'] = 'user'
session['id'] = 1
r = self.client.get('/getListCSV', data={'industry': 'All', 'country': 'UK', 'size': 'All'})
self.assertEqual(r.status_code, 200)
def test_request_args_opened(self):
with self.client.session_transaction() as session:
session['role'] = 'user'
session['id'] = 1
r = self.client.get('/getListCSV',
query_string={'industry': 'Compliance', 'country': 'USA', 'size': 'Midsize', 'open': False, 'assign': False,
'closed': False})
self.assertEqual(r.status_code, 200)
這些都涵蓋了我的測試用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.