pytest測(cè)試入門--簡(jiǎn)單使用


title: pytest測(cè)試入門--簡(jiǎn)單使用
date: 2019-06-14 15:57:08
tags:

  • 測(cè)試
  • pytest
  • python

categories:

  • 測(cè)試
  • pytest

pytest測(cè)試入門--簡(jiǎn)單使用

安裝

pip install pytest

初步使用

mkdir pytest_demo
cd pytest_demo
vim test_1.py
cat test_1.py

測(cè)試使用到的代碼如下:

import pytest

def test_1():
    assert 1 == 1

@pytest.mark.hello
def test_hello():
    strinf = "hello world"
    assert strinf == "hello world"

@pytest.mark.hello
def test_exception():
    assert 1 != 2

def test_error():
    assert 1 == 2

執(zhí)行命令

pytest

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

![collect_onnly.png](https://upload-images.jianshu.io/upload_images/10206502-ef88d62d46c8a0e9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

為什么什么參數(shù)都不加,但是確實(shí)將代碼執(zhí)行成功了?

答: 這里就需要引入pytest搜索路徑了,標(biāo)準(zhǔn)搜索規(guī)則如下:

  • 從一個(gè)或者多個(gè)目錄開(kāi)始查找,可以在命令行指定文件名或目錄名,如果沒(méi)有指定則在當(dāng)前目錄下查找;
  • 在該目錄和所有子目錄下遞歸查找測(cè)試模塊;
  • 測(cè)試模塊指:文件名為test_*.py 或 *_test.py;
  • 在測(cè)試模塊中查找以test_*的函數(shù)名;
  • 查找名字以Test開(kāi)頭的類,首先篩選掉包含_init_函數(shù)的類,再查找勒種以test_*開(kāi)頭的類方法;

以上。

當(dāng)然可以在pytest.ini中設(shè)置。(后續(xù))

pytest常用命令

# 獲取命令行幫助
pytest --help

--collect-only選項(xiàng)

? 只會(huì)展示哪些測(cè)試用例會(huì)被運(yùn)行;


collect_onnly.png

[圖片上傳中...(k.png-dc8b34-1565871214380-0)]

-k 選項(xiàng)

? -k 選項(xiàng)可以使用表達(dá)式來(lái)獲取希望執(zhí)行的用例。

k.png

-m 選項(xiàng)

? 在pytest中,我們可以使用marker來(lái)對(duì)測(cè)試進(jìn)行分組,-m選項(xiàng)則是快速選中分組并運(yùn)行。

choice_m.png

? 下面警告是需要在pytest.ini中注冊(cè)marker。

-v 選項(xiàng)

輸出結(jié)果會(huì)更加詳細(xì),如:


choice_v.png

-s 與 --capture=<method>

? -s 等價(jià)于 --capture=no, 允許終端在測(cè)試運(yùn)行時(shí)輸出結(jié)果;

? 即,程序中的print()語(yǔ)句,可以使用-s選項(xiàng)來(lái)捕獲輸出;

method:

? no: 如上;

? fd: fd為文件描述符,如1,2,則會(huì)被輸出至臨時(shí)文件;

? sys: 將stdout/stderr輸出至內(nèi)存。

--tb=<style> 選項(xiàng)

? 決定捕捉到失敗時(shí)輸出信息的顯示方式:

style:

? short: 僅輸出一行以及系統(tǒng)判定內(nèi)容;

? line: 只使用一行輸出所有錯(cuò)誤信息;

? no: 直接屏蔽全部回溯信息;

short

tb_short.png

line

tb_line.png

no

tb_no.png

--duration=<N> 選項(xiàng)

? 加快測(cè)試節(jié)奏,統(tǒng)計(jì)測(cè)試過(guò)程中那幾個(gè)階段是最慢的,包括每個(gè)測(cè)試的call, setup, teardown過(guò)程;

建議使用:

pytest --duration=0 -vv

-vv,能夠顯示詳細(xì)信息。 0則是將所有階段耗時(shí)從長(zhǎng)到短排序;


duration.png

以上。

接下來(lái)則介紹pytest中setup,teardown,以及fixture的使用;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容