Pytest 使用介绍

发布时间: 更新时间: 总字数:3168 阅读时间:7m 作者: IP:上海 网址

pytest框架使编写小型测试变得简单,同时又能支持复杂的功能测试

介绍

  • Pytest 是用于测试 Python 应用lib库
  • 测试套件(test suites)是一个测试案例(Test cases)的集合,为测试执行目的而分组
  • pytest 支持自动在测试的目录中查找 test_*.py*_test.py 的文件,并加载测试用例
  • 命名规则
    • 测试文件:以 test_ 开头 或者 _test 结尾
    • 用例类测试文件中以 Test 开头的类\
    • 测试用例测试文件 中以 test 开头的方法或用例类方法
  • 判断
    • 使用 assert 关键字

安装

# 安装
pip3 install pytest

# 查看版本
$ pytest --version
pytest 7.4.3

help

pytest --help ...

使用

目录中运行

pytest
pytest <test-dir>/

指定测试文件

pytest sample_test.py

指定测试方法

  • 指定测试文件的指定方法,:: 后跟函数名称
pytest sample_test.py::test_answer
  • 使用表达式来运行需要的测试
pytest -k 'test_method or test_other'
  • Only run tests matching given mark expression
pytest -m 'mark1 and not mark2'

收集测试用例

  • 收集有哪些测试用例
pytest --collect-only

多进程、多线程

  • 多进程使用 -n num 指定
    • -n auto CPU 的个数
    • -n num 指定测试的CPU进程数
    • pytest-parallel 用于 并行并发 测试的 pytest 插件,类似的还有 pytest-xdist
      • pip install pytest-parallel
      • 通过 --workers--tests-per-worker 配置进程和线程数
      • pytest xxx_test.py --workers 2 --tests-per-worker 4
        • 2个进程并行,每个进程最多4个线程运行,总共最多8个线程运行

测试输出

  • 显示具体的测试用例
    • -x 失败立即停止
    • --maxfail 指定最大失败次数
    • -s 等价于 --capture=no,关闭捕获输出
    • -l/--showlocals 失败时,输出局部变量
    • -v 输出详细的信息,与 -q 相反
pytest -xvs xxx_test.py
  • 输出
    • pytest --capture=fd 默认,关闭输出
    • pytest -s 打开实时输出,关闭 Capture Log 输出
    • pytest --capture=sys 打开实时输出,Captrue Log 只捕获sys.outsys.err
    • pytest --capture=tee-syspytest -spytest --capture=sys 的组合

代码启动测试、传递参数

import pytest

pytest.main(['-v','-s'])

简单示例

  • sample_test.py
# content of test_sample.py
def inc(x):
    return x + 1


def test_answer():
    assert inc(3) == 5
  • 运行测试,提示一个测试用例失败
    • pytest -v sample_test.py 显示详细错误信息
    • 测试结果中
      • F 表示 fail 失败
      • s 表示 stip 跳过
      • . 表示成功
pytest sample_test.py ...

标记

通过标记将测试组织为单元,参考

  • marking_test.py
import pytest

@pytest.mark.eq
def test_eq1():
    assert (1) == (1)

@pytest.mark.eq
def test_eq2():
    assert (1, 2) == (1, 2)

@pytest.mark.join
def test_join1():
    assert "hello world" == "hello " + "hello"

@pytest.mark.join
def test_join2():
    assert "hi str" == "hi str"
[pytest]
markers =
  eq
  join
  • 调用
run test ...

跳过测试用例

import pytest

@pytest.mark.skip
def test_answer():
  print('skiped')

参数化

  • parametrized_test.py
import pytest

@pytest.mark.parametrize("v1, v2", [('hi1', 'hi1'), ('hi2', 'hi2')])
def test_eq(v1, v2):
    assert v1 == v2
pytest parametrized_test.py ...

fixture

  • fixture ​为测试提供可靠的、一致的上下文

  • 运行 pytest --fixtures

  • 支持 scope 作用域

  • fixture_test.py

import pytest

@pytest.fixture
def data():
    return 'hi'

def test_hi(data):
    assert 'hi' == data
pytest fixture_test.py ...

配置

关闭颜色

pytest 打印的日志带有颜色,日志显示带有如 31m 等字样, 原因是pytest内部有自己的logging color format设置(pytest --help 配置)

  • 方式一:可以通过设置环境变量关闭,参考
export PY_COLORS=0
# or
export NO_COLOR=1
  • 方式二:使用命令关闭 pytest --color=no
$ pytest --help
...
  --color=color         Color terminal output (yes/no/auto)

输出 html 报告

pytest-html 用于生成 HTML 报告的 pytest 插件,官方文档

  • 安装
pip install pytest-html
  • help
$ pytest --help | grep html
  --html=path           create html report file at given path.
  --self-contained-html
                        create a self-contained html file containing all
                        the html report.
  • 测试结果输出到一个 html 文件,--self-contained-html 会合并 css 样式到单个 html 文件
pytest sample_test.py --self-contained-html --html=report.html

与 Allure 集成

  • Allure 是一款轻量级并且非常灵活的开源测试报告框架,特点
    • 它支持绝大多数测试框架,例如TestNG、Pytest、JUint等
    • 简单易用,易于集成
  • Allure 安装部署参考
wget https://github.com/allure-framework/allure2/releases/download/2.24.1/allure_2.24.1-1_all.deb
apt install openjdk-8-jdk
dpkg -i allure_2.24.1-1_all.deb
  • 安装 allure-pytest 插件
pip install allure-pytest
  • help
$ pytest --help | grep allure
  --allure-severities=SEVERITIES_SET
  --allure-epics=EPICS_SET
  --allure-features=FEATURES_SET
  --allure-stories=STORIES_SET
  --allure-ids=IDS_SET  Comma-separated list of IDs.
  --allure-label=LABELS_SET
  --allure-link-pattern=LINK_TYPE:LINK_PATTERN
  --alluredir=DIR       Generate Allure report in the specified directory (may
  --clean-alluredir     Clean alluredir folder if it exists
  --allure-no-capture   Do not attach pytest captured logging/stdout/stderr
  • 生成报告,allure generate 参数
    • -o 生成报告的路径
    • -c|--clean 清理旧报告
# 1. 指定测试报告的生成路径
pytest --alluredir=./report/tmp

# 2. 生成测试报告
allure generate report/tmp/ -o report/html --clean

# 3. 打开报告,-h/-p指定ip和端口
allure open report/html/

# or 打开报告服务 web
allure serve report/html/
  • 配置 allure ENVIRONMENT 变量,./report/tmp/environment.properties
T1=1
T2=2

即可以在报告中显示环境变量,也可以使用 environment.xml 配置

  • allure支持使用标记为报告添加更多内容,如 @allure.feature("xxx")/@allure.step(xxx)
本文总阅读量 次 本站总访问量 次 本站总访客数