pytest學習筆記(一)


這兩天在學習pytest,之前有小用到pytest,覺得這個測試框架很靈巧,用在實現接口自動化(pytest+requests)非常的輕便,然后很有興致的決定學習下,然后又發現了pytest-selenium這么個神奇的東東,加上pytest-rerunfailures失敗case自動執行,pytest-html完美測試報告生成,完全就解決了我的selenium測試中的難點,仔細研讀了下pytest的英文文檔,發現這個框架和豐富的plugins真的很好用,所以決心仔細研究下pytest,下面就開始pytest的學習吧。

(一)介紹

  pytest是一個非常成熟的全功能的Python測試框架,主要特點有以下幾點:1、簡單靈活,容易上手;2、支持參數化;3、能夠支持簡單的單元測試和復雜的功能測試,還可以用來做selenium/appnium等自動化測試、接口自動化測試(pytest+requests);4、pytest具有很多第三方插件,並且可以自定義擴展,比較好用的如pytest-selenium(集成selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重復執行)、pytest-xdist(多CPU分發)等;5、測試用例的skip和xfail處理;6、可以很好的和jenkins集成;(二)安裝

  pip install -U pytest 

  pip install -U pytest-html

  pip install -U pytest-rerunfailures

此外還有很多很好的第三方插件,請到http://plugincompat.herokuapp.com/ 和 https://pypi.python.org/pypi?%3Aaction=search&term=pytest-&submit=search 查找

(三)例子

這里列幾個pytest-document中的例子

1、默認執行當前目錄下的所有以test_為前綴(test_*.py)或以_test為后綴(*_test.py)的文件中以test_為前綴的函數

import pytest

# content of test_sample.py
def func(x):
    return x + 1
def test_answer():
    assert func(3) == 5

運行 py.test  或 指定特定文件 py.test -q test_sample.py

2、使用類來組成多個用例的

import pytest

# content of test_class.py
class TestClass:
    def test_one(self):

        x = "this"
    assert 'h' in x
    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

3、在python中調用pytest: python test_class.py

import pytest

# content of test_class.py
class TestClass:
    def test_one(self):
        print 'one'
        x = "this"
        assert 'h' in x
    def test_two(self):
        print 'two'
        x = "hello"
        assert hasattr(x, 'check')
if __name__ == '__main__':
    pytest.main("-q --html=a.html")

4、來個支持參數化的例子,參數化使用pytest.mark.parametrize的參數,第一個為變量的元組,第二個是變量賦值的元組列表,具體下面的章節會仔細介紹

# content of test_time.py
import pytest
from datetime import datetime, timedelta

testdata = [
(datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),
(datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
]

@pytest.mark.parametrize("a,b,expected", testdata)
def test_timedistance_v0(a, b, expected):
    diff = a - b
    assert diff == expected
    
@pytest.mark.parametrize("a,b,expected", testdata, ids=["forward", "backward"])
def test_timedistance_v1(a, b, expected):

    diff = a - b
    assert diff == expected
    
def idfn(val):
    if isinstance(val, (datetime,)):
    # note this wouldn't show any hours/minutes/seconds
        return val.strftime('%Y%m%d')
@pytest.mark.parametrize("a,b,expected", testdata, ids=idfn)
def test_timedistance_v2(a, b, expected):
    diff = a - b
    assert diff == expected

 

  以上對pytest做了入門的介紹,下一節再對pytest中的重點內容做介紹

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM