「 python 」 unittest 單元測試

前言

項(xiàng)目開發(fā)流程

項(xiàng)目開發(fā)流程

不會(huì)自測的程序員不是合格的程序員

單元測試

單元測試就是開發(fā)者 編寫一小段代碼,檢驗(yàn)?zāi)繕?biāo)代碼的功能是否符合預(yù)期 。通常情況下,單元測試主要面向一些功能單一的模塊進(jìn)行。

在Web開發(fā)過程中,單元測試實(shí)際上就是一些“斷言”(assert)代碼。

斷言

斷言就是 判斷 一個(gè)函數(shù)或?qū)ο蟮囊粋€(gè)方法所產(chǎn)生的結(jié)果 是否符合你期望 的那個(gè)結(jié)果。 pythonassert斷言是聲明布爾值為真的判定,如果表達(dá)式為假會(huì)發(fā)生異常。單元測試中,一般使用assert來斷言結(jié)果。

導(dǎo)包

# 導(dǎo)入python自己的單元測試包,將別人寫好的代碼拿過來自己用
import unittest 

封裝

# 封裝:
class TestClass:
  """
  測試類,將測試方法封裝在類中
  """
 pass

繼承

# 繼承:
class Testclass(unittest.TestCase):
 """
 自己寫的TestClass含有unittest類的方法
 """
 #該方法會(huì)首先執(zhí)行,相當(dāng)于做測試前的準(zhǔn)備工作
 def setUp(self):
     pass

 #該方法會(huì)在測試代碼執(zhí)行完后執(zhí)行,相當(dāng)于做測試后的掃尾工作
 def tearDown(self):
     pass
 
 #測試代碼
 def test_app_exists(self): # 方法名必須以 ‘test_’ 作為前綴,unittest才能識(shí)別
     pass

代碼實(shí)現(xiàn)

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<form action="/login" method="post">
 <table>
     <tr>
         <td>姓名:</td>
         <td><input type="text" name="username"></td>
     </tr>
     <tr>
         <td>密碼:</td>
         <td><input type="password" name="password"></td>
     </tr>
 </table>
 <input type="submit" value="登錄">

</form>

</body>
</html>

demo_unittest.py

# -*- coding: utf-8 -*-
# @Time    : 2019/8/1 14:27
# @Author  : hang1720
# @Site    :
# @File    : demo_unittest.py
# @Software: PyCharm
import json
import unittest
from login import app


class LoginTesCase(unittest.TestCase):

 # 該方法會(huì)首先執(zhí)行,方法名為固定寫法
 def setUp(self):
     """
     再開始所執(zhí)行的方法之前,會(huì)調(diào)用該方法,該方法可以做一些初始化的操作,連接數(shù)據(jù)庫等
     :return:
     """
     app.testing = True
     # self.client = app.test_clinet()

 # 該方法會(huì)在測試代碼執(zhí)行完后執(zhí)行,方法名為固定寫法
 def tearDown(self):
     pass

 # 單元測試的方法要以test開頭
 def test_empty_username_password(self):
     """測試用戶名與密碼為空的情況[當(dāng)參數(shù)不全的話,返回errcode=-2]"""
     response = app.test_client().post('http://127.0.0.1:5000/login', data={})
     json_data = response.data
     json_dict = json.loads(json_data)

     self.assertIn('errcode', json_dict, '數(shù)據(jù)格式返回錯(cuò)誤')
     self.assertEqual(json_dict['errcode'], -2, '狀態(tài)碼返回錯(cuò)誤')

 def test_error_username_password(self):
     """測試用戶名和密碼錯(cuò)誤的情況[當(dāng)?shù)卿浢兔艽a錯(cuò)誤的時(shí)候,返回 errcode = -1]"""
     # response = app.test_client().post('/login', data={"username": "aaaaa", "password": "12343"})
     response = app.test_client().post('/login', data={"username": "aaaaa"}) # 參數(shù)傳遞不完整
     json_data = response.data
     json_dict = json.loads(json_data)
     self.assertIn('errcode', json_dict, '數(shù)據(jù)格式返回錯(cuò)誤')
     self.assertEqual(json_dict['errcode'], -1, '狀態(tài)碼返回錯(cuò)誤')

 def test_ok_username_password(self):
     """測試用戶名和密碼都正確的情況[當(dāng)?shù)卿浢兔艽a都正確的時(shí)候,返回 errcode = 0]"""
     response = app.test_client().post('/login', data={"username": "python", "password": "python"})
     json_data = response.data
     json_dict = json.loads(json_data)
     self.assertIn('errcode', json_dict, '數(shù)據(jù)格式返回正確')
     self.assertEqual(json_dict['errcode'], 0, '狀態(tài)碼返回正確')


if __name__ == '__main__':
 # login = LoginTesCase()
 # login.test_empty_username_password()
 unittest.main()

login.py

# -*- coding: utf-8 -*-
# @Time    : 2019/8/1 14:27
# @Author  : hang1720
# @Site    : 
# @File    : login.py
# @Software: PyCharm

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
# app.json_encoder = JSONEncode
#

@app.route('/')
def index_page():
 return "index_page"


# 用戶登錄
# 1. 如果傳入的參數(shù)不足,會(huì)返回 errcode = -2
# 2. 如果傳入的賬號(hào)和密碼都不正確,會(huì)返回 errcode = -1
# 3. 如果賬號(hào)與密碼都正確, errcode = 0

@app.route('/login', methods=['GET', 'POST'])
def login_index():
 if request.method == "GET":
     return render_template('/login.html')
 username = request.form.get('username')
 password = request.form.get('password')
 print(username)
 print(password)

 # 判斷參數(shù)是否為空
 if not all([username, password]):
     result = {
         "errcode": -2,
         "errmsg": "params error"
     }
     return jsonify(result)

 # 如果賬號(hào)密碼正確
 # 判斷賬號(hào)密碼是否正確
 if username == 'python' and password == 'python':
     result = {
         "errcode": 0,
         "errmsg": "success"
     }
     return jsonify(result)
 else:
     result = {
         "errcode": -1,
         "errmsg": "wrong username or password"
     }
     return jsonify(result)


if __name__ == '__main__':
 app.run(debug=True)

? 單元測試結(jié)果

單元測試.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容