pytest学习笔记1

1、安装pytest

pip install -U pytest

2、查看pytest版本

pytest --version  或 
pytest -V

3、pytest用例设计原则

  • 1、测试文件以test开头(或者以_test结尾)
  • 2、测试类以Test开头,并且不能带init方法
  • 3、测试函数以test_开头
def add(x, y):
    return x + y

def test_add():
    assert add(1, 10) == 11
    assert add(1, 1) == 2
    assert add(1, 99) == 100

class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x

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

    def three(self):
        x = "hello"
        assert hasattr(x, "hello")        
--------------

pytest_demo/test_sample.py::test_add PASSED                                                                                                 [ 33%]
pytest_demo/test_sample.py::TestClass::test_one PASSED                                                                                      [ 66%]
pytest_demo/test_sample.py::TestClass::test_two FAILED                                                                                      [100%]

4、执行用例规则

  • 1、执行某个目录下所有用例
pytest 文件名/
  • 2、执行某个py文件下的所有用例
pytest *.py
  • 3、按关键字匹配
pytest -k "类名 or 方法名"
  • 4、执行某个py文件下的某个类
pytest *.py::类名
  • 5、执行某个py文件下的的某个类得某个方法
pytest *.py::类名:方法名
  • 6、执行所有标记的用例
pytest -m [标记名]

5、pytest运行参数

  • 无参数
    • 读取路径下所有符合规则的文件,类、方法、函数全部执行,使用方法:pytest 或 py.test
  • -v参数
    • 打印详细的运行日志信息,一般在调试的时候加上这个参数、使用方法:pytest -v
  • -s 参数:
    • 带控制太输出结果,当代码中有print输出语句,如果想在运行结果中打印print输出的代码,在运行时可以添加-s 参数,一般在调试时候使用
  • -m 参数
    • 将运行有@pytest.mark.[标记名]这个标记的测试用例,使用方法: pytest -m [标记名]
  • -k 参数
    • 运行指定的某些用例,或者模糊匹配用例
  • -q 参数 --quiet decrease verbosity
    • 显示简单结果
  • -x 参数
    • 遇到运行失败的用例就停止执行后面的用例
  • –maxfail=num
    • 当错误用例达到指定用例数时,停止

6、用例运行模式

  • 模块级(setup_module/teardown_module)
  • 函数级(setup_function/teardown_function)(类外面)
  • 类级(setup_class/teardown_class)
  • 方法级(setup_method/teardown_method)(类里面)
  • 方法级(setup/teardown)

猜你喜欢

转载自blog.csdn.net/LiaoBin0608/article/details/106661944