当前位置:网站首页>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) == 5open 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_ERRORYou 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:
边栏推荐
猜你喜欢
随机推荐
杰理之烧录上层版物料需要【篇】
Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
能升职加薪?PMP证书含金量浅析
PWN攻防世界cgpwn2
Importance of EDA tools to chip industry knowledge popularization
Spark面试题
MQ学习笔记
架构师毕业总结
杰理之蓝牙耳机品控和生产技巧【篇】
分离字符串中的字母和数字并使得字母在前数组在后
[multithreading] realize the singleton mode (hungry and lazy) realize the thread safe singleton mode (double validation lock)
杰理之、产线装配环节【篇】
杰理之、产线装配环节【篇】
杰理之关于长按开机检测抬起问题【篇】
What else do you not know about new set()
面试题:MySQL的union all和union有什么区别、MySQL有哪几种join方式(阿里面试题)[通俗易懂]
柒微自动发卡系统源码
运放-滞回(迟滞)比较器全流程实战计算
EMC-电路保护器件-防浪涌及冲击电流用
【Leetcode】最大连续1的个数









