当前位置:网站首页>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:
边栏推荐
- Comprehensive evaluation and detailed inventory of high-quality note taking software (I) note, obsedian, remnote, flowus
- Test of NSI script
- Spark面试题
- Penetration tools - trustedsec's penetration testing framework (PTF)
- 《QTreeView+QAbstractItemModel自定义模型》:系列教程之三[通俗易懂]
- 【智能QbD风险评估工具】上海道宁为您带来LeanQbD介绍、试用、教程
- BPR(贝叶斯个性化排序)
- 选择在同花顺上炒股开户可以吗?安全吗?
- 最近公共祖先(LCA)在线做法
- 同花顺股票开户选哪个券商好手机开户是安全么?
猜你喜欢
小鸟逃票登机,如何反思,应如何解决,飞机为何怕小鸟?
九章云极DataCanvas公司蝉联中国机器学习平台市场TOP 3
Importance of EDA tools to chip industry knowledge popularization
tensorflow 张量做卷积,输入量与卷积核维度的理解
Principle of motion capture system
杰理之、产线装配环节【篇】
图片拼图微信小程序源码_支持多模板制作和流量主
Entering Ruxin Town, digital intelligence transformation connects "future community"
收藏:存储知识全面总结
强大的万年历微信小程序源码-支持多做流量主模式
随机推荐
BPR(贝叶斯个性化排序)
2022安全员-A证考题及在线模拟考试
芭比Q了!新上架的游戏APP,咋分析?
图片拼图微信小程序源码_支持多模板制作和流量主
AirServer手机第三方投屏电脑软件
目标检测——Yolo系列
从20s优化到500ms,我用了这三招
PLC模拟量输入 模拟量转换FB S_ITR(三菱FX3U)
杰理之关于长按开机检测抬起问题【篇】
ngnix基础知识
Test of NSI script
Can I choose to open an account for stock trading on flush? Is it safe?
极客DIY开源方案分享——数字幅频均衡功率放大器设计(实用的嵌入式电子设计作品软硬件综合实践)
GCC编译
idea中类中显示成员变量和方法
Iframe parent-child page communication
leetcode刷题:栈与队列05(逆波兰表达式求值)
运放-滞回(迟滞)比较器全流程实战计算
Oracle deadlock test
[mysql] install mysql5.7