Pytest高級進階之Fixture

From: https://www.jianshu.com/p/54b0f4016300

一. fixture介紹

fixture是pytest的一個閃光點,pytest要精通怎么能不學習fixture呢?跟著我一起深入學習fixture吧。其實unittest和nose都支持fixture,但是pytest做得更炫。
fixture是pytest特有的功能,它用pytest.fixture標識,定義在函數前面。在你編寫測試函數的時候,你可以將此函數名稱做為傳入參數,pytest將會以依賴注入方式,將該函數的返回值作為測試函數的傳入參數。
fixture有明確的名字,在其他函數,模塊,類或整個工程調用它時會被激活。
fixture是基于模塊來執行的,每個fixture的名字就可以觸發一個fixture的函數,它自身也可以調用其他的fixture。
我們可以把fixture看做是資源,在你的測試用例執行之前需要去配置這些資源,執行完后需要去釋放資源。比如module類型的fixture,適合于那些許多測試用例都只需要執行一次的操作。
fixture還提供了參數化功能,根據配置和不同組件來選擇不同的參數。
fixture主要的目的是為了提供一種可靠和可重復性的手段去運行那些最基本的測試內容。比如在測試網站的功能時,每個測試用例都要登錄和退出,利用fixture就可以只做一次,否則每個測試用例都要做這兩步也是冗余。

下面會反復提高Python的Module概念,Python中的一個Module對應的就是一個.py文件。其中定義的所有函數或者是變量都屬于這個Module。這個Module 對于所有函數而言就相當于一個全局的命名空間,而每個函數又都有自己局部的命名空間。

二. Fixture基礎實例入門

把一個函數定義為Fixture很簡單,只能在函數聲明之前加上“@pytest.fixture”。其他函數要來調用這個Fixture,只用把它當做一個輸入的參數即可。
test_fixture_basic.py

import pytest@pytest.fixture()
def before(): print '\nbefore each test' def test_1(before): print 'test_1()' def test_2(before): print 'test_2()' assert 0 

下面是運行結果,test_1和test_2運行之前都調用了before,也就是before執行了兩次。默認情況下,fixture是每個測試用例如果調用了該fixture就會執行一次的。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_basic.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe cachedir: .cache metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}} rootdir: C:\Users\yatyang\PycharmProjects\pytest_example, inifile: plugins: metadata-1.3.0, html-1.14.2 collected 2 items test_fixture_basic.py::test_1 before each test test_1() PASSED test_fixture_basic.py::test_2 before each test test_2() FAILED ================================== FAILURES =================================== ___________________________________ test_2 ____________________________________ before = None def test_2(before): print 'test_2()' > assert 0 E assert 0 test_fixture_basic.py:12: AssertionError ===================== 1 failed, 1 passed in 0.23 seconds ====================== 

如果你的程序出現了下面的錯誤,就是開始忘記添加‘import pytest',所以不要忘記羅。

=================================== ERRORS ====================================
_________________ ERROR collecting test_fixture_decorator.py __________________
test_fixture_decorator.py:2: in <module> @pytest.fixture() E NameError: name 'pytest' is not defined !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.36 seconds =========================== 

三. 調用fixture的三種方式

1. 在測試用例中直接調用它,例如第二部分的基礎實例。

2. 用fixture decorator調用fixture

可以用以下三種不同的方式來寫,我只變化了函數名字和類名字,內容沒有變。第一種是每個函數前聲明,第二種是封裝在類里,類里的每個成員函數聲明,第三種是封裝在類里在前聲明。在可以看到3中不同方式的運行結果都是一樣。
test_fixture_decorator.py

import pytest@pytest.fixture()
def before(): print('\nbefore each test') @pytest.mark.usefixtures("before") def test_1(): print('test_1()') @pytest.mark.usefixtures("before") def test_2(): print('test_2()') class Test1: @pytest.mark.usefixtures("before") def test_3(self): print('test_1()') @pytest.mark.usefixtures("before") def test_4(self): print('test_2()') @pytest.mark.usefixtures("before") class Test2: def test_5(self): print('test_1()') def test_6(self): print('test_2()') 

