前言
首先說下為什么要學pytest,在此之前相信大家已經掌握了python里面的unittest單元測試框架,那再學一個框架肯定是需要學習時間成本的。
剛開始我的內心是拒絕的,我想我用unittest也能完成自動化測試,干嘛要去學pytest呢?最近看到越來越多的招聘要求會pytest框架了,也有小伙伴出去面試說會unittest框架被鄙視的。
所以學此框架應該至少有以下2個理由,第一條已經足夠:
- 學會了可以裝逼
- 可以避免被面試官鄙視
python鄙視鏈:pytest 鄙視 > unittest 鄙視 > robotframework 鄙視 > 記流水賬 鄙視 > "hello world"小白
pytest簡介
pytest是python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高。根據pytest的官方網站介紹,它具有如下特點:
- 非常容易上手,入門簡單,文檔豐富,文檔中有很多實例可以參考
- 能夠支持簡單的單元測試和復雜的功能測試
- 支持參數化
- 執行測試過程中可以將某些測試跳過(skip),或者對某些預期失敗的case標記成失敗
- 支持重復執行(rerun)失敗的case
- 支持運行由nose, unittest編寫的測試case
- 可生成html報告
- 方便的和持續集成工具jenkins集成
- 可支持執行部分用例
- 具有很多第三方插件,並且可以自定義擴展
安裝pytest
1.安裝方法
pip install -U pytest
2.pip show pytest查看安裝版本
pip show pytest
3.也可以pytest --version查看安裝的版本
pytest --version
This is pytest version 3.6.3, imported from d:\soft\python3.6\lib\site-packages\
pytest.py
快速開始
1.新建一個test_sample.py文件,寫以下代碼
# content of test_sample.py
def func(x):
return x +1
def test_answer():
assert func(3)==5
2.打開test_sample.py所在的文件夾,cmd窗口輸入:pytest(或者輸入py.test也可以)
D:\YOYO>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO, inifile:
collected 1 item
test_sample.py F [100%]
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
def test_answer():
> assert func(3)==5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:6: AssertionError
========================== 1 failed in 0.19 seconds ===========================
3.pytest運行規則:查找當前目錄及其子目錄下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test開頭函數並執行。
寫個測試類
1.前面是寫的一個test開頭的測試函數,當用例用多個的時候,寫函數就不太合適了。這時可以把多個測試用例,寫到一個測試類里。
# 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')
2.pytest會找到符合規則(test_.py和_test.py)所有測試,因此它發現兩個test_前綴功能。 如果只想運行其中一個,可以指定傳遞文件名test_class.py來運行模塊:
備注: -q, --quiet decrease verbosity( 顯示簡單結果)
py.test -q test_class.py
D:\YOYO>py.test -q test_class.py
.F [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x00000000039F1828>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:11: AssertionError
1 failed, 1 passed in 0.04 seconds
第一次測試通過,第二次測試失敗。 您可以在斷言中輕松查看失敗的原因。
pytest用例規則
- 測試文件以test_開頭(以_test結尾也可以)
- 測試類以Test開頭,並且不能帶有
__init__
方法 - 測試函數以test_開頭
- 斷言使用assert
---------------------------------pytest結合selenium自動化完整版-------------------------
全書購買地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b
作者:上海-悠悠 QQ交流群:874033608
也可以關注下我的個人公眾號:yoyoketang