Python Pytest框架(三)測試韌體 下

2021-10-06 03:11:57 字數 2003 閱讀 7557

一、執行命令pytest -- fixture:可以列出當前所有可用的fixture,包括內建的、外掛程式中的、以及當前專案定義的。

eg:conftest.py和test_1.py在同一目錄下,要使用測試韌體login。

conftest.py

import pytest

@pytest.fixture()

def login():

print('登入系統')

# import pytest

# # @pytest.fixture(name = "lg")

# def login():

# print('登入系統')

test_1.py

def test_1(login):

print('測試test1')

# def test_1(lg):

# print('測試test1')

conftest.py

import pytest

@pytest.fixture(name = "lg")

def login():

print('登入系統')

test_1.py 

import pytest

@pytest.mark.usefixtures("lg")

def test_1():

print('測試test1')

conftest.py

import pytest

@pytest.fixture(name='lg', autouse=true)

def login():

print('登入系統')

test_1.py 

def test_1():

print('測試test1')

1、測試用例可以通過引數使用測試韌體,測試韌體也可以通過引數使用其他測試韌體。按照傳參順序執行,此例:先執行fix1(),然後執行fix2(),最後執行test_1()。

import pytest

@pytest.fixture()

def fix1():

print('fix1')

@pytest.fixture()

def fix2(fix1):

print('fix2')

def test_1(fix2):

print('執行測試1')

2、測試用例可以呼叫多個測試韌體,如果它們的作用域相同,則按照傳參順序執行;如果它們的作用域不同,則按照作用域級別,從高到低執行。此例:先執行fix2(),然後執行fix1(),最後執行test_1()。

import pytest

@pytest.fixture()

def fix1():

print('fix1')

@pytest.fixture(scope='module')

def fix2():

print('fix2')

def test_1(fix1, fix2):

print('執行測試1')

3、如果使用autouse引數,測試用例自動呼叫測試韌體。作用域相同時,按函式名的編碼從小到大執行;作用域不同時,按作用域的級別從高到低執行。此例:先執行fix1(),然後執行fix2(),最後執行test_1()。

import pytest

@pytest.fixture(autouse=true)

def fix2():

print('fixc')

@pytest.fixture(autouse=true)

def fix1():

print('fixb')

def test_1():

print('執行測試1')

python pytest測試框架介紹三

之前介紹了pytest以xunit形式來寫用例,下面來介紹pytest特有的方式來寫用例 如下 這裡使用的了pytest的特有的模式來寫用例,使用的方式是scope方式,scope支援多種,後面會介紹 這裡還使用了pytest的addfinalizer內建功能,具體可參見官網,用處是 在最後乙個測試...

Python pytest測試框架基本用法(一)

一 框架介紹及安裝 pytest是python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高。安裝 pip install pytest 我這裡已經安裝成功了 二 框架使用流程 建立如下的原始碼檔案test one.py de...

Python pytest單元測試框架安裝與執行

摘要1 摘要2 摘要3 摘要4 pytest外掛程式 pytest是乙個非常成熟的全功能的python測試框架,主要特點有以下幾點 與安裝其他的python軟體無異,直接使用pip安裝。pip install u pytest安裝完成後,可以驗證安裝的版本 pytest version1 pytes...