日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python單元測試框架pytest介紹_python

作者:小旭2021 ? 更新時間: 2022-08-22 編程語言

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

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

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

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

  • 1)pytest的簡單示例
  • 2)pytest的安裝
  • 3)pytest的特征、與unittest的區別。
  • 4) pytest如何自動識別用例。
  • 5)pytest框架中,用例的運行順序。

1)pytest寫用例很簡單

下面是一個簡單的例子:

import random

def test_demo():
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。文件內容如下:

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

 # 定義py文件下的測試用例
 def test_sample():
     print("我是測試用例!")

 class TestSample:

     def test_ss(self):
         print("我也是測試用例!")

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

原文鏈接:https://www.cnblogs.com/chenyablog/p/15162324.html

欄目分類
最近更新