pytest的运行方式及如何控制测试用例的执行

一、pytest的运行方式

# file_name: test_add.py

import pytest  # 导入pytest包


def test_add01():  # test开头的测试函数
    print("----------------->>> test_add01")
    assert 1 # 断言成功


def test_add02():
    print("----------------->>> test_add02")
    assert 0 # 断言失败


if __name__ == '__main__':
    pytest.main(["-s", "test_add.py"])  # 调用pytest的main函数执行测试

1.1 测试类主函数模式运行:

pytest.main(["-s", "test_add.py"])

 

1.2 命令行模式运行:

pytest 文件路径 / 测试文件名

例如:pytest ./test_add.py

 

二、控制测试用例的执行

2.1 在第N个测试用例失败后,结束测试用例执行

pytest -X    # 第1次失败就停止测试

pytest --maxfail=2    # 出现2个失败就终止测试

 

2.2 执行测试模块

pytest test_add.py

 

2.3 执行测试目录

pytest ./pytest_study/

 

2.4 通过关键字表达式过滤执行

pytest -k "keyword and not other keyword"

这条命令会去匹配"文件名、类名、方法名"符合表达式的的测试用例!

举例:

# file_name: test_add.py

import pytest


def test_add01():
    print("----------------->>> test_add01")
    assert 1


def test_add02():
    print("----------------->>> test_add02")
    assert 0


def test_add03():
    print("test_add03")
    assert 1


def test_add04_abc():
    print("test_add04_abc")
    assert 1

执行命令:pytest  -k "test and not abc" -s ./pytest_study/test_add.py   (这个命令表示执行文件名、类名、方法名中关键字包含test但是不包含abc的用例)

从执行结果中可以看到,只有方法test_add04_abc()没有被执行!

 

2.5 通过node id指定测试用例运行

  node id由模块文件名、分隔符、类名、方法名、参数构成,举例如下:

  运行模块中指定方法或用例:

pytest test_mod.py::TestClass::test_func

 

2.6 通过标记表达式执行

pytest -m fast    # fast代表标记的名称,可自定义

这条命令会执行被装饰器 @pytest.mark.fast 装饰的所有测试用例

 举例:

# file_name: test_add.py


import pytest


@pytest.mark.slow
def test_add01():
    print("----------------->>> test_add01")
    assert 1


@pytest.mark.slow
def test_add02():
    print("----------------->>> test_add02")
    assert 0


@pytest.mark.fast
def test_add03():
    print("----------------->>> test_add03")
    assert 1

上面代码中方法test_add01()和test_add02()被标记为slow,test_add03()被标记为fast

执行命令:pytest -m fast ./pytest_study/test_add.py -s  (这个命令执行标记为fast的用例)

从上面的执行结果中可以看到,只有被标记为fast的用例test_add03()被执行了!

posted @ 2021-02-02 15:03  lwjnicole  阅读(1708)  评论(0编辑  收藏  举报