運行結果如下,和上面的基礎實例的運行效果一樣。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_decorator.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe cachedir: .cache metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}} rootdir: C:\Users\yatyang\PycharmProjects\pytest_example, inifile: plugins: metadata-1.3.0, html-1.14.2 collected 6 items test_fixture_decorator.py::test_1 before each test test_1() PASSED test_fixture_decorator.py::test_2 before each test test_2() PASSED test_fixture_decorator.py::Test1::test_3 before each test test_1() PASSED test_fixture_decorator.py::Test1::test_4 before each test test_2() PASSED test_fixture_decorator.py::Test2::test_5 before each test test_1() PASSED test_fixture_decorator.py::Test2::test_6 before each test test_2() PASSED ========================== 6 passed in 0.10 seconds =========================== 

3. 用autos調用fixture

fixture decorator一個optional的參數是autouse, 默認設置為False。
當默認為False,就可以選擇用上面兩種方式來試用fixture。
當設置為True時,在一個session內的所有的test都會自動調用這個fixture。
權限大,責任也大,所以用該功能時也要謹慎小心。

import time
import pytest@pytest.fixture(scope="module", autouse=True)
def mod_header(request): print('\n-----------------') print('module : %s' % request.module.__name__) print('-----------------') @pytest.fixture(scope="function", autouse=True) def func_header(request): print('\n-----------------') print('function : %s' % request.function.__name__) print('time : %s' % time.asctime()) print('-----------------') def test_one(): print('in test_one()') def test_two(): print('in test_two()') 

從下面的運行結果,可以看到mod_header在該module內運行了一次,而func_header對于每個test都運行了一次,總共兩次。該方式如果用得好,還是可以使代碼更為簡潔。
但是對于不熟悉自己組的測試框架的人來說,在pytest里面去新寫測試用例,需要去了解是否已有一些fixture是module或者class級別的需要注意。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_auto.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe cachedir: .cache metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}} rootdir: C:\Users\yatyang\PycharmProjects\pytest_example, inifile: plugins: metadata-1.3.0, html-1.14.2 collected 2 items test_fixture_auto.py::test_one ----------------- module : test_fixture_auto ----------------- ----------------- function : test_one time : Sat Mar 18 06:56:54 2017 ----------------- in test_one() PASSED test_fixture_auto.py::test_two ----------------- function : test_two time : Sat Mar 18 06:56:54 2017 ----------------- in test_two() PASSED ========================== 2 passed in 0.03 seconds =========================== 

四. fixture scope

function:每個test都運行,默認是function的scope
class:每個class的所有test只運行一次
module:每個module的所有test只運行一次
session:每個session只運行一次

比如你的所有test都需要連接同一個數據庫,那可以設置為module,只需要連接一次數據庫,對于module內的所有test,這樣可以極大的提高運行效率。

五. fixture 返回值

在上面的例子中,fixture返回值都是默認None,我們可以選擇讓fixture返回我們需要的東西。如果你的fixture需要配置一些數據,讀個文件,或者連接一個數據庫,那么你可以讓fixture返回這些數據或資源。

如何帶參數
fixture還可以帶參數,可以把參數賦值給params,默認是None。對于param里面的每個值,fixture都會去調用執行一次,就像執行for循環一樣把params里的值遍歷一次。
test_fixture_param.py

import pytest@pytest.fixture(params=[1, 2, 3])
def test_data(request): return request.param def test_not_2(test_data): print('test_data: %s' % test_data) assert test_data != 2 

可以看到test_not_2里面把用test_data里面定義的3個參數運行里三次。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_param.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe cachedir: .cache metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}} rootdir: C:\Users\yatyang\PycharmProjects\pytest_example, inifile: plugins: metadata-1.3.0, html-1.14.2 collected 3 items test_fixture_param.py::test_not_2[1] test_data: 1 PASSED test_fixture_param.py::test_not_2[2] test_data: 2 FAILED test_fixture_param.py::test_not_2[3] test_data: 3 PASSED ================================== FAILURES =================================== ________________________________ test_not_2[2] ________________________________ test_data = 2 def test_not_2(test_data): print('test_data: %s' % test_data) > assert test_data != 2 E assert 2 != 2 test_fixture_param.py:9: AssertionError ===================== 1 failed, 2 passed in 0.24 seconds ====================== 

轉載于:https://www.cnblogs.com/Raul2018/p/10340452.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395244.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395244.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395244.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql 慢日志報警_一則MySQL慢日志監控誤報的問題分析

之前因為各種原因&#xff0c;有些報警沒有引起重視&#xff0c;最近放假馬上排除了一些潛在的人為原因&#xff0c;發現數據庫的慢日志報警有些奇怪&#xff0c;主要表現是慢日志報警不屬實&#xff0c;收到報警的即時通信提醒后&#xff0c;隔一會去數據庫里面去排查&#xf…

用css實現自定義虛線邊框

開發產品功能的時候ui往往會給出虛線邊框的效果圖&#xff0c;于是乎&#xff0c;我們往往第一時間想到的是用css里的border&#xff0c;可是border里一般就提供兩種效果&#xff0c;dashed或者dotted&#xff0c;ui這時就不滿意了&#xff0c;說虛線太密了。廢話不多說&#x…

無限復活服務器,絕地求生無限復活模式怎么玩 無限復活新手教程

相信不少的絕地求生玩家們最近都聽說了其無限復活模式吧?因此肯定想要知道這種模式究竟該怎么玩&#xff0c;所以下面就來為各位帶來此玩法的攻略相關&#xff0c;希望各位在看了如下的內容之后恩呢狗狗了解到新手教程攻略一覽。“War”模式的設定以及玩法規則如下&#xff1a…

lua math.random()

math.random([n [,m]]) 用法&#xff1a;1.無參調用&#xff0c;產生[0, 1)之間的浮點隨機數。 2.一個參數n&#xff0c;產生[1, n]之間的整數。 3.兩個參數&#xff0c;產生[n, m]之間的整數。 math.randomseed(n) 用法&#xff1a;接收一個整數n作為隨即序列的種子。 例&…

零基礎學習ruby_學習Ruby:從零到英雄

零基礎學習ruby“Ruby is simple in appearance, but is very complex inside, just like our human body.” — Matz, creator of the Ruby programming language“ Ruby的外觀很簡單&#xff0c;但是內部卻非常復雜&#xff0c;就像我們的人體一樣。” — Matz &#xff0c;R…

windows同時啟動多個微信

1、創建mychat.bat文件(文件名任意)&#xff0c;輸入以下代碼&#xff0c;其中"C:\Program Files (x86)\Tencent\WeChat\"為微信的安裝路徑。以下示例為同時啟動兩個微信 start/d "C:\Program Files (x86)\Tencent\WeChat\" Wechat.exe start/d "C:\P…

mysql date time year_YEAR、DATE、TIME、DATETIME和TIMESTAMP詳細介紹[MySQL數據類型]

為了方便在數據庫中存儲日期和時間&#xff0c;MySQL提供了表示日期和時間的數據類型&#xff0c;分別是YEAR、DATE、TIME、DATETIME和TIMESTAMP。下面列舉了這些MSL中日期和時間數據類型所對應的字節數、取值范圍、日期格式以及零值。從上圖中可以看出&#xff0c;每種日期和時…

九度oj 題目1380:lucky number

題目描述&#xff1a;每個人有自己的lucky number&#xff0c;小A也一樣。不過他的lucky number定義不一樣。他認為一個序列中某些數出現的次數為n的話&#xff0c;都是他的lucky number。但是&#xff0c;現在這個序列很大&#xff0c;他無法快速找到所有lucky number。既然這…

安裝Tengine

1.安裝VMware2.安裝CentOS6.53.配置網絡a.修改 /etc/sysconfig/network-scripts/ifcfg-eth0配置文件,添加如下內容DEVICEeth0HWADDR00:0C:29:96:01:6BTYPEEthernetUUID41cbd943-024b-4341-ac7a-e4d2142b4938ONBOOTyesNM_CONTROLLEDyesBOOTPROTOnoneIPADDRxxx.xxx.x.xxx#例如:IP…

node seneca_使用Node.js和Seneca編寫國際象棋微服務,第2部分

node seneca處理新需求而無需重構 (Handling new requirements without refactoring) Part 1 of this series talked about defining and calling microservices using Seneca. A handful of services were created to return all legal moves of a lone chess piece on a ches…

