濮阳杆衣贸易有限公司

主頁 > 知識庫 > pytest框架之fixture詳細(xì)使用詳解

pytest框架之fixture詳細(xì)使用詳解

熱門標(biāo)簽:蘇州人工外呼系統(tǒng)軟件 看懂地圖標(biāo)注方法 打印谷歌地圖標(biāo)注 淮安呼叫中心外呼系統(tǒng)如何 電話機(jī)器人貸款詐騙 電話外呼系統(tǒng)招商代理 廣東旅游地圖標(biāo)注 京華圖書館地圖標(biāo)注 佛山通用400電話申請

本人之前寫了一套基于unnitest框架的UI自動化框架,但是發(fā)現(xiàn)了pytest框架之后覺得unnitest太low,現(xiàn)在重頭開始學(xué)pytest框架,一邊學(xué)習(xí)一邊記錄,和大家分享,話不多說,那就先從pytest框架的精髓fixture說起吧!

簡介:

  fixture區(qū)別于unnitest的傳統(tǒng)單元測試(setup/teardown)有顯著改進(jìn):

  1.有獨(dú)立的命名,并通過聲明它們從測試函數(shù)、模塊、類或整個(gè)項(xiàng)目中的使用來激活。

  2.按模塊化的方式實(shí)現(xiàn),每個(gè)fixture都可以互相調(diào)用。

  3.fixture的范圍從簡單的單元測試到復(fù)雜的功能測試,可以對fixture配置參數(shù),或者跨函數(shù)function,類class,模塊module或整個(gè)測試session范圍。

(很重要?。。。ê苤匾。。。ê苤匾。。。?/p>

謹(jǐn)記:當(dāng)我們使用pytest框架寫case的時(shí)候,一定要拿它的命令規(guī)范去case,這樣框架才能識別到哪些case需要執(zhí)行,哪些不需要執(zhí)行。

用例設(shè)計(jì)原則

文件名以test_*.py文件和*_test.py

以test_開頭的函數(shù)

以Test開頭的類

以test_開頭的方法

fixture可以當(dāng)做參數(shù)傳入

定義fixture跟定義普通函數(shù)差不多,唯一區(qū)別就是在函數(shù)上加個(gè)裝飾器@pytest.fixture(),fixture命名不要以test開頭,跟用例區(qū)分開。fixture是有返回值得,沒有返回值默認(rèn)為None。用例調(diào)用fixture的返回值,直接就是把fixture的函數(shù)名稱當(dāng)做變量名稱。

ex:

import pytest

@pytest.fixture()
def test1():
    a = 'leo'
    return a


def test2(test1):
    assert test1 == 'leo'


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')

輸出:

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item

test_fixture.py .                                                        [100%]

========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0

使用多個(gè)fixture

如果用例需要用到多個(gè)fixture的返回?cái)?shù)據(jù),fixture也可以返回一個(gè)元祖,list或字典,然后從里面取出對應(yīng)數(shù)據(jù)。

ex:

import pytest

@pytest.fixture()
def test1():
    a = 'leo'
    b = '123456'
    print('傳出a,b')
    return (a, b)


def test2(test1):
    u = test1[0]
    p = test1[1]
    assert u == 'leo'
    assert p == '123456'
    print('元祖形式正確')


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')


輸出結(jié)果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item

test_fixture.py 傳出a,b
.元祖形式正確
                                                        [100%]

========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0

當(dāng)然也可以分成多個(gè)fixture,然后在用例中傳多個(gè)fixture參數(shù)

import pytest


@pytest.fixture()
def test1():
    a = 'leo'
    print('\n傳出a')
    return a


@pytest.fixture()
def test2():
    b = '123456'
    print('傳出b')
    return b


def test3(test1, test2):
    u = test1
    p = test2
    assert u == 'leo'
    assert p == '123456'
    print('傳入多個(gè)fixture參數(shù)正確')


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')



輸出結(jié)果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item

test_fixture.py 
傳出a
傳出b
.傳入多個(gè)fixture參數(shù)正確

fixture互相調(diào)用

import pytest


@pytest.fixture()
def test1():
    a = 'leo'
    print('\n傳出a')
    return a


def test2(test1):
    assert test1 == 'leo'
    print('fixture傳參成功')


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')


輸出結(jié)果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item

test_fixture.py 
傳出a
.fixture傳參成功
                                                        [100%]

========================== 1 passed in 0.03 seconds ===========================
Process finished with exit code 0

介紹完了fixture的使用方式,現(xiàn)在介紹一下fixture的作用范圍(scope)

fixture的作用范圍

fixture里面有個(gè)scope參數(shù)可以控制fixture的作用范圍:session>module>class>function

-function:每一個(gè)函數(shù)或方法都會調(diào)用

