当前位置:网站首页>Pytest collection (2) - pytest operation mode
Pytest collection (2) - pytest operation mode
2022-07-01 21:36:00 【Practice it kiss】
One 、 Run in command line mode
1、 Run in command line mode pytest
Create a computer desktop named test_sample.py The new document of , Contains functions and test cases .
# content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5
open test_sample.py Folder in which ,cmd Window input command :pytest.pytest It will search the current directory and all its subdirectories with test_*.py or *_test.py file , Then execute the file with test Start function . See pytest Test case collection rules .
Microsoft Windows [ edition 10.0.19044.1766]
(c) Microsoft Corporation. All rights reserved .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>
explain :
- collected 1 item:pytest A total of 1 Test cases .
- test_sample.py F: Marked as F It means that the test result is failed .
- [100%] : Refers to the overall progress of running all test cases .
- FAILURES: Detailed error information is output , Help us analyze the test reason , We can see "assert func(3) == 5" There is an error in this statement , The reason for the mistake is func(3)=4, Then we assert that func(3) be equal to 5.
2、pytest Run result flags
- . Order number , Indicates that the use case passes
- F It means failure Failure
- E Indicates that there is an exception in the use case Error
- S Indicates that the use case is skipped Skip
- x Lowercase x Indicates expected failure xfail
- X uppercase X Indicates expected failure , But it passed
Two 、Pycharm Run in
1、Terminal Run in terminal
pycharm The project directory is as follows , Choose test_sample.py file , Right mouse button Open in | Open in Terminal, Enter in command line mode pytest
Microsoft Windows [ edition 10.0.19044.1766]
(c) Microsoft Corporation. All rights reserved .(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、 Configure the test runner
We can also choose the default by configuration pytest The way to run py file .
File | Settings | Tools | Python Integrated Tools
3、pytest.main() Method
pytest.main() Method can be used as the test case execution entry of our automated test project , Now we're right pytest.main()
Explain .
Modify the above test_sample.py The documents are as follows :
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'])
explain :
- pytest.main() : No parameters , All test cases under the current directory will be collected , It is equivalent to entering commands in command line mode pytest.
- pytest.main(['test_sample.py']) : One parameter , Execute the specified file test_sample.py All test cases of .
- pytest.main(['-q','test_sample.py']) : Two parameters , Parameters -q For quiet mode , Do not output environment information .
(1)pytest.main() Source code analysis
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
You can see , main() The function takes two arguments :
- args : Command line argument list , The same parameters as when running in command line mode , In the list List With string str In the form of , Multi parameter with “,” separate , You can also pass in tests case The path of .
- plugins : For plug-in parameters , List of plug-in objects to be automatically registered during initialization .
(2).pytest_cache Folder
pytest After all test cases are executed in the test framework, they will be generated in the current directory .pytest_cache , The information of the last use case execution is saved in it .
reference:
边栏推荐
猜你喜欢
Common components of flask
编程英语生词笔记本
leetcode刷题:栈与队列02(用队列实现栈)
2022熔化焊接与热切割上岗证题目模拟考试平台操作
基于K-means的用户画像聚类模型
Introduction à l'ingénierie logicielle (sixième édition) notes d'examen de Zhang haifan
2022年低压电工考试试题及答案
8K HDR!| Hevc hard solution for chromium - principle / Measurement Guide
leetcode刷题:二叉树01(二叉树的前序遍历)
Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
随机推荐
游览器打开摄像头案例
2022年低压电工考试试题及答案
Common components of flask
matlab遍历图像、字符串数组等基本操作
AirServer手机第三方投屏电脑软件
合成大西瓜小游戏微信小程序源码/微信游戏小程序源码
从20s优化到500ms,我用了这三招
最近公共祖先(LCA)在线做法
deb文件安装
vscode的使用
杰理之蓝牙耳机品控和生产技巧【篇】
深度学习 常见的损失函数
升级版手机检测微信工具小程序源码-支持多种流量主模式
Practical project notes (I) -- creation of virtual machine
打出三位数的所有水仙花数「建议收藏」
功利点没啥!
Uniapp uses Tencent map to select points without window monitoring to return users' location information. How to deal with it
tensorflow 张量做卷积,输入量与卷积核维度的理解
2022安全员-B证考试练习题模拟考试平台操作
Slf4j打印异常的堆栈信息