Exception assert

参考:

方法:

1
2
3
>>> import pytest
>>> with pytest.raises(ZeroDivisionError) as exe_info:
...    1/0

注意:

  1. 用于捕获单个 Exception

exception 文本匹配

解说:

  • 使用 match 关键字参数
  • 匹配对象

    • 文本
    • 正则
1
2
>>> with pytest.raises(ValueError, match=r'must be \d+$'):
...     raise ValueError("value must be 42")

直接传入函数和参数,不适用 with 语句

有参数

1
2
3
4
5
6
>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>

无参数

1
2
>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ...>

数据驱动

通过 csv 文件传入测试参数

参考:

例子:

  1. 单个参数
1
2
3
4
5
6
7
8
9
import pytest

def get_test_data():
    my_read_data()


@pytest.mark.parametrize('name', get_test_data())
def test_my_function(name: str):
    assert len(name) == 3
  1. 多个参数
1
2
3
4
5
6
7
# content of test_expectation.py
import pytest


@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

报告 report

命令行

1
pytest -s -v

html

1
2
3
pip install pytest-html # 依赖

py.test --html=report.html -s

monkeypatch 猴子补丁

参考:

用途:

  • mock python 对象的属性
  • 例子:

    1. 模块下的 变量 mock
    2. 模块下的 mock
    3. 类的 方法 mock
    4. 类的 字段 mock

用例:

  1. mock 文件的内容

    • 通过 Path.read_text 方法的 mock 来改变读取的内容

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      
      from pytest import MonkeyPatch
      
      
      def test_file_content():
          mock_content = 'this is the content'
      
          def mock_read_text(self, *args, **kwargs):
              return mock_content
      
          with MonkeyPatch() as m:
              from pathlib import Path
      
              assert 'content' in Path('/data/demo.txt').read_text()

      这里通过修改 Path 类的 read_text 方法,来 mock 文件读取的内容。

pytest 与 依赖注入(DI)、控制反转(IoC)