unittest 單元測試框架教程 1-執行測試指令碼

ZOO發表於2020-08-23

原文連結
unittest單元測試框架教程1-執行測試指令碼

unittest模組提供了一系列建立和執行測試的工具。這一段落演示了這些工具的一小部分,但也足以滿足大部分使用者的需求。

首先我們為了學習使用Django REST framework執行一個可以返回狀態和內容的介面,程式碼如下:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET', 'POST'])
def add(request):
response = Response()
if request.method == 'POST':
response.status_code = 200
redata = {}
redata['status'] = 1
redata['message'] = '請求成功'
redata['data'] = request.data['a'] + request.data['b']
response.data = redata
return response
else:
return response

@api_view(['GET', 'POST'])
def minus(request):
response = Response()
if request.method == 'POST':
response.status_code = 200
redata = {}
redata['status'] = 1
redata['message'] = '請求成功'
redata['data'] = request.data['a'] - request.data['b']
response.data = redata
return response
else:
return response

@api_view(['GET', 'POST'])
def chengfa(request):
response = Response()
if request.method == 'POST':
response.status_code = 200
redata = {}
redata['status'] = 1
redata['message'] = '請求成功'
redata['data'] = request.data['a'] + request.data['b']
response.data = redata
return response
else:
return response

當然也可以用其它工具建立。
測試一下功能,乘法故意寫錯以便於進行測試unittest的功能。

為了測試3個函式是否正確,我們利用unittest進行測試。

import unittest
import requests
import json

class TestMath(unittest.TestCase):
def setUp(self):
self.a = 0
self.b = 0

def tearDown(self):
print(self.a)
print(self.b)

def test_add(self):
'''測試加法程式'''
self.a = 1
self.b = 1
headers = {
'Content-Type': "application/json",
}
reqdata = {'a':self.a,'b':self.b}
resp = requests.request(method='POST', url='http://127.0.0.1:8000/testapi/add/', verify=False, headers=headers, json=reqdata)
resp = json.loads(resp.text)
self.assertEqual(resp['status'],1)
self.assertEqual('請求成功',resp['message'])
self.assertEqual(resp['data'], self.a + self.b)

def test_minus(self):
'''測試減法程式'''
self.a = 2
self.b = 2
headers = {
'Content-Type': "application/json",
}
reqdata = {'a':self.a,'b':self.b}
resp = requests.request(method='POST', url='http://127.0.0.1:8000/testapi/minus/', verify=False, headers=headers, json=reqdata)
resp = json.loads(resp.text)
self.assertEqual(resp['status'],1)
self.assertEqual(resp['message'], '請求成功')
self.assertEqual(resp['data'], self.a - self.b)

def test_chengfa(self):
'''測試乘法程式'''
self.a = 3
self.b = 3
headers = {
'Content-Type': "application/json",
}
reqdata = {'a':self.a,'b':self.b}
resp = requests.request(method='POST', url='http://127.0.0.1:8000/testapi/chengfa/', verify=False, headers=headers, json=reqdata)
resp = json.loads(resp.text)
self.assertEqual(resp['status'],1)
self.assertEqual(resp['message'], '請求成功')
self.assertEqual(resp['data'], self.a * self.b)

if __name__ == '__main__':
unittest.main()

一個簡單的測試指令碼完成了,使用pycharm的話點選右上角的綠色執行按鈕即可執行。直接執行看下結果:

D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/newtest.py
.F.
1
1
3
3
2
2
======================================================================
FAIL: test_chengfa (__main__.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.045s

FAILED (failures=1)

我們發現第三個方法先執行,這是因為使用main或命令列執行時,載入器按照方法名進行排序。

unittest.main() 提供了一個測試指令碼的命令列介面。unittest 模組可以通過命令列執行模組、類和獨立測試方法的測試:

python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method
python -m unittest tests/test_something.py

python -m unittest -h用於獲取命令列引數選項列表,看下執行指令碼時可以用到的重要的引數。

執行引數

-k

只執行匹配模式或子串的測試方法和類。可以多次使用這個選項,以便包含匹配子串的所有測試用例。可以使用萬用字元(*)的模式對測試名稱進行匹配。另外,該匹配是大小寫敏感的。

python -m unittest newtest.py -k *

(venv) D:\PycharmProjects\untitled>python -m unittest newtest.py -k *
1
1
.3
3
F2
2
.
======================================================================
FAIL: test_chengfa (newtest.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\PycharmProjects\untitled\newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.049s

FAILED (failures=1)

-f, --failfast

當為true時,當出現第一個錯誤或者失敗時,停止執行測試。

加入引數執行

D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/newtest.py
1
1
3
3
.F
======================================================================
FAIL: test_chengfa (__main__.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 2 tests in 0.038s

FAILED (failures=1)

失敗後就停下

-b, --buffer

如果為True,在測試執行時,標準輸出流與標準錯誤流會被放入緩衝區。成功的測試的執行時輸出會被丟棄;測試不通過時,測試執行中的輸出會正常顯示,錯誤會被加入到測試失敗資訊。

加入引數執行

(venv) D:\PycharmProjects\untitled>python -m unittest newtest.py -b
.F
Stdout:
3
3
.
======================================================================
FAIL: test_chengfa (newtest.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\PycharmProjects\untitled\newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

Stdout:
3
3

----------------------------------------------------------------------
Ran 3 tests in 0.046s

FAILED (failures=1)

只列印了錯誤的引數

'--verbose'

  • 0 不列印描述及任何成功失敗標誌,相當於命令列的-q

  • 1 不列印描述只列印失敗標誌,預設

  • 2 列印描述內容並列印成功及失敗標誌,相當於命令列的-v

  • 加入引數verbose=0執行
D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/newtest.py
1
1
3
3
2
2
======================================================================
FAIL: test_chengfa (__main__.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.047s

FAILED (failures=1)
  • 加入引數verbose=1執行
D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/newtest.py
1
1
3
3
.F.
======================================================================
FAIL: test_chengfa (__main__.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.059s

FAILED (failures=1)
2
2
  • 加入引數verbose=2執行
D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/newtest.py
test_add (__main__.TestMath)
測試加法程式 ... ok
1
1
test_chengfa (__main__.TestMath)
測試乘法程式 ... FAIL
3
3
test_minus (__main__.TestMath)
測試減法程式 ... ok

======================================================================
FAIL: test_chengfa (__main__.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.062s

FAILED (failures=1)
2
2

-W --warnings

“error” | 將警告轉換為異常

“ignore” | 不會列印匹配的警告

“always” | 總是列印匹配的警告

“default” | 列印發出警告的每個位置的首次出現的匹配警告

“module” | 將為發出警告的每個模組列印首次發生的匹配警告

“once” | 僅列印第一次匹配的警告,不管位置如何

預設為default

--locals

在回溯中顯示區域性變數。

python -m unittest newtest.py --locals

(venv) D:\PycharmProjects\untitled>python -m unittest newtest.py --locals
1
1
.3
3
F2
2
.
======================================================================
FAIL: test_chengfa (newtest.TestMath)
測試乘法程式
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\PycharmProjects\untitled\newtest.py", line 56, in test_chengfa
self.assertEqual(resp['data'], self.a * self.b)
headers = {'Content-Type': 'application/json'}
reqdata = {'a': 3, 'b': 3}
resp = {'status': 1, 'message': '請求成功', 'data': 6}
self = <newtest.TestMath testMethod=test_chengfa>
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 3 tests in 0.052s

###
轉載請註明出處

相關文章