亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

pytest框架之fixture詳細使用詳解

 更新時間:2021年04月16日 14:12:04   作者:輝輝輝輝a  
這篇文章主要介紹了pytest框架之fixture詳細使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

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

簡介:

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

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

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

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

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

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

用例設計原則

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

以test_開頭的函數(shù)

以Test開頭的類

以test_開頭的方法

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

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

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

使用多個fixture

如果用例需要用到多個fixture的返回數(shù)據(jù),fixture也可以返回一個元祖,list或字典,然后從里面取出對應數(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')


輸出結果:
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

當然也可以分成多個fixture,然后在用例中傳多個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('傳入多個fixture參數(shù)正確')


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 
傳出a
傳出b
.傳入多個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')


輸出結果:
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里面有個scope參數(shù)可以控制fixture的作用范圍:session>module>class>function

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

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

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

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

fixture源碼詳解

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

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

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

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

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

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

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

scope="function"

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

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')


輸出結果:

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 ===========================

放在類中實現(xià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


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'])

輸出結果:

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級別的時候,如果一個class里面有多個用例,都調(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'])

輸出結果:
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時,在當前.py腳本里面所有用例開始前只執(zhí)行一次。

import pytest
##test_fixture.py

@pytest.fixture(scope='module')
def test1():
    b = '男'
    print('傳出了%s, 且在當前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'])


輸出結果:
============================= 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 傳出了男, 且在當前py文件下執(zhí)行一次?。?!
.找到sex
.找到name
                                                       [100%]

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

scope="session"

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

conftest.py文件名稱時固定的,pytest會自動識別該文件。放到項目的根目錄下就可以全局調(diào)用了,如果放到某個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'])

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

執(zhí)行結果為:

================================================= 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í)行')

輸出結果:
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()修飾需要運行的用例

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'])

輸出結果:
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

如果一個方法或者一個class用例想要同時調(diào)用多個fixture,可以使用@pytest.mark.usefixture()進行疊加。注意疊加順序,先執(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'])


輸出結果:
============================= 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就無法獲取到返回值,這個是裝飾器usefixture與用例直接傳fixture參數(shù)的區(qū)別。

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

fixture自動使用autouse=True

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

autouse設置為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'])


輸出結果:
============================= 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的作用范圍

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

項目實例:

目錄結構:

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

# conftest層級展示/conftest.py

import pytest


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





# 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'])



輸出結果:

============================= 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 ----準備登錄----
-----登錄百度頁面-----
.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'])


輸出結果:
============================= 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 ----準備登錄----
打印頁面日志成功
hhh,成功一次打印日志
.打印頁面日志成功
hhh,成功兩次打印日志
.

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

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

相關文章

  • Python利用緩存流實現(xiàn)壓縮PDF文件

    Python利用緩存流實現(xiàn)壓縮PDF文件

    在Python中,有許多庫可以用來壓縮PDF文件,其中最常用的是PyPDF2和PDFMiner,本文將為大家介紹一個新的方法,即使用緩存流壓縮PDF文件,感興趣的可以了解下
    2023-08-08
  • 使用Python處理Excel文件并將數(shù)據(jù)存儲到PostgreSQL的方法

    使用Python處理Excel文件并將數(shù)據(jù)存儲到PostgreSQL的方法

    在日常工作中,我們經(jīng)常會遇到需要處理大量文件并將數(shù)據(jù)存儲至數(shù)據(jù)庫或整合到一個文件的需求,本文將向大家展示如何使用Python處理Excel文件并將數(shù)據(jù)存儲到PostgreSQL數(shù)據(jù)庫中,需要的朋友可以參考下
    2024-01-01
  • Python3 修改默認環(huán)境的方法

    Python3 修改默認環(huán)境的方法

    今天小編就為大家分享一篇Python3 修改默認環(huán)境的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-02-02
  • python中列表元素連接方法join用法實例

    python中列表元素連接方法join用法實例

    這篇文章主要介紹了python中列表元素連接方法join用法,實例分析了Python中join方法的使用技巧,非常具有實用價值,需要的朋友可以參考下
    2015-04-04
  • Python接口測試環(huán)境搭建過程詳解

    Python接口測試環(huán)境搭建過程詳解

    這篇文章主要介紹了Python接口測試環(huán)境搭建過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • 解決Python調(diào)用df.to_csv()出現(xiàn)中文亂碼的問題

    解決Python調(diào)用df.to_csv()出現(xiàn)中文亂碼的問題

    在Python使用df.to_csv()時,若出現(xiàn)中文亂碼,可通過加入?yún)?shù)encoding="utf_8_sig"解決,"utf-8"編碼不包含BOM,直接處理文件時會將BOM誤讀為內(nèi)容;而"utf_8_sig"會識別并處理BOM,避免亂碼,此方法為實踐經(jīng)驗,供參考
    2024-09-09
  • 使用Python解析Chrome瀏覽器書簽的示例

    使用Python解析Chrome瀏覽器書簽的示例

    這篇文章主要介紹了使用Python解析Chrome瀏覽器書簽的示例,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-11-11
  • Django url反向解析的實現(xiàn)

    Django url反向解析的實現(xiàn)

    本文主要介紹了Django url反向解析的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • 快速解決cv2.imread()讀取圖像為BGR的問題

    快速解決cv2.imread()讀取圖像為BGR的問題

    這篇文章主要介紹了快速解決cv2.imread()讀取圖像為BGR的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • python實現(xiàn)解數(shù)獨程序代碼

    python實現(xiàn)解數(shù)獨程序代碼

    最近在帶孩子學習數(shù)獨,職業(yè)使然,就上網(wǎng)搜了下相關程序的解法,這里分享給大家,希望對大家學習python有所幫助
    2017-04-04

最新評論