当前位置:网站首页>pytest合集(2)— pytest運行方式
pytest合集(2)— pytest運行方式
2022-07-01 21:35:00 【篤行之.kiss】
一、命令行模式運行
1、命令行模式運行pytest
電腦桌面創建一個名為test_sample.py的新文件,包含函數和測試用例。
# content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5
打開test_sample.py所在的文件夾,cmd窗口輸入命令:pytest。pytest會查找當前目錄及其子目錄下所有以test_*.py或*_test.py文件,然後執行文件中以test開頭函數。詳見pytest測試用例收集規則。
Microsoft Windows [版本 10.0.19044.1766]
(c) Microsoft Corporation。保留所有權利。C:\Users\057776\Desktop>pytest
==================================== test session starts ====================================
platform win32 -- Python 3.8.8, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\057776\Desktop
plugins: html-3.1.1, metadata-1.11.0, rerunfailures-9.1.1, assume-2.2.0, requests-mock-1.7.0
collected 1 itemtest_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:18: AssertionError
================================= short test summary info =================================
FAILED test_sample.py::test_answer - assert 4 == 5
==================================== 1 failed in 0.70s ====================================C:\Users\057776\Desktop>
說明:
- collected 1 item:pytest運行的時候一共收集到了1條測試用例。
- test_sample.py F:標記為F是指測試結果是失敗的。
- [100%] :指運行所有測試用例的總體進度。
- FAILURES:輸出了詳細的錯誤信息,幫助我們分析測試原因,我們可以看到"assert func(3) == 5"這條語句出錯了,錯誤的原因是func(3)=4,然後我們斷言func(3) 等於 5。
2、pytest運行結果標記符
- . 點號,錶示用例通過
- F 錶示失敗 Failure
- E 錶示用例中存在异常 Error
- S 錶示用例被跳過 Skip
- x 小寫的 x 錶示預期失敗 xfail
- X 大寫的 X 錶示預期失敗,但是通過了
二、Pycharm中運行
1、Terminal終端中運行
pycharm項目目錄如下,選中test_sample.py文件,鼠標右鍵Open in | Open in Terminal,在命令行模式下輸入pytest
Microsoft Windows [版本 10.0.19044.1766]
(c) Microsoft Corporation。保留所有權利。(venv) C:\Users\057776\PycharmProjects\pytest-demo\testcases>pytest
================================== test session starts ===================================
platform win32 -- Python 3.8.8, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\057776\PycharmProjects\pytest-demo\testcases
plugins: html-3.1.1, metadata-1.11.0, rerunfailures-9.1.1, assume-2.2.0, requests-mock-1.7.0
collected 1 itemtest_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:18: AssertionError
================================ short test summary info ================================
FAILED test_sample.py::test_answer - assert 4 == 5
=================================== 1 failed in 0.60s ===================================(venv) C:\Users\057776\PycharmProjects\pytest-demo\testcases>
2、配置測試運行器
我們也可以通過配置來選擇默認pytest的方式來運行py文件。
File | Settings | Tools | Python Integrated Tools
3、pytest.main()方法
pytest.main()方法可以作為我們自動化測試項目的測試用例執行入口,下面我們對pytest.main()
進行講解。
修改上面的test_sample.py文件如下:
import pytest # content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5 if __name__ == '__main__': pytest.main() # pytest.main(['test_sample.py']) # pytest.main(['-q','test_sample.py'])
說明:
- pytest.main() :無任何參數,會收集當前目錄下所有的測試用例,相當於命令行模式下輸入命令pytest。
- pytest.main(['test_sample.py']) :一個參數,執行指定文件test_sample.py的所有測試用例。
- pytest.main(['-q','test_sample.py']) :二個參數,參數-q錶示安靜模式, 不輸出環境信息。
(1)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
可以看到, main() 函數接受兩個參數:
- args :命令行參數列錶,和命令行模式運行時的參數相同,在列錶 List 裏以字符串 str 的形式,多參數以 “,” 隔開,也可以傳入測試case的路徑。
- plugins :為插件參數,初始化期間要自動注册的插件對象列錶。
(2).pytest_cache文件夾
pytest測試框架中執行完所有的測試用例後會在當前目錄下生成 .pytest_cache ,裏面就保存了上一次用例執行的信息。
reference:
边栏推荐
猜你喜欢
随机推荐
PHP gets the external chain address of wechat applet and applet store
2022安全员-B证考试练习题模拟考试平台操作
浏览器tab页之间的通信
杰理之关于长按开机检测抬起问题【篇】
杰理之、产线装配环节【篇】
Internship: gradually moving towards project development
idea中类中显示成员变量和方法
Using qeventloop to realize synchronous waiting for the return of slot function
How to connect the two nodes of the flow chart
股票手机开户哪个app好,安全性较高的
【深度学习】利用深度学习监控女朋友的微信聊天?
matlab遍历图像、字符串数组等基本操作
js数组拼接的四种方法[通俗易懂]
【商业终端仿真解决方案】上海道宁为您带来Georgia介绍、试用、教程
能升职加薪?PMP证书含金量浅析
leetcode刷题:二叉树02(二叉树的中序遍历)
杰理之、产线装配环节【篇】
基于LSTM模型实现新闻分类
NSI脚本的测试
Learn white box test case design from simple to deep