1. 程式人生 > 其它 >pytest框架基本知識

pytest框架基本知識

pytest框架

一、簡介

1. 什麼是pytest

python的測試框架,是第三方的,成熟的,功能齊全的。可使用python原生的斷言語句。

2. 安裝

pip install -U pytest

二、基本使用

1.建立測試用例

(1)簡單的函式

點選檢視程式碼
# 函式
def func(x):
    return x + 1
# 測試函式(對於函式要test開頭)
def test_answer():
    assert func(3) == 5

(2)測試用例類

點選檢視程式碼
# 類
# 需要以Test開頭
class TestClass:
    # 需要以test開頭
    def test_one(self):
        x = 'this'
        assert 'h' in x

    def test_two(self):
        x = 'hello'
        assert hasattr(x, 'check')

2.收集測試用例的方法

(1)標準發現規則

  1. 如果不給引數,預設從當前目錄或者配置中的testpath下收集測試用例
  2. 預設會遞迴所有目錄,二級以上的目錄要加__init__.py
  3. 在目錄中收集所有test_.py和_test.py的模組
  4. 在上述模組中收集
  • 以test作為字首的類外面的函式
  • 以Test作為字首的類(不能包含__init__方法)裡面的以test作為字首的方法

3.執行測試用例

(1)通過pytest命令來執行測試用例

pytest [options] [file_or_dir] [file_or_dir]

(2)通過python程式碼執行

點選檢視程式碼
import pytest
def test_sth():
    assert 1 == 1

if __name__ =='__main__':
    pytest.main(["-s","-v", "demo1.py"])

(3)執行順序

在模組級別採用模組名的ascii碼排序,在模組的內部根據從上往下的定義順序。會先執行test_a內部函式,從上往下,再去執行test_b內部函式,從上往下

4.斷言

在pytest中只需要使用python語言的標準斷言語句assert來斷言

5.前置後置

(1)經典的xunit風格

可以基於模組/類函式實現fixture

①模組級別setupteardown

如果在單個模組中需要在整個模組前後執行一次:

def setup_module():
    """在整個模組裡的用例執行前執行一次"""

    
def teardown_module():
    """在整個模組裡的用例執行完畢之後執行一次"""

##### ②類級別
```python

@classmethod
def setup_class(cls):
    """類前置"""

@classmethod
def teardown_class(cls):
    """類後置"""
③方法級別
def setup_method(self):
    """類中方法級前置"""
    
def teardown_method(self):
    """類中方法級別後置"""
④函式級別
def setup_function():
    """函式級前置"""
    
def teardown_function():
    """函式級別後置"""

(2)unittest風格


@classmethod
def setUpClass(cls) -> None:
    pass
@classmethod
def tearDownClass(cls) -> None:
    pass
def setUp(self) -> None:
    pass
def tearDown(self) -> None:
    pass

(3)@pytest.fixture

①定義
@pytest.fixture()
def fixture_func():
    print('前置條件')
②呼叫夾具
  1. 通過裝飾器@pytest.mark.usefixtures(fixture_name)
  2. 通過在測試函式中定義與夾具函式名同名的引數
點選檢視程式碼
import pytest

@pytest.fixture()
def fixture_func():
    print('前置條件')
    yield '1'
    print('後置條件')

@pytest.mark.usefixtures('fixture_func')
def test_some():
    print('*****some*****')

def test_one(fixture_func):
    print('fixture_func=' + fixture_func)

if __name__ == '__main__':
    pytest.main(["-s","-v", "testcases"])
③夾具的作用範圍

@pytest.fixture() 有一個scope引數可以指定夾具的作用範圍

scope的取值有:

  • function 預設範圍,函式範圍
  • class 在類中最後一個測試完成後結束
  • module 在整個模組中最後一個測試完成後結束
  • package 在整個包中的最後一個測試完成後結束
  • session 在一次會話中最後一個測試完成後結束
④共享夾具

如果一個夾具需要被多個測試檔案使用,則可以將其移至一個conftest.py檔案中,不需要在測試中帶入,他會自動被發現

點選檢視程式碼
import pytest

@pytest.fixture()
def fixture_func():
    print('前置條件')
    yield '1'
    print('後置條件')

@pytest.fixture(scope='module',autouse=True)
def module_fixture():
    print('模組級別前置')
    yield
    print('模組級別後置')

@pytest.fixture(scope='class')
def class_fixture():
    print('類級別前置')
    yield
    print('類級別後置')

@pytest.fixture(scope='package',autouse=True)
def package_fixture():
    print('包級別前置')
    yield
    print('包級別後置')

@pytest.fixture(scope='session',autouse=True)
def session_fixture():
    print('會話級別前置')
    yield
    print('會話級別後置')
⑤使用夾具的夾具(夾具的繼承)
點選檢視程式碼
import pytest

@pytest.fixture()
def someone():
    print('someone')
    yield 1
    print('someone')

@pytest.fixture()
def sometwo(someone):
    print('sometwo')
    yield 1 + someone
    print('sometwo')

def test_some(sometwo):
    print(sometwo)

if __name__ =='__main__':
    pytest.main(["-s","-v"])
⑥引數化

使用裝飾器@pytest.mark.parametrize

點選檢視程式碼
import pytest

test_data = [('lizhi', '123456'), ('lizhi1','123456')]
test_data1 = [{'username':'lizhi','password':'123456'},
              {'username':'lizhi1','password':'123456'}]

@pytest.mark.parametrize("username,password",test_data)
def test_login(username,password):
    print(username,password)

@pytest.mark.parametrize("case",test_data1)
def test_login1(case):
    print(case)

if __name__ == '__main__':
    pytest.main(['-s'])
⑦生成報告

需要安裝對應的外掛

⑧整合allure報告
  1. allure是一個專門生成測試報告的框架
  2. 安裝allure服務
    https://github.com/allure-framework/allure2/releases,下載對應的壓縮包
    allure目錄地址需要新增到環境變數中
  3. 與pytest整合
    • 安裝pytest外掛
      pip install allure-pytest
    • 使用
      通過加引數
      pytest --alluredir=reports
      
    • 檢視需要啟動allure服務
       allure serve 報告檔案地址