1、命令行启动
pytest框架是python经典单元测试框架,运行会自动识别测试项目中的测试用例,包含测试模块module(以
test_
开头)、测试类class(以Test
开头)、测试函数function(以test
开头)
命令: pytest [options] [file_or_dir] [file_or_dir] [...]
指定当前项目下的测试所有module:
pytest [option] .
指定某个文件:
pytest [option] test1.py
指定某个测试类:
pytest [option] test1.py::TestCaseClass
指定某个测试函数:
pytest [option] test1.py::TestCaseClass::test_func
常用option参数:
- -v: 显示测试的详细信息
- -s: 打印测试函数用例中的print信息,方便调试
- -q: 与-v相反, 静默输出信息
- -k: 允许使用表达式指定希望执行的测试用例, 批量执行用例, 例如: demo.py有三个测试用例函数,分别为: test_result、test_answer、test_func,
pytest -s -v -k "func or result" demo.py
则只会执行test_func 和 test_result用例函数- -x: 失败一次后不再执行后面的测试用例
- -maxfail=num: 最大失败次数,失败超过次数不再执行后面的用例
- -m: 配合pytest.mark使用,用作测试用例分组
-k参数实例:
-m参数实例:
在新版本的pytest中, 需要在pytest.ini中添加mark, 或者通过conftest.py中定义pytest_configure()函数添加mark(后面记录), 否则在执行测试用例过程中会产生PytestUnknownMarkWarning告警, pytest.ini应放在项目的根路径
pytest.ini添加如下:[pytest] markers = finish: has finished over: has over
2、pytest.main()启动
直接调用pytest.main()
方法启动, 以列表形式传入各个命令行参数
# -*- coding: UTF-8 -*-
# ---------------------------------------------------------
# @Author : Bingo
# @Time : 2021/4/17 0:03
# @File : demo1.py
# ---------------------------------------------------------
# There is no bug, have a great day. Please start your code.
import pytest
@pytest.mark.finish
def test_result():
assert 1 == 1
@pytest.mark.over
def test_answer():
assert 2 + 0 == 2
def test_func():
assert "hello".startswith("he")
if __name__ == "__main__":
pytest.main(["-s", "-v", "-m finish or over", "test_demo1.py"])
运行结果如下: