Pytest: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分發)、
pytest--ordering(控制測試運行的順序)
5、測試用例的skip和xfail處理;
6、可以很好的和CI工具結合,例如jenkins

編寫規則:

  • 測試文件以test_開頭(以_test結尾也可以)
  • 測試類以Test開頭,並且不能帶有 init 方法
  • 測試函數以test_開頭
  • 斷言使用基本的assert即可

快速示例

 test_pyexample.py

import pytest

class TestClass:
        def test_one(self):
            x = "this"
            assert 'h' in x

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

        def test_three(self):
            a = "hello"
            b = "hello world"
            assert a in b

通過命令行運行:

1、cd 到代碼所在的目錄,執行命令:py.test test_pyexample.py

2、安裝pytest-sugar插件可以看到進度條

Pycharm配置運行:

1.file->Setting->Tools->Python Integrated Tools->項目名稱->Default test runner->選擇py.test

import pytest

class TestClass:
        def test_one(self):
            x = "this"
            assert 'h' in x

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

        def test_three(self):
            a = "hello"
            b = "hello world"
            assert a in b

if __name__ == "__main__":
    pytest.main('-q test_class.py')
Console常用參數介紹:
-v 用於顯示每個測試函數的執行結果
-q 只顯示整體測試結果
-s 用於顯示測試函數中print()函數輸出
-x, --exitfirst, exit instantly on first error or failed test
-m 只運行帶有裝飾器配置的測試用例
-h 幫助
py.test # run all tests below current dir
py.test test_mod.py # run tests in module file test_mod.py
py.test somepath # run all tests below somepath like ./tests/
py.test -k stringexpr # only run tests with names that match the
# the "string expression", e.g. "MyClass and not method"
# will select TestMyClass.test_something
# but not TestMyClass.test_method_simple
py.test test_mod.py::test_func # only run tests that match the "node ID",
# e.g "test_mod.py::test_func" will be selected
# only run test_func in test_mod.py

pytest參數化

使用裝飾器:@pytest.mark.parametrize()

單個參數:

import pytest
import random
 
@pytest.mark.parametrize('x',[(1),(2),(6)])
 
def test_add(x):
    print(x)
    assert  x==random.randrange(1,7)

多個參數:

import pytest
 
@pytest.mark.parametrize('x,y',[
    (1+2,3),
    (2-0,1),
    (6*2,12),
    (10*2,3),
    ("test","test"),
])
 
def test_add(x,y):   #必須與上面保持一致,只能用x,y不能用其他字母
 
    assert  x==y

控制測試運行順序

安裝pytest-ordering

pip install pytest-ordering

借助於裝飾器@pytest.mark.run(order=1)控制測試運行的順序

import pytest
import time
 
value=0
@pytest.mark.run(order=2) #后執行order=2
def test_add2():
    print("I am 2")
    time.sleep(2)
    assert value==10
 
@pytest.mark.run(order=1)   #先執行order=1
def test_add():
    print("I am add")
    global value
    value=10
    assert value==10

運行后生成測試報告(htmlReport)

安裝pytest-html:

pip install -U pytest-html

如何使用:

py.test test_pyexample.py --html=report.html

更詳細的測試報告

安裝 pytest-cov:

pip install pytest-cov 

如何使用

py.test --cov-report=html --cov=./ test_code_target_dir
Console參數介紹
--cov=[path], measure coverage for filesystem path (multi-allowed), 指定被測試對象,用於計算測試覆蓋率
--cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 測試報告的類型
--cov-config=path, config file for coverage, default: .coveragerc, coverage配置文件
--no-cov-on-fail, do not report coverage if test run fails, default: False,如果測試失敗,不生成測試報告
--cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果測試覆蓋率低於MIN,則認為失敗

多進程運行

安裝pytest-xdist:

pip install -U pytest-xdist
 

如何使用:

py.test test_pyexample.py -n NUM
 

其中NUM填寫並發的進程數。

重新運行失敗的用例

安裝pytest- rerunfailures:

import random
 
def add(x,y):
    return x+y
 
def test_add():
    random_value=random.randint(2,7)
    print('random_value:'+str(random_value))
    assert add(1,3)==random_value

如何使用:

命令:pytest --reruns 重試次數
  比如:pytest --reruns 3  表示:運行失敗的用例可以重新運行3次
命令:pytest --reruns 重試次數 --reruns-delay 次數之間的延時設置(單位:秒)     
  比如:pytest --reruns 3 --reruns-delay 5  表示:(譯:瑞軟四、地類)運行失敗的用例可以重新運行3次,第一次和第二次的間隔時間為5秒鍾

另外也可以通過裝飾器的方式配置:

@pytest.mark.flaky(reruns=3, reruns_delay=5)

 


免責聲明!

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



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