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 -*-
 3 # Name: test_sample_1.py
 4 # Author: 簡
 5 # Time: 2019/6/27
 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 -*-
# Name: test_sample_2
# Author: 簡
# Time: 2019/6/27

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文件當中,按照代碼順序,先搜索到的用例先執行。

 

*******請大家尊重原創,如要轉載,請注明出處:轉載自:https://www.cnblogs.com/Simple-Small,謝謝!!*******
*******有任何疑問,歡迎加入軟件測試交流群:666056120(加群時,請備注:博客園-簡)。博主QQ:2501768591*******


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM