测试框架pytest教程(11)-pytestAPI

常量

pytest.__version__ #输出pytest版本

 

 

pytest.version_tuple #输出版本的元组形式

 

 

功能

pytest.approx

`pytest.approx` 是一个用于进行数值近似比较的 pytest 断言工具。

在测试中,有时候需要对浮点数或其他具有小数部分的数值进行比较。然而,由于浮点数精度限制,直接使用相等判断可能会导致测试不稳定或失败。这时,就可以使用 `pytest.approx` 工具来进行近似比较。

`pytest.approx` 可以用于比较单个值或列表、字典等数据结构的值。

以下是 `pytest.approx` 的常见用法示例:

```python
import pytest

def test_approx():
    assert 0.1 + 0.2 == pytest.approx(0.3)
    
def test_list_approx():
    assert [0.1, 0.2, 0.3] == pytest.approx([0.1, 0.2, 0.3])
    
def test_dict_approx():
    assert {"a": 0.1, "b": 0.2} == pytest.approx({"a": 0.1, "b": 0.2})
```

在上述示例中,第一个测试用例使用 `pytest.approx(0.3)` 来判断 `0.1 + 0.2` 是否近似于 `0.3`。第二个测试用例使用 `pytest.approx([0.1, 0.2, 0.3])` 来比较两个列表是否近似相等。第三个测试用例使用 `pytest.approx({"a": 0.1, "b": 0.2})` 来比较两个字典是否近似相等。

`pytest.approx` 在进行比较时会考虑到浮点数的精度问题,具有一定的容错性。可以通过设置 `rel` 和 `abs` 参数来调整容忍度。例如 `pytest.approx(0.3, rel=1e-3, abs=1e-5)` 可以设置相对误差不超过 `1e-3`,绝对误差不超过 `1e-5`。

pytest.fail

`pytest.fail` 是一个用于强制测试用例失败的 pytest 断言工具。

在某些情况下,您可能希望在测试中明确主动地使测试用例失败,而不是依赖其他断言条件或业务逻辑来触发失败。

`pytest.fail` 函数可以用于在测试中显式地引发 AssertionError,导致当前测试用例立即失败。

以下是 `pytest.fail` 的示例用法:

```python
import pytest

def test_fail():
    pytest.fail("Test case intentionally fails")
```

在上述示例中,`test_fail` 函数调用 `pytest.fail("Test case intentionally fails")` 来强制使测试用例失败,并提供一个可选的错误信息。

当测试运行到 `pytest.fail` 调用时,将引发 `AssertionError`,并且测试用例会立即失败。测试运行将停止,并且不会执行该用例后续的代码。

`pytest.fail` 函数还支持其他参数,例如 `pytrace=True` 用于显示堆栈跟踪信息,`skip=True` 用于标记测试用例为跳过状态。

请注意,在正常的测试编写中,尽量避免过多使用 `pytest.fail`,它应该被视为一种辅助工具,用于某些特殊场景下的测试目的。

pytest.skip

`pytest.skip` 是一个用于跳过测试用例的 pytest 断言工具。

在某些情况下,您可能希望在测试中主动跳过某些用例,而不是执行它们。`pytest.skip` 函数可以用于在测试运行时标记测试用例为跳过状态,告诉 pytest 不要执行这些用例。

以下是 `pytest.skip` 的示例用法:

```python
import pytest

def test_skip():
    pytest.skip("This test case is skipped intentionally")
```

在上述示例中,`test_skip` 函数调用 `pytest.skip("This test case is skipped intentionally")` 来标记测试用例为跳过状态,并提供一个可选的跳过说明。

当测试运行到 `pytest.skip` 调用时,该用例将被跳过,在测试报告中被标记为跳过状态。测试运行将继续进行,并且不会执行该用例后续的代码。

`pytest.skip` 函数还支持其他参数,例如 `allow_module_level=True` 用于允许跳过整个模块。

请注意,在正常的测试编写中,应该根据测试需要谨慎使用 `pytest.skip`。它通常用于某些特殊场景下,例如在某些条件不满足时跳过某些用例,或者在暂时无法实现某些功能时跳过相关的测试。

pytest.importorskip

`pytest.importorskip` 是一个 pytest 工具,用于在测试中动态导入所需的模块,如果导入失败则跳过测试用例。

有时,测试用例可能依赖于外部模块或库,如果在运行测试用例之前无法导入所需的模块,则这些用例可能会失败。为了避免因为缺少依赖而导致测试用例无法执行,您可以使用 `pytest.importorskip` 来跳过这些用例。

以下是 `pytest.importorskip` 的示例用法:

```python
import pytest

def test_dependency():
    module = pytest.importorskip("module_name")
    # 使用module进行进一步的测试
```

在上述示例中,`test_dependency` 函数使用 `pytest.importorskip` 导入名为 "module_name" 的模块。如果无法导入该模块,则测试用例将被跳过,不会执行后续的代码。

`pytest.importorskip` 函数会尝试导入指定的模块,如果导入失败,则会引发 `pytest.skip` 异常,该异常会被 pytest 捕获,并将相应的测试用例标记为跳过状态。

请注意,`pytest.importorskip` 可以接受其他参数,用于控制导入的行为,例如 `minversion` 参数用于指定要求的最低版本号,`reason` 参数用于提供跳过用例的说明。

无法导入,该条用例跳过 

pytest.xfail

预期用例失败

pytest.exit

`pytest.exit` 函数是 pytest 的一个工具,用于在测试运行期间提前退出测试过程。

在某些情况下,您可能希望在测试执行过程中主动退出,而不继续执行后续的测试用例。`pytest.exit` 函数可以用于在测试运行时提前终止测试过程。

以下是 `pytest.exit` 的示例用法:

```python
import pytest

def test_exit():
    pytest.exit("Testing is interrupted")
```

在上述示例中,`test_exit` 函数调用 `pytest.exit` 来提前终止测试执行,并提供一个可选的退出信息。

当测试运行到 `pytest.exit` 调用时,测试过程将立即终止,当前运行的测试用例将被中断,后续的测试用例将不会执行。同时,测试报告中会记录异常退出信息。

请注意,使用 `pytest.exit` 函数需要小心,并且只应在特殊情况下使用。正常情况下,测试用例应该按照规定的顺序执行,并且尽量避免意外退出测试过程。

pytest.main

执行入口

pytest.param

`pytest.param` 是 pytest 提供的一个装饰器函数,用于给测试参数化过程中的每个参数提供自定义的元数据。

在 pytest 中,参数化是一种技术,用于在执行同一个测试函数时,多次运行该函数,并为每次运行传递不同的参数组合。`pytest.param` 装饰器函数可以为每个参数组合提供自定义的元数据,这些元数据可以在测试报告中提供更多的信息。

以下是 `pytest.param` 的示例用法:

import pytest

@pytest.mark.parametrize("param", [
    pytest.param("good", marks=pytest.mark.first),
    pytest.param("morning", marks=pytest.mark.second)
])
def test_param(param):
    assert len(param) > 0

在上述示例中,`test_param` 函数通过 `@pytest.mark.parametrize` 装饰器实现参数化。`pytest.param` 函数用于为每个参数提供自定义的元数据。在示例中,第一个参数值 "value1" 标记为 `pytest.mark.first`,第二个参数值 "value2" 标记为 `pytest.mark.second`。

通过为每个参数组合提供自定义的元数据,您可以在测试报告中识别和过滤特定的用例,以及运行自定义的处理逻辑,比如添加标记、过滤用例等。

请注意,使用 `pytest.param` 装饰器需要在参数化过程中使用 `@pytest.mark.parametrize` 装饰器进行配合。

pytest.raises

`pytest.raises` 是 pytest 提供的一个上下文管理器,用于检查测试用例中是否引发了指定的异常。

在测试过程中,有时您可能会希望测试某些代码在特定情况下是否会引发预期的异常。`pytest.raises` 上下文管理器可以帮助您捕获和断言这些异常。

以下是 `pytest.raises` 的示例用法:

```python
import pytest

def test_raises():
    with pytest.raises(Exception):
        # 在此处编写可能引发异常的代码
        raise Exception("An error occurred")
```

在上述示例中,`test_raises` 函数使用 `with pytest.raises(Exception):` 语句块来标识捕获异常的范围。在 `with` 代码块中,您可以编写可能引发异常的代码。在示例中,我们手动引发了一个 `Exception` 类型的异常。

当代码块中引发了指定类型的异常时,`pytest.raises` 将捕获该异常,测试将继续进行,并进行后续的断言。如果代码块中没有引发指定类型的异常,`pytest.raises` 将引发一个断言错误,测试将被标记为失败。

通过使用 `pytest.raises`,您可以确保代码在预期情况下引发了异常,并可以对异常进行进一步的检查和断言。

请注意,`pytest.raises` 还支持对异常对象进行断言,例如检查异常的具体信息、属性等。可以通过使用 `as` 关键字来捕获异常对象,并对其进行断言。

fixture

record_property

`record_property` 是 pytest 的一个内置函数,用于在测试运行期间记录自定义的属性。

在测试过程中,您可能希望记录一些额外的信息或元数据,以便于后续分析和报告。`record_property` 函数提供了一种将自定义属性与测试用例关联起来的方法。

以下是 `record_property` 的示例用法:


def test_example(record_property):
    record_property("priority", "high")
    record_property("severity", "medium")

    # 编写测试断言...
    assert 1 + 1 == 2

在上述示例中,`record_property` 函数被用于记录两个自定义的属性:`priority` 和 `severity`。这些属性与测试用例 `test_example` 相关联。

