20200917 pytest 公开课

pytest

参考链接

pytest 用例识别

  • 测试文件
    • test_*.py
    • *_test.py
  • 用例识别
    • Test*类包含的所有test_*的方法(测试类不能带有__init__方法)
    • 不在class中的所有的test_*方法
  • pytest也可以执行unittest框架写的用例和方法

pytest 用例识别与运行2

终端执行
pytest --help 帮助文档
pytest/py.test
pytest –v (最高级别信息–verbose) 打印详细运行日志信息
pytest -v -s 文件名 (s是带控制台输出结果,也是输出详细)
pytest 文件名.py 执行单独一个pytest模块
pytest 文件名.py::类名 运行某个模块里面某个类
pytest 文件名.py::类名::方法名 运行某个模块里面某个类里面的方法
报错停止运行
pytest -x 文件名 一旦运行到报错,就停止 运行
pytest —maxfail=[num] 当运行错误达到num的时候就停止 运行

  • 只执行某条用例或者某一类用例
    • pytest -m [标记名] @pytest.mark.tags 将运行有这个标记的测试用例
    • pytest -k "类名 and not 方法名” 运行某个用例
  • 跳过执行
    • @pytest.mark.skip(reason=“当前版本不支持”) 跳过某条用例
    • @pytest.importorskip(“模块名",minversion=“1.5”) 跳过某个模块

参考代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 相加方法
import pytest
import yaml


def add(a, b):
    return a + b


def get_data():
    with open("./datas/add.yml") as f:
        adddatas = yaml.safe_load(f)
    return adddatas


class TestAdd:
    # 参数化
    @pytest.mark.parametrize('a,b,expect', get_data())
    def test_add1(self, a, b, expect):
        result = add(a, b)
        assert result == expect

    # def test_add2(self):
    #     result = add(0.1, 0.1)
    #     assert result == 0.2
    #
    # def test_add3(self):
    #     result = add(100, 200)
    #     assert result == 300