-class:每一個(gè)類調(diào)用一次,一個(gè)類中可以有多個(gè)方法

-module:每一個(gè).py文件調(diào)用一次,該文件內(nèi)又有多個(gè)function和class

-session:是多個(gè)文件調(diào)用一次,可以跨.py文件調(diào)用,每個(gè).py文件就是module

fixture源碼詳解

fixture(scope='function',params=None,autouse=False,ids=None,name=None):

scope:有四個(gè)級別參數(shù)"function"(默認(rèn)),"class","module","session"

params:一個(gè)可選的參數(shù)列表,它將導(dǎo)致多個(gè)參數(shù)調(diào)用fixture功能和所有測試使用它。

autouse:如果True,則為所有測試激活fixture func可以看到它。如果為False則顯示需要參考來激活fixture

ids:每個(gè)字符串id的列表,每個(gè)字符串對應(yīng)于params這樣他們就是測試ID的一部分。如果沒有提供ID它們將從params自動生成

name:fixture的名稱。這默認(rèn)為裝飾函數(shù)的名稱。如果fixture在定義它的統(tǒng)一模塊中使用,夾具的功能名稱將被請求夾具的功能arg遮蔽,解決這個(gè)問題的一種方法時(shí)將裝飾函數(shù)命令"fixture_fixturename>"然后使用"@pytest.fixture(name='fixturename>')"。

具體闡述一下scope四個(gè)參數(shù)的范圍

scope="function"

@pytest.fixture()如果不寫參數(shù),參數(shù)就是scope="function",它的作用范圍是每個(gè)測試用例來之前運(yùn)行一次,銷毀代碼在測試用例之后運(yùn)行。

import pytest


@pytest.fixture()
def test1():
    a = 'leo'
    print('\n傳出a')
    return a


@pytest.fixture(scope='function')
def test2():
    b = '男'
    print('\n傳出b')
    return b


def test3(test1):
    name = 'leo'
    print('找到name')
    assert test1 == name


def test4(test2):
    sex = '男'
    print('找到sex')
    assert test2 == sex


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')


輸出結(jié)果:

platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items

test_fixture.py 
傳出a
.找到name

傳出b
.找到sex
                                                       [100%]

========================== 2 passed in 0.04 seconds ===========================

放在類中實(shí)現(xiàn)結(jié)果也是一樣的

import pytest


@pytest.fixture()
def test1():
    a = 'leo'
    print('\n傳出a')
    return a


@pytest.fixture(scope='function')
def test2():
    b = '男'
    print('\n傳出b')
    return b


class TestCase:
    def test3(self, test1):
        name = 'leo'
        print('找到name')
        assert test1 == name

    def test4(self, test2):
        sex = '男'
        print('找到sex')
        assert test2 == sex


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

輸出結(jié)果:

platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items

test_fixture.py 
傳出a
.找到name

傳出b
.找到sex
                                                       [100%]

========================== 2 passed in 0.03 seconds ===========================
Process finished with exit code 0

scope="class"

fixture為class級別的時(shí)候,如果一個(gè)class里面有多個(gè)用例,都調(diào)用了次fixture,那么此fixture只在此class里所有用例開始前執(zhí)行一次。

import pytest


