前言:最近熬夜太多,老是失眠,那就努力更新博客,讓大家多多學習,自己也梳理知識點
1、pytest的安裝(pytest不允許測試類出現初始化方法,不然整個類就不會被當成測試類)
pip install pytest
2、查看pytest版本號
pytest -V
3、pytestkuk框架的簡介
4、pip install pytest-sugar(對運行過程進行界面美化)
pip install pytest-rerunfailures(重新運行出錯的測試用例)
pip install pytest-xdist(多任務同時併發的執行測試用例)
pip install pytest-assume(添加斷言,同一條測試用例每一條的斷言都會反饋出來)
pip install pytest-html(生成美觀的HTML測試報告)
5、測試用例的識別和運行
6、命令欄詳細的使用介紹
pytest 文件名(運行該文件下以test命名的所有測試用例)
pytest -v -s 文件名(會輸出詳細信息)
pytest --maxfail=2文件名(當運行錯誤的用例達到設置的次數就停止,2可以改爲其他數字)
7、pytest執行-失敗重新運行
pytest -v -s --reruns 3 --reruns-delay 2 文件名(失敗用例重新運行3次,間隔2秒)
8、pytest執行-多條斷言有失敗也都運行
pytest data1.py::TestDemo::test_four(運行效果如下圖)
9、使用pycharm運行pytest
10、pytest框架結構
代碼例子:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @File : data2.py
# @Time : 2020/3/28 15:49
# @Author : 李文良
import pytest
def setup_module():
print("這是一個setup_module方法")
def teardown_module():
print("這是一個teardown_module方法")
def setup_function():
print("setup_function")
def teardown_function():
print("teardown_function")
def test_login():
print("這是一個外部的方法")
class TestDemo():
def setup_class(self):
print("setup_class")
def setup_method(self):
print("setup_method")
def setup(self):
print("setup")
def teardown_class(self):
print("teardown_class")
def teardown_method(self):
print("teardown_method")
def teardown(self):
print("teardown")
def test_one(self):
print("請開始執行 test_one 方法")
x = "this"
assert "t" in x
# pytest.assume("t" in x)
# pytest.assume(1 == 2)
def test_two(self):
print("請開始執行 test_two 方法")
x = "this"
assert "h" in x
def test_three(self):
print("請開始執行 test_three 方法")
x = "this"
assert "i" in x
def test_four(self):
print("請開始執行 test_four 方法")
x = "this"
assert "i" in x
# pytest.assume("1" in x)
# pytest.assume("1" not in x)
# pytest.assume("s" in x)
# pytest.assume("s" not in x)
def test_five(self):
print("請開始執行 test_five 方法")
x = "this"
assert "s" in x
if __name__ == "__main__":
pytest.main("-v -s")
# pytest.main(['-v','-s'])
執行結果:
11、pytest-fixture的用法
例子:
12、公共模塊conftest的應用
13、yield的應用,用來進行數據回收
例子:scope="module"是可以修改的,默認function
14、不想原有測試方法有任何改動,或全部都自動實現自動應用,我們使用fixture中參數autouse=Ture實現
autouse=Ture默認是False,可以自己更改成Ture
15、fixture帶參數傳遞
fixture固件函數需要傳參,如果@pytest.fixture()裏面沒有傳參,可以通過@pytest.mark.parametrize()給固件函數傳參,即indirect=True。並且固件函數的返回值作爲Test函數的參數,不寫的話傳參的函數是不會調用的
16、某些場景跳過個別用例執行,這時我們需要用到@pytest.mark.skip和@pytest.mark.xfail
17、對用例進行標記
例子:
去除標籤警告:
18、多線程並行與分佈式執行用例
19、生成htm報告
待更新,營養跟不上了