1. 程式人生 > 其它 >自動化測試常用框架之pytest

自動化測試常用框架之pytest

執行方式

命令列模式 命令列中執行 pytest -s test_login.py 主函式模式 在 test_login.py 檔案中增加主函式 if __name__ == '__main__':   pytest.main(["-s", "login.py"] -s 支援控制檯列印

setup和teardown

函式級別

import pytest 

class TestLogin:

# 函式級開始
  def setup(self):
    print("------->setup_method")
# 函式級結束
  def teardown(self):
    print("------->teardown_method")
  def test_a(self):
    print("------->test_a")
  def test_b(self):
    print("------->test_b")
scripts/test_login.py ------->setup_method # 第一次 setup()
 ------->test_a .
------->teardown_method # 第一次 teardown() 
------->setup_method # 第二次 setup() 
------->test_b .
------->teardown_method # 第二次 teardown()

類級別

class TestLogin: 
# 測試類級開始 
    def setup_class(self): 
        
print("------->setup_class") # 測試類級結束 def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") def test_b(self): print("------->test_b")
scripts/test_login.py 
------->setup_class #
第一次 setup_class() ------->test_a . ------->test_b . ------->teardown_class # 第一次 teardown_class()

配置檔案

[pytest] 
# 新增命令列引數 
addopts = -s 
# 檔案搜尋路徑 
testpaths = ./scripts 
# 檔名稱 
python_files = test_*.py 
# 類名稱 
python_classes = Test* 
# 方法名稱 
python_functions = test_*
# 測試報告

addopts = -s --html=report/report.html


addopts = -s 表示命令列引數 testpaths,python_files,python_classes,python_functions 表示 哪一個資料夾 下的 哪一個檔案 下的 哪一個類 下的 哪一個函式 表示執行 scripts 資料夾下的 test 開頭 .py 結尾的檔案下的 Test 開頭的類下的 test開頭的函 數

控制引數執行順序

1. 標記於被測試函式,@pytest.mark.run(order=x) 2. 根據order傳入的引數來解決執行順序 3. order值全為正數或全為負數時,執行順序:值越小,優先順序越高 4. 正數和負數同時存在:正數優先順序高
import pytest 
class TestLogin: 
    def test_hello_001(self): 
        print("test_hello_001") 
    @pytest.mark.run(order=1) 
    def test_hello_002(self): 
        print("test_hello_002") 
    @pytest.mark.run(order=2)
    def test_hello_003(self): 
        print("test_hello_003") 

scripts/test_login.py 
test_hello_002 # 先執行2 
.test_hello_003 # 再執行3 
.test_hello_001

失敗重試

addopts = -s --reruns 3

跳過測試

import pytest 
class TestLogin: 
    def test_a(self): 
# test開頭的測試函式 
        print("------->test_a") 
        assert 1 # 斷言成功 
    @pytest.mark.skipif(condition=True, reason="xxx") 
    def test_b(self): 
        print("------->test_b") 
        assert 0 # 斷言失敗                    
scripts/test_login.py ------->test_a .s

資料引數化

import pytest 
class TestLogin: 
    @pytest.mark.parametrize("name", ["xiaoming", "xiaohong"]) 
    def test_a(self, name): 
        print(name) assert 1