@pytest.fixture(scope='class')
def test1():
    b = '男'
    print('傳出了%s, 且只在class里所有用例開始前執(zhí)行一次?。。? % b)
    return b


class TestCase:
    def test3(self, test1):
        name = '男'
        print('找到name')
        assert test1 == name

    def test4(self, test1):
        sex = '男'
        print('找到sex')
        assert test1 == sex


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

輸出結(jié)果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items

test_fixture.py 傳出了男, 且只在class里所有用例開始前執(zhí)行一次!??!
.找到name
.找到sex
                                                       [100%]

========================== 2 passed in 0.05 seconds ===========================
Process finished with exit code 0

scope="module"

fixture為module時(shí),在當(dāng)前.py腳本里面所有用例開始前只執(zhí)行一次。

import pytest
##test_fixture.py

@pytest.fixture(scope='module')
def test1():
    b = '男'
    print('傳出了%s, 且在當(dāng)前py文件下執(zhí)行一次?。?!' % b)
    return b


def test3(test1):
    name = '男'
    print('找到name')
    assert test1 == name


class TestCase:

    def test4(self, test1):
        sex = '男'
        print('找到sex')
        assert test1 == sex


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


輸出結(jié)果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items

test_fixture.py 傳出了男, 且在當(dāng)前py文件下執(zhí)行一次!?。?
.找到sex
.找到name
                                                       [100%]

========================== 2 passed in 0.03 seconds ===========================
Process finished with exit code 0

scope="session"

fixture為session級別是可以跨.py模塊調(diào)用的,也就是當(dāng)我們有多個(gè).py文件的用例的時(shí)候,如果多個(gè)用例只需調(diào)用一次fixture,那就可以設(shè)置為scope="session",并且寫到conftest.py文件里。

conftest.py文件名稱時(shí)固定的,pytest會自動識別該文件。放到項(xiàng)目的根目錄下就可以全局調(diào)用了,如果放到某個(gè)package下,那就在改package內(nèi)有效。

文件目錄為

import pytest
# conftest.py

@pytest.fixture(scope='session')
def test1():
    sex = '男'
    print('獲取到%s' % sex)
    return sex
import pytest
# test_fixture.py

def test3(test1):
    name = '男'
    print('找到name')
    assert test1 == name


if __name__ == '__main__':
    pytest.main(['-s', 'test_fixture.py'])
import pytest
# test_fixture1.py

class TestCase:

    def test4(self, test1):
        sex = '男'
        print('找到sex')
        assert test1 == sex


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

如果需要同時(shí)執(zhí)行兩個(gè)py文件,可以在cmd中在文件py文件所在目錄下執(zhí)行命令:pytest -s test_fixture.py test_fixture1.py

執(zhí)行結(jié)果為:

================================================= test session starts =================================================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:
collected 2 items

test_fixture.py 獲取到男
找到name
.
test_fixture1.py 找到sex
.

============================================== 2 passed in 0.05 seconds ===============================================

調(diào)用fixture的三種方法

1.函數(shù)或類里面方法直接傳fixture的函數(shù)參數(shù)名稱

import pytest
# test_fixture1.py


@pytest.fixture()
def test1():
    print('\n開始執(zhí)行function')


def test_a(test1):
    print('---用例a執(zhí)行---')


class TestCase:

    def test_b(self, test1):
        print('---用例b執(zhí)行')

輸出結(jié)果:
test_fixture1.py 
開始執(zhí)行function
.---用例a執(zhí)行---

開始執(zhí)行function
.---用例b執(zhí)行
                                                      [100%]

========================== 2 passed in 0.05 seconds ===========================
Process finished with exit code 0

2.使用裝飾器@pytest.mark.usefixtures()修飾需要運(yùn)行的用例

import pytest
# test_fixture1.py


@pytest.fixture()
def test1():
    print('\n開始執(zhí)行function')


@pytest.mark.usefixtures('test1')
def test_a():
    print('---用例a執(zhí)行---')


@pytest.mark.usefixtures('test1')
class TestCase:

    def test_b(self):
        print('---用例b執(zhí)行---')

    def test_c(self):
        print('---用例c執(zhí)行---')


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

輸出結(jié)果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items

test_fixture1.py 
開始執(zhí)行function
.---用例a執(zhí)行---

開始執(zhí)行function
.---用例b執(zhí)行---

開始執(zhí)行function
.---用例c執(zhí)行---
                                                     [100%]

========================== 3 passed in 0.06 seconds ===========================
Process finished with exit code 0

疊加usefixtures

如果一個(gè)方法或者一個(gè)class用例想要同時(shí)調(diào)用多個(gè)fixture,可以使用@pytest.mark.usefixture()進(jìn)行疊加。注意疊加順序,先執(zhí)行的放底層,后執(zhí)行的放上層。

import pytest
# test_fixture1.py


@pytest.fixture()
def test1():
    print('\n開始執(zhí)行function1')


@pytest.fixture()
def test2():
    print('\n開始執(zhí)行function2')


@pytest.mark.usefixtures('test1')
@pytest.mark.usefixtures('test2')
def test_a():
    print('---用例a執(zhí)行---')


@pytest.mark.usefixtures('test2')
@pytest.mark.usefixtures('test1')
class TestCase:

    def test_b(self):
        print('---用例b執(zhí)行---')

    def test_c(self):
        print('---用例c執(zhí)行---')


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


輸出結(jié)果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items

test_fixture1.py 
開始執(zhí)行function2

開始執(zhí)行function1
.---用例a執(zhí)行---

開始執(zhí)行function1

開始執(zhí)行function2
.---用例b執(zhí)行---

開始執(zhí)行function1

開始執(zhí)行function2
.---用例c執(zhí)行---
                                                     [100%]

========================== 3 passed in 0.03 seconds ===========================
Process finished with exit code 0

usefixtures與傳fixture區(qū)別

如果fixture有返回值,那么usefixture就無法獲取到返回值,這個(gè)是裝飾器usefixture與用例直接傳fixture參數(shù)的區(qū)別。

當(dāng)fixture需要用到return出來的參數(shù)時(shí),只能講參數(shù)名稱直接當(dāng)參數(shù)傳入,不需要用到return出來的參數(shù)時(shí),兩種方式都可以。

fixture自動使用autouse=True

當(dāng)用例很多的時(shí)候,每次都傳這個(gè)參數(shù),會很麻煩。fixture里面有個(gè)參數(shù)autouse,默認(rèn)是False沒開啟的,可以設(shè)置為True開啟自動使用fixture功能,這樣用例就不用每次都去傳參了

autouse設(shè)置為True,自動調(diào)用fixture功能

import pytest
# test_fixture1.py


@pytest.fixture(scope='module', autouse=True)
def test1():
    print('\n開始執(zhí)行module')


@pytest.fixture(scope='class', autouse=True)
def test2():
    print('\n開始執(zhí)行class')


@pytest.fixture(scope='function', autouse=True)
def test3():
    print('\n開始執(zhí)行function')


def test_a():
    print('---用例a執(zhí)行---')


def test_d():
    print('---用例d執(zhí)行---')


class TestCase:

    def test_b(self):
        print('---用例b執(zhí)行---')

    def test_c(self):
        print('---用例c執(zhí)行---')


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


輸出結(jié)果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 4 items

test_fixture1.py 
開始執(zhí)行module

開始執(zhí)行class

開始執(zhí)行function
.---用例a執(zhí)行---

開始執(zhí)行class

開始執(zhí)行function
.---用例d執(zhí)行---

開始執(zhí)行class

開始執(zhí)行function
.---用例b執(zhí)行---

開始執(zhí)行function
.---用例c執(zhí)行---
                                                    [100%]

conftest.py的作用范圍

一個(gè)工程下可以建多個(gè)conftest.py的文件,一般在工程根目錄下設(shè)置的conftest文件起到全局作用。在不同子目錄下也可以放conftest.py的文件,作用范圍只能在改層級以及以下目錄生效。

項(xiàng)目實(shí)例:

目錄結(jié)構(gòu):

1.conftest在不同的層級間的作用域不一樣

# conftest層級展示/conftest.py

import pytest


@pytest.fixture(scope='session', autouse=True)
def login():
    print('----準(zhǔn)備登錄----')





# conftest層級展示/sougou_login/conftest
import pytest


@pytest.fixture(scope='session', autouse=True)
def bai_du():
    print('-----登錄百度頁面-----')







# conftest層級展示/sougou_login/login_website
import pytest


class TestCase:
    def test_login(self):
        print('hhh,成功登錄百度')


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



輸出結(jié)果:

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest層級演示\sougou_login, inifile:collected 1 item

login_website.py ----準(zhǔn)備登錄----
-----登錄百度頁面-----
.hhh,成功登錄百度
                                                       [100%]

========================== 1 passed in 0.03 seconds ===========================
Process finished with exit code 0

2.conftest是不能跨模塊調(diào)用的(這里沒有使用模塊調(diào)用)

# conftest層級演示/log/contfest.py
import pytest


@pytest.fixture(scope='function', autouse=True)
def log_web():
    print('打印頁面日志成功')




# conftest層級演示/log/log_website.py
import pytest


def test_web():
    print('hhh,成功一次打印日志')


def test_web1():
    print('hhh,成功兩次打印日志')


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


輸出結(jié)果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest層級演示\log, inifile:
collected 2 items

log_website.py ----準(zhǔn)備登錄----
打印頁面日志成功
hhh,成功一次打印日志
.打印頁面日志成功
hhh,成功兩次打印日志
.

========================== 2 passed in 0.02 seconds ===========================

到此這篇關(guān)于pytest框架之fixture詳細(xì)使用詳解的文章就介紹到這了,更多相關(guān)pytest fixture內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python pytest進(jìn)階之fixture詳解
  • pytest進(jìn)階教程之fixture函數(shù)詳解
  • Python 測試框架unittest和pytest的優(yōu)劣
  • Python自動化測試pytest中fixtureAPI簡單說明

標(biāo)簽:股票 湖州 中山 衡水 江蘇 呼和浩特 駐馬店 畢節(jié)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《pytest框架之fixture詳細(xì)使用詳解》,本文關(guān)鍵詞  pytest,框架,之,fixture,詳細(xì),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《pytest框架之fixture詳細(xì)使用詳解》相關(guān)的同類信息!
  • 本頁收集關(guān)于pytest框架之fixture詳細(xì)使用詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    仪征市| 丽水市| 英山县| 兴文县| 万盛区| 临桂县| 布拖县| 蕉岭县| 拜泉县| 象州县| 达拉特旗| 文化| 珲春市| 且末县| 黄梅县| 思南县| 大同县| 定安县| 华亭县| 榆中县| 清河县| 沁水县| 徐水县| 九龙城区| 密山市| 武乡县| 交城县| 镇巴县| 五家渠市| 邯郸市| 桂林市| 五常市| 申扎县| 海口市| 松江区| 纳雍县| 兴化市| 图木舒克市| 金川县| 天祝| 祁阳县|