[接口測(cè)試_B] 06 Pytest的setup和teardown

pytest實(shí)際上是python自帶測(cè)試框架unittest的擴(kuò)展挽荠,那么pytest是如何實(shí)現(xiàn)unittest中的setup和teardown的呢?

pytest初始化的類(lèi)別和作用域

  • 模塊級(jí)別(Module level setup/teardown):作用于一個(gè)模塊內(nèi)的所有class和def类缤,對(duì)于所有class和def,setup和teardown只執(zhí)行一次
def setup_module(module):
""" setup any state specific to the execution of the given module."""
def teardown_module(module):
""" teardown any state that was previously setup with a setup_module
method.
"""
  • 類(lèi)級(jí)別(Class level setup/teardown):作用于一個(gè)class內(nèi)中的所有test,所有用例只執(zhí)行一次setup邻吭,當(dāng)所有用例執(zhí)行完成后餐弱,才會(huì)執(zhí)行teardown
@classmethod
def setup_class(cls):
""" setup any state specific to the execution of the given class (which
usually contains tests).
"""
@classmethod
def teardown_class(cls):
 """ teardown any state that was previously setup with a call to
setup_class.
"""
  • 方法和函數(shù)級(jí)別(Method and function level setup/teardown):作用于單個(gè)測(cè)試用例,若用例沒(méi)有執(zhí)行(如被skip了)或失敗了囱晴,則不會(huì)執(zhí)行teardown
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
class. setup_method is invoked for every test method of a class.
"""
def teardown_method(self, method):
""" teardown any state that was previously setup with a setup_method
call.
"""

若用例直接寫(xiě)在模塊中膏蚓,而不是在類(lèi)中,則用:

def setup_function(function):
""" setup any state tied to the execution of the given function.
Invoked for every test function in the module.
"""
def teardown_function(function):
""" teardown any state that was previously setup with a setup_function
call.
"""
  • pytest.fixture()裝飾函數(shù)畸写,結(jié)合yield實(shí)現(xiàn)初始化和teardown
    舉個(gè)例子(pytest)文檔中的:
import smtplib
import pytest
@pytest.fixture(scope="module")
def smtp():
    smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
    yield smtp # provide the fixture value
    print("teardown smtp")
    smtp.close()

運(yùn)行結(jié)果:

$ pytest -s -q --tb=no
FFteardown smtp
2 failed in 0.12 seconds

pytest用例初始化操作的示例

為了體現(xiàn)初始化和環(huán)境恢復(fù)驮瞧,本節(jié)演示采用郵件發(fā)送的腳本,可查看郵件發(fā)送的腳本:python發(fā)送郵件腳本或者參考文章:SMTP發(fā)送郵件枯芬。

1论笔、setup_method(self, method)

  • 在test_method.py中構(gòu)建了3個(gè)測(cè)試用例,每個(gè)用例在執(zhí)行前后都會(huì)執(zhí)行setup_method/teardown_method連接smtp和斷開(kāi)smtp千所。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

import pytest

class TestSmtp():
    # 發(fā)件人和收件人,換成你自己的發(fā)件人狂魔、收件人qq號(hào)
    sender = "sender@qq.com"
    receivers = "rece@qq.com"

    # 郵箱服務(wù)器
    smtpserver = "smtp.qq.com"
    smtpport = 465

    # 連接郵箱服務(wù)器,qq郵箱和密碼,換成自己的
    username = "sendr@qq.com"
    password = "qq mail's password"
    smtp = smtplib.SMTP_SSL()

    def setup_method(self, method):
        self.smtp.connect(self.smtpserver, self.smtpport)
        self.smtp.login(self.username, self.password)
        print("成功登錄")

    def teardown_method(self, method):
        self.smtp.quit()
        print("斷開(kāi)連接")

    def test_send_text(self):
        # 郵件發(fā)送淫痰、接收人員最楷,郵件標(biāo)題、正文
        msg = MIMEText("微信公眾號(hào)號(hào):開(kāi)源優(yōu)測(cè)", "plain", "utf-8")
        msg["From"] = self.sender
        msg["To"] = self.receivers
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele_text", "utf-8")

        # 發(fā)送郵件
        self.smtp.sendmail(self.sender, self.receivers, msg.as_string())

    def test_send_html(self):
        msg = MIMEText("<p>微信公眾號(hào)號(hào):開(kāi)源優(yōu)測(cè)</p><a , 
        "html", 
        "utf-8")
        msg["From"] = self.sender
        msg["To"] = self.receivers
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele_html", "utf-8")

        # 發(fā)送郵件
        self.smtp.sendmail(self.sender, self.receivers, msg.as_string())

    def test_send_attchment(self):
        # 郵件格式說(shuō)明、發(fā)送管嬉、接收人員信息、郵件標(biāo)題
        msg = MIMEMultipart()
        msg["From"] = self.sender
        msg["To"] = self.receivers
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele", "utf-8")

        # 構(gòu)建帶附件的郵件正文
        msg.attach(MIMEText("微信公眾號(hào):開(kāi)源優(yōu)測(cè)", "plain", "utf-8")) 
    
        # 構(gòu)造附件,多個(gè)附件同理
        attach1 = MIMEText(open("judge_leap.json", 'rb').read(), "base64", "utf-8")
        attach1["Content-Type"] = "application/octet-stream"

        # 這里filename隨意寫(xiě)朗鸠,將會(huì)在郵件中顯示
        attach1["Content-Disposition"] = "attrachment;filename=code.py"
    
        # 關(guān)聯(lián)附件到正文
        msg.attach(attach1)
        # 發(fā)送郵件
        self.smtp.sendmail(self.sender, self.receivers, msg.as_string())


  • 查看結(jié)果蚯撩,采用pytest -s -q 運(yùn)行,-s 可以查看打印信息烛占,-q減少輸出信息:


    test_method結(jié)果.png

2胎挎、setup_class(cls)

  • 作用于class的setup_class/teardown_class,類(lèi)中所有的用例只會(huì)執(zhí)行一次忆家,如圖所示犹菇;
  • ps:用例與test_method.py的一致,參考上一串代碼芽卿。
test_class.png

3揭芍、setup_module(module)

  • setup_module/teardown_module在一個(gè)模塊內(nèi),只會(huì)執(zhí)行一次卸例,作用于模塊內(nèi)的所有用例
  • 示例中構(gòu)建了2個(gè)class和1個(gè)def称杨,共4個(gè)用例,可以看到筷转,4個(gè)用例只執(zhí)行了一次module
test_module結(jié)果.png
test_module.py
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

import pytest

info = {"sender": "your@qq.com", 
        "receivers": "yourother@qq.com",
        "smtpserver": "smtp.qq.com",
        "smtpport": 465,
        "username":"your@qq.com",
        "password": "yourpassword",
        "smtp": smtplib.SMTP_SSL()}


def setup_module(module):
    info["smtp"].connect(info["smtpserver"], info["smtpport"])
    info["smtp"].login(info["username"], info["password"])
    print("成功登錄")

def teardown_module(module):
    info["smtp"].quit()
    print("斷開(kāi)連接")

class TestSendText():
     def test_send_text(self):
        # 郵件發(fā)送姑原、接收人員,郵件標(biāo)題呜舒、正文
        msg = MIMEText("微信公眾號(hào)號(hào):開(kāi)源優(yōu)測(cè)", "plain", "utf-8")
        msg["From"] =info["sender"]
        msg["To"] = info["receivers"]
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele_text", "utf-8")

        # 發(fā)送郵件
        info["smtp"].sendmail(info["sender"], info["receivers"], msg.as_string())
    
     def test_send_html(self):
        msg = MIMEText("<p>微信公眾號(hào)號(hào):開(kāi)源優(yōu)測(cè)</p><a , 
        "html", 
        "utf-8")
        msg["From"] = info["sender"]
        msg["To"] = info["receivers"]
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele_html", "utf-8")

        # 發(fā)送郵件
        info["smtp"].sendmail(info["sender"], info["receivers"], msg.as_string())

class TestSendAttach():
    def test_send_attchment(self):
        # 郵件格式說(shuō)明锭汛、發(fā)送、接收人員信息、郵件標(biāo)題
        msg = MIMEMultipart()
        msg["From"] = info["sender"]
        msg["To"] = info["receivers"]
        msg["Subject"] = Header("開(kāi)源優(yōu)測(cè)_DeepTest_from_chenlele", "utf-8")

        # 構(gòu)建帶附件的郵件正文
        msg.attach(MIMEText("微信公眾號(hào):開(kāi)源優(yōu)測(cè)", "plain", "utf-8")) 
    
        # 構(gòu)造附件,多個(gè)附件同理
        attach1 = MIMEText(open("judge_leap.json", 'rb').read(), "base64", "utf-8")
        attach1["Content-Type"] = "application/octet-stream"

        # 這里filename隨意寫(xiě)日矫,將會(huì)在郵件中顯示
        attach1["Content-Disposition"] = "attrachment;filename=code.py"
    
        # 關(guān)聯(lián)附件到正文
        msg.attach(attach1)

        # 發(fā)送郵件
        info["smtp"].sendmail(info["sender"], info["receivers"], msg.as_string())

def test_send_text_out():
    # 郵件發(fā)送奥此、接收人員,郵件標(biāo)題眨八、正文
    msg = MIMEText("微信公眾號(hào)號(hào):開(kāi)源優(yōu)測(cè)", "plain", "utf-8")
    msg["From"] =info["sender"]
    msg["To"] = info["receivers"]
    msg["Subject"] = Header("class外的用例執(zhí)行", "utf-8")

    # 發(fā)送郵件
    info["smtp"].sendmail(info["sender"], info["receivers"], msg.as_string())

4、pytest.fixture()

  • pytest.fixture采用yield實(shí)現(xiàn)setup和teardown操作左电,yield提供的參數(shù)為函數(shù)名稱(chēng)
  • 與setup_module類(lèi)似廉侧,pytest.fixture可作用于一個(gè)模塊內(nèi)的所有def和class。區(qū)別在于篓足,必須將pytest.fixture()裝飾的函數(shù)作為參數(shù)傳遞給用例段誊。
  • pytest.fixture()裝飾的函數(shù)必須作為參數(shù)傳遞給用例嗎?
    1)栈拖、將class中的smtp_ini都刪除连舍,class中的用例執(zhí)行失敗,def用例執(zhí)行成功涩哟;
    2)索赏、將class中test_send_text的smtp_ini保留盼玄,其余2個(gè)刪除,class中的用例都執(zhí)行成功潜腻?這是為什么呢埃儿?只有1個(gè)用力傳入了參數(shù),但所有用例都執(zhí)行成功了融涣。
    3)童番、將class和def中的smtp_ini都刪除,用例全部執(zhí)行失敗威鹿。
  • ps:用例內(nèi)容與test_module.py的一致剃斧,就不粘代碼了。
image.png

總結(jié)

4種方式的作用域:

  • setup_method:僅作用于class用例集中的用例忽你,置于class內(nèi),每個(gè)用例都會(huì)調(diào)用一次
  • setup_function:作用于獨(dú)立的def用例幼东,不可作用于class內(nèi)的用例
  • setup_class:作用于class用例集中的用例,置于class內(nèi)科雳,只在class用例執(zhí)行的開(kāi)始執(zhí)行setup_class,結(jié)束時(shí)執(zhí)行teardown_class
  • setup_module:作用于模塊內(nèi)的所有用例筋粗,置于class外,只在所以用例的開(kāi)始執(zhí)行setup_module,結(jié)束時(shí)執(zhí)行teardown_module
  • pytest.fixture():作用于模塊內(nèi)的所有用例炸渡,但需要傳遞裝飾函數(shù)為參數(shù)娜亿,可置于class內(nèi)或class外
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市蚌堵,隨后出現(xiàn)的幾起案子买决,更是在濱河造成了極大的恐慌,老刑警劉巖吼畏,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件督赤,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡泻蚊,警方通過(guò)查閱死者的電腦和手機(jī)躲舌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)性雄,“玉大人没卸,你說(shuō)我怎么就攤上這事∶胄” “怎么了约计?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)迁筛。 經(jīng)常有香客問(wèn)我煤蚌,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任尉桩,我火速辦了婚禮筒占,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蜘犁。我一直安慰自己翰苫,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布沽瘦。 她就那樣靜靜地躺著,像睡著了一般农尖。 火紅的嫁衣襯著肌膚如雪析恋。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天盛卡,我揣著相機(jī)與錄音助隧,去河邊找鬼。 笑死滑沧,一個(gè)胖子當(dāng)著我的面吹牛并村,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播滓技,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼哩牍,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了令漂?” 一聲冷哼從身側(cè)響起膝昆,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叠必,沒(méi)想到半個(gè)月后荚孵,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡纬朝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年收叶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片共苛。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡判没,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出隅茎,到底是詐尸還是另有隱情哆致,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布患膛,位于F島的核電站摊阀,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜胞此,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一臣咖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧漱牵,春花似錦夺蛇、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至闻镶,卻和暖如春甚脉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背铆农。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工牺氨, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人墩剖。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓猴凹,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親岭皂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子郊霎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容