一、pytest是一個接口測試框架,試用版起來比較輕便靈活。首先來介紹他的安裝:
直接使用命令 : pip install -U pytest
通過命令 :pytest --version 來查看版本信息
二、首先來創建第一個簡單的demo,可以在pycharm里面創建,並且運行,運行只需要配置一下就可以
# content of test_1.py
def func(x): return x + 1 def test_answer(): assert func(3) == 5

如何運行呢? 首先,測試的方法必須是test_開頭,文件名字是 test_*.py or *_test.py,如果在pycharm中的話,名字可以隨意起。
兩種運行方式:
1、進入到文件當前目錄,然后輸入命令pytest 就會執行所有的文件,也可以指定要執行的文件:pytest -q test_??.py
指定執行的文件名字
2、在pycharm里面配置如下:
Name隨便起一個名字,我起名為pytest
以下是運行結果:
換成類也是一樣的,多個測試方法在同一個類中:
運行的一些命令:
pytest test_mod.py 運行一個具體的模塊
pytest testing/ 運行一個路徑下的所有case
pytest -k "MyClass and not method" 運行包含MYClass類中的case,但是不包含名字為“method”這個case
pytest test_mod.py::test_func 運行模塊中的方法
pytest test_mod.py::TestClass::test_method 運行模塊中的類中的方法
pytest -m slow 將會運行所有被裝飾器裝飾過的方法,比如 @pytest.mark.slow
pytest --pyargs pkg.testing 運行testing包中的case
pytest -x # stop after first failure 在第一個case失敗以后就停止 pytest --maxfail=2 # stop after two failures 在第二個case失敗以后就停止
執行完命令的一些code的含義:
Exit code 0: | All tests were collected and passed successfully,所有的用例都被收集完成而且執行成功 |
---|---|
Exit code 1: | Tests were collected and run but some of the tests failed 所有的用例都被收集完成,但是失敗了一些 |
Exit code 2: | Test execution was interrupted by the user 執行過程中被執行者終止 |
Exit code 3: | Internal error happened while executing tests 執行過程中內部發生錯誤 |
Exit code 4: | pytest command line usage error pytest命令有錯誤 |
Exit code 5: | No tests were collected 沒有用例被收集 |