【OCR技術系列之八】端到端不定長文本識別CRNN代碼實現

CRNN是OCR領域非常經典且被廣泛使用的識別算法&#xff0c;其理論基礎可以參考我上一篇文章&#xff0c;本文將著重講解CRNN代碼實現過程以及識別效果。 數據處理 利用圖像處理技術我們手工大批量生成文字圖像&#xff0c;一共360萬張圖像樣本&#xff0c;效果如下&#xff1a;…

mysql 修改字段類型死鎖_mysql數據庫死鎖的產生原因及解決辦法

數據庫和操作系統一樣&#xff0c;是一個多用戶使用的共享資源。當多個用戶并發地存取數據 時&#xff0c;在數據庫中就會產生多個事務同時存取同一數據的情況。若對并發操作不加控制就可能會讀取和存儲不正確的數據&#xff0c;破壞數據庫的一致性。加鎖是實現數據庫并 發控制…

openwrt無盤服務器,搭建基于 OpenWrt/gPXE/iSCSI 的 Windows 無盤工作站

本文要介紹的是如何在 OpenWrt 平臺上面搭建無盤工作站服務器以及 Windows 的 iSCSI 部署。當然&#xff0c;由于 OpenWrt 也可以算得上一種 Linux 發行版了&#xff0c;所以本文所介紹的一些方法&#xff0c;在其它 Linux 發行版上面仍有一定的參考價值。整個過程大概分為以下…

Ralink5350開發環境搭建

一、安裝虛擬機(Oracle VM VirtualBox 或 VMware Workstation) 二、在虛擬機中安裝linux操作系統&#xff08;當前使用的是Ubuntu1204桌面版&#xff09; 三、配置linux相關服務 安裝、配置、啟動ftp服務apt-get install vsftpd 改動 vsftpd 的配置文件 /etc/vsftpd.conf,將以…

figma下載_Figma重新構想的團隊庫

figma下載一個新的&#xff0c;功能更強大的界面&#xff0c;用于在整個組織中共享組件 (A new, more powerful interface for sharing Components across your organization) The Team Library in Figma is a set of shared Components across all files in a Team. Component…

boost python導出c++ map_使用Boost生成的Python模塊:與C++簽名不匹配

我正在使用名為Mitsuba的軟件。它附帶了一個用Boost包裝的Python實現。 Python中的這一行&#xff1a;使用Boost生成的Python模塊&#xff1a;與C簽名不匹配scene SceneHandler.loadScene(fileResolver.resolve("model.xml"), paramMap)產生一個錯誤。根據文檔&…

CSU-1982 小M的移動硬盤

CSU-1982 小M的移動硬盤 Description 最近小M買了一個移動硬盤來儲存自己電腦里不常用的文件。但是他把這些文件一股腦丟進移動硬盤后&#xff0c;覺得這些文件似乎沒有被很好地歸類&#xff0c;這樣以后找起來豈不是會非常麻煩&#xff1f; 小M最終決定要把這些文件好好歸類&a…

杜比服務器系統安裝教程,win10杜比音效如何安裝?win10安裝杜比音效的詳細教程...

杜比音效想必大家都不陌生&#xff0c;聽歌或者看電影開啟杜比音效可以給人一種身臨其境的感覺。不少朋友都升級了win10系統卻不知道如何安裝杜比音效&#xff1f;如何為自己的系統安裝杜比音效呢&#xff1f;感興趣的小伙伴請看下面的操作步驟。win10安裝杜比音效的方法&#…

劍指Offer_52_正則表達式匹配

題目描述 請實現一個函數用來匹配包括.和的正則表達式。模式中的字符.表示任意一個字符&#xff0c;而表示它前面的字符可以出現任意次&#xff08;包含0次&#xff09;。 在本題中&#xff0c;匹配是指字符串的所有字符匹配整個模式。例如&#xff0c;字符串"aaa"與…

分布式系統開發注意點_分布式系統注意事項

分布式系統開發注意點by Shubheksha通過Shubheksha 分布式計算概述&#xff1a;分布式系統如何工作 (Distributed Computing in a nutshell: How distributed systems work) This post distills the material presented in the paper titled “A Note on Distributed Systems”…