安装

pip install pytest


基本使用

使用assert就可以作为检查点了

# content of test_sample.py
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

pytest 以下规则 寻找 测试项:

比如,下面是把 多个测试项 放在 类 中的写法

# content of test_class.py
class TestABC:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

测试类不需要继承什么父类, 也不需要我们实例化 该类, pytest 执行的时候会自己进行实例化操作。


如果我们的预期是 某个函数调用 就应该 抛出 某个异常,可以这样写

# content of test_sysexit.py
import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

用例目录结构

初始化、清除

Local conftest.py plugins contain directory-specific hook implementations. Hook Session and test running activities will invoke all hooks defined in conftest.py files closer to the root of the filesystem. Example of implementing the pytest_runtest_setup hook so that is called for tests in the a sub directory but not for other directories:

a/conftest.py:
    def pytest_runtest_setup(item):
        # called for running each test in 'a' directory
        print("setting up", item)

a/test_sub.py:
    def test_sub():
        pass

test_flat.py:
    def test_flat():
        pass

Here is how you might run it:

pytest test_flat.py –capture=no # will not show “setting up” pytest a/test_sub.py –capture=no # will show “setting up”

生成报表

挑选用例和套件执行

指定一个文件模块

pytest test_mod.py

指定目录

指定1个目录 pytest testing

也可以指定多个目录 pytest suite1 suite2

指定模块里面的函数或者类

pytest test_mod.py::test_func

pytest test_mod.py::TestClass::test_method

根据标签






扫码分享给朋友,一起学更有动力哦




下一页