前言:
上一篇pytest文檔2 -- 用例的執行規則已經介紹了如何在cmd執行pytest用例,平常我們寫代碼在pycharm比較多
寫完用例后,需要調試看看,是否正常運行,如果每次跑cmd執行,太麻煩,所以很有必要學習如何在pycharm里賣弄運行pytest用例
Pycharm運行的三種方式:
1、以xx.py腳本方式直接執行,當寫的代碼里面沒有用到unittest 和pytest框架時,並且腳本名稱不是以test開頭命名的,此時pycharm’ 會以xx.py腳本方式運行
2、當腳本名為test_xx.py時,用到unitest框架,此時運行代碼,pycharm會自動識別到以unittest方式運行
3、以pytest方式運行,需要改該工程默認的運行器,file->setting->Tools->Python Integrated Tools ->項目名稱-> Default test runner -->選擇 py.test
備注:pytest 是可以兼容unittest框架代碼的。
pycharm 寫pytest代碼
1、在pycharm里面寫pytest用例,要先導入pytest
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File : Test_class.py
# Time :2021/11/16 19:39
# Author :author Richard_kong
# version :python 3.8
# Description:
"""
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(['-s', 'test_class.py'])
運行結果 .F. 點代表測試通過,F代表Fail的意思, pytest.main() 里面要傳遞的是 list,多個參數放在list中就不會有告警
pytest.main(['-q','test_class'])
pytest.main()的含義:
每個項目都有入口文件用來啟動項目,但是在自動化項目里,特別是unitest框架 在項目新建一個main.py 或者run_all.py文件 使用python main.py或者python run_all.py執行測試用例。
在pytest框架也有一個入口,那就是pytest.main(),可以作為用例執行入口,下面對pytest.main()進行講解:
def main(
args: Optional[Union[List[str], py.path.local]] = None,
plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None,
) -> Union[int, ExitCode]:
"""Perform an in-process test run.
:param args: List of command line arguments.
:param plugins: List of plugin objects to be auto-registered during initialization.
:returns: An exit code.
"""
try:
try:
config = _prepareconfig(args, plugins)
except ConftestImportFailure as e:
exc_info = ExceptionInfo(e.excinfo)
tw = TerminalWriter(sys.stderr)
tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
exc_info.traceback = exc_info.traceback.filter(
filter_traceback_for_conftest_import_failure
)
exc_repr = (
exc_info.getrepr(style="short", chain=False)
if exc_info.traceback
else exc_info.exconly()
)
formatted_tb = str(exc_repr)
for line in formatted_tb.splitlines():
tw.line(line.rstrip(), red=True)
return ExitCode.USAGE_ERROR
else:
try:
ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
config=config
)
try:
return ExitCode(ret)
except ValueError:
return ret
finally:
config._ensure_unconfigure()
except UsageError as e:
tw = TerminalWriter(sys.stderr)
for msg in e.args:
tw.line(f"ERROR: {msg}\n", red=True)
return ExitCode.USAGE_ERROR
重點參數說明:args
param args: List of command line arguments
翻譯:參數args:就是參數傳入 以 列表的方式傳入
main()命令行參數詳情
-s: 顯示程序中的print/logging輸出
-v:豐富信息魔術,輸出更詳細的用例執行信息
-q:安靜模式,不輸出環境信息
-x:出現一條測試用例失敗就退出測試。調試階段非常有用
-k:可以使用 and not or 等邏輯運算符,區分:匹配方法(文件名、類名、函數名)
當不傳入參數時,相當於執行命令 pytest **.py 來執行測試用例
當 輸入參數 -s -v -x時 相當於命令行輸入 pytest -s -v -x
pytest.main(['-s','-v','-x'])
Pycharm設置pytest
1、新建一個工程后,左上角file -> setting -> tools-> python integrated Tools->項目名稱-> Default test runer -> 選擇py.test

改完之后,再重新建個腳本(注意是先改項目運行方式,再寫代碼才能出來),接下來右鍵運行就能出來pytest運行了

pytest是可以兼容unitest腳本的,之前寫的unittest用例也可以使用pytest框架來運行