在运行测试时,`record_property` 函数将记录这些属性值,并将其与该测试用例关联。这些属性值将显示在测试报告中,可以帮助您更好地理解和分析测试结果。

通过记录适当的属性,您可以为测试结果提供更多的上下文,例如标记测试的优先级、严重性级别等。这对于组织和分析大规模测试套件非常有用。

`record_property` 函数可以在测试用例的任何位置调用,以记录所需的属性。通常,它在测试用例顶部作为一种常见的做法,以便更容易找到和识别相关属性。

record_testsuite_property

 记录testsuite的属性

def test_foo(record_testsuite_property):
    record_testsuite_property("ARCH", "PPC")
    record_testsuite_property("STORAGE_TYPE", "CEPH")

request

`request` 是 pytest 中的一个固定参数,用于访问测试用例运行时的上下文信息和功能。

在 pytest 的测试用例中,可以通过使用 `request` 参数来获取有关当前测试用例和测试运行环境的信息。`request` 参数是一个固定的 pytest fixture,可以在测试用例函数或其他 fixture 中使用。

以下是一些常见的 `request` 对象的用法:

1. 获取当前测试用例的名称:

def test_example(request):
    test_name = request.node.name
    print(f"Running test: {test_name}")
    # 其他测试断言和操作...

2. 获取当前测试用例的标记信息:

import pytest

@pytest.mark.smoke
def test_example(request):
    marker = request.node.get_closest_marker("smoke")
    if marker:
        print("This test is marked as smoke test")
    # 其他测试断言和操作...

3. 获取测试用例函数的 docstring:

def test_example(request):
    """这是一个test"""
    docstring = request.node.function.__doc__
    print(f"Test function docstring: {docstring}")
    # 其他测试断言和操作...

 

 

4. 访问配置文件中的自定义参数:

def test_example(request):
    my_param = request.config.getoption("--my-param")
    print(f"My custom parameter: {my_param}")
    # 其他测试断言和操作...

通过使用 `request` 对象,您可以在测试用例运行时获得更多的上下文信息,并根据需要执行各种操作,例如获取标记、访问配置等。

对象

Item

在 pytest 中,`Item` 类代表着一个测试项目,可以是一个测试用例、一个测试集合或一个测试模块。`Item` 类是 pytest 框架中的一个重要概念,用于管理和操作测试项目的相关信息和行为。

`Item` 类的实例包含了诸如测试项目的名称、位置、标记、参数、测试路径等信息。它也提供了一组方法和属性,用于操作和访问测试项目的各个方面。

以下是 `Item` 类的一些常见方法和属性:

1. `name` - 返回测试项目的名称。

```python
def test_example(item):
    print(f"Test name: {item.name}")
```

2. `nodeid` - 返回测试项目的唯一标识符。

```python
def test_example(item):
    print(f"Node ID: {item.nodeid}")
```

3. `get_closest_marker(name)` - 返回最接近的标记对象。

```python
import pytest

@pytest.mark.smoke
def test_example(item):
    marker = item.get_closest_marker("smoke")
    if marker:
        print("This test is marked as smoke test")
```

4. `get_marker(name)` - 返回与指定名称匹配的第一个标记对象。

```python
import pytest

@pytest.mark.slow
@pytest.mark.smoke
def test_example(item):
    marker = item.get_marker("smoke")
    if marker:
        print("This test is marked as smoke test")
```

5. `keywords` - 返回测试项目的关键字。

```python
def test_example(item):
    print(f"Test keywords: {item.keywords}")
```

`Item` 类还提供了其他一些方法和属性,用于获取和操作测试项目的参数、位置、路径以及与测试框架相关的信息。

config

在 pytest 中,`Config` 类是一个重要的概念,它代表了 pytest 的配置对象。`Config` 类提供了访问和配置 pytest 运行时的各种选项和参数的方法和属性。

`Config` 对象可以通过在自定义的 pytest 插件中使用 `pytest_configure(config)` 钩子函数中的 `config` 参数来获取。

下面是 `Config` 类的一些常见方法和属性:

1. `getoption(name)` - 获取命令行选项或配置文件中的选项的值。

def pytest_configure(config):
    my_option = config.getoption("--my-option")
    print(f"My option value: {my_option}")

2. `addinivalue_line(name, value)` - 在配置文件中添加一行配置。

def pytest_configure(config):
    config.addinivalue_line("markers", "smoke: mark a test as a smoke test.")

3. `getini(name)` - 获取配置文件中的值。

def pytest_configure(config):
    my_value = config.getini("my_option")
    print(f"My value from config file: {my_value}")

4. `getoption(name, default=None)` - 获取命令行选项或配置文件中的选项的值,如果不存在则返回指定的默认值。

def pytest_configure(config):
    my_option = config.getoption("--my-option", default="default_value")
    print(f"My option value: {my_option}")

除了上述示例外,`Config` 类还提供了许多其他有用的方法和属性,用于访问和配置 pytest 的各种选项和功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值