1. 程式人生 > 其它 >pytest學習(一) - 什麼是單元測試?

pytest學習(一) - 什麼是單元測試?

pytest是python語言中一款強大的單元測試框架,用來管理和組織測試用例,可應用在單元測試、自動化測試工作中。

unittest也是python語言中一款單元測試框架,但是功能有限,沒有pytest靈活。

就像:蘋果電腦mac air和mac pro一樣。都是具備同樣的功能,但是好用,和更好用。

本文包含以下幾個內容點:

1)pytest的簡單示例

2)pytest的安裝

3)pytest的特徵、與unittest的區別。

4) pytest如何自動識別用例。

5)pytest框架中,用例的執行順序。

1)pytest寫用例很簡單,下面是一個簡單的例子:

1 import random
2 
3 
4 def test_demo():
5     assert 7 == random.randint(0,10)

執行結果如下:

============================= test session starts =============================
platform win32 -- Python 3.7.2, pytest-4.6.3, py-1.8.0, pluggy-0.12.0
rootdir: D:\Pychram-Workspace\STUDY_PYTEST
plugins: allure-pytest-2.6.5, html-1.21.1, metadata-1.8.0, rerunfailures-7.0collected 1 item

simple.py F
simple.py:10 (test_demo)
7 != 6

Expected :6
Actual   :7

========================== 1 failed in 0.14 seconds ===========================

2)pytest的安裝

安裝命令:

pip install pytest

3)pytest的特徵、與unittest的區別。

pytest的特徵如下:

3.1 自動識別測試用例。(unittest當中,需要引入TestSuite,主動載入測試用例。)

3.2 簡單的斷言表達:assert表示式即可。(unittest當中,self.assert*)

3.3 有測試會話、測試模組、測試類、測試函式級別的fixture。(unittest當中是測試類、測試函式級別的fixture)

3.4有非常豐富的外掛,目前在600+,比如allure外掛。(unittest無)

3.5測試用例不需要封裝在測試類當中。(unittest中需要自定義類並繼承TestCase)

那麼pytest是如何自動識別測試用例的呢?我們在編寫pytest用例的時候,需要遵守哪些規則呢?

4) pytest如何自動識別用例

 識別規則如下:

1、搜尋根目錄:預設從當前目錄中搜集測試用例,即在哪個目錄下執行pytest命令,則從哪個目錄當中搜尋;

2、搜尋規則:

1)搜尋檔案:符合命名規則 test_*.py 或者 *_test.py 的檔案

2)在滿足1)的檔案中識別用例的規則:

2.1)以test_開頭的函式名;

2.2)以Test開頭的測試類(沒有__init__函式)當中,以test_開頭的函式

示例:在D:\pycharm_workspace目錄下,建立一個python工程,名為study_pytest。在工程下,建立一個python包,包名為TestCases。

在包當中,建立一個測試用例檔案:test_sample_1.py。檔案內容如下:

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 6 
 7 # 定義py檔案下的測試用例
 8 def test_sample():
 9     print("我是測試用例!")
10 
11 class TestSample:
12 
13     def test_ss(self):
14         print("我也是測試用例!")
15 
16     def hello_pytest(self):
17         print("hi,pytest,我不是用例哦!!")

按照上面定義的搜尋規則,需要跳轉到工程目錄,然後再執行命令:pytest -v 。 執行結果如下:

讓我們愉快的加進來第2個測試檔案:test_sample_2.py,內容如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

def add(a,*args):
    sum = a
    for item in args:
        sum += item
    return sum


def test_add_two_number():
    assert 33 == add(11,22)
    assert 55.55 == add(22.22,33.33)


def test_add_three_number():
    assert 101 == add(10,90,1)

再次執行命令:pytest -v 得到如下結果:

通過多個用例檔案的執行,可以看出用例的執行順序。

5) pytest中用例的執行順序

原則:先搜尋到的py檔案中的用例,先執行。在同一py檔案當中,按照程式碼順序,先搜尋到的用例先執行。