当前位置:网站首页>pytest合集(2)— pytest运行方式
pytest合集(2)— pytest运行方式
2022-07-01 21:32: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:
边栏推荐
- 随机头像大全,多分类带历史记录微信小程序源码_支持流量主
- Halcon知识:三维重构的一个尝试
- 朋友圈社区程序源码分享
- Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
- 合成大西瓜小游戏微信小程序源码/微信游戏小程序源码
- idea中类中显示成员变量和方法
- Vulnerability recurrence - Net ueeditor upload
- PMP与NPDP之间的区别是什么?
- 架构师毕业总结
- leetcode刷题:栈与队列06(前 K 个高频元素)
猜你喜欢

Learn white box test case design from simple to deep

After adding cocoapods successfully, the header file cannot be imported or an error is reported in not found file

Comprehensive evaluation and detailed inventory of high-quality note taking software (I) note, obsedian, remnote, flowus

Data analysts sound tall? Understand these points before you decide whether to transform

杰理之、产线装配环节【篇】

PMP与NPDP之间的区别是什么?

朋友圈社区程序源码分享

基于K-means的用户画像聚类模型

新牛牛盲盒微信小程序源码_支持流量变现,带完整素材图片

latex如何打空格
随机推荐
网上开户是安全的吗?新手可以开炒股账户吗。
Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)
关联线探究,如何连接流程图的两个节点
从20s优化到500ms,我用了这三招
Keras machine translation practice
【智能QbD风险评估工具】上海道宁为您带来LeanQbD介绍、试用、教程
Using qeventloop to realize synchronous waiting for the return of slot function
十三届蓝桥杯B组国赛
游览器打开摄像头案例
After adding cocoapods successfully, the header file cannot be imported or an error is reported in not found file
Richview trvdocparameters page parameter settings
功利点没啥!
能升职加薪?PMP证书含金量浅析
统计字符中每个字符出现的个数
目标检测——Yolo系列
UVM教程
NIO与传统IO的区别
GCC编译
杰理之蓝牙耳机品控和生产技巧【篇】
Principle of motion capture system