python - 使用 pytest 记录成功的测试用例断言

标签 python pytest

当 pytest 测试失败时,它会给我一个很好的描述,说明测试失败的确切位置,以及具体的值。

虽然这对于失败的测试来说真的很棒,但我也想为没有失败的测试获得这份报告。

例如:

    def test_one():
        a =  0
>       assert 0 < a <= 1  # to see what was printed
E       assert 0 < 0 <= 1

test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
first
1 failed in 0.12 seconds

如果测试没有失败,我还想看看 'a' 的值。

例如:

    def test_one():
        a = 0.5
>       assert 0 < a <= 1  # to see what was printed
E       assert 0 < 0.5 <= 1

test_sample.py:6: AssertionSuccess
--------------------------- Captured stdout call ---------------------------
first
1 passed in 0.12 seconds

最佳答案

我想,第一个测试用例中 a 的值为 0。 那是因为,您指定了,

def test_one():
    a=0

此外,您应该在参数中添加 self 以执行测试。

当我们通过设置 a=0 的值进行测试时,发生的情况是当我们比较 a 是否小于 1 或大于 0 时。两者都给出结果 false。因此,它会报错。

而在第二种情况下,

def test_one():
    a=0.5

当我们比较 a 是小于 1 还是大于 0.5 时会发生什么。两者都给出 true 的结果。因此,它给出了成功通过的测试。

-------- 已编辑-------- 您可以添加记录器以获取记录详细信息。

import logging
# Your code
logger = logging.logger()
logging.debug(a)

希望对您有所帮助! :)

关于python - 使用 pytest 记录成功的测试用例断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54530826/

相关文章:

python - 将两个 Pandas 数据帧与仅添加整数计数相结合

python - 为什么我的 if, else 语句在 python 的 while 循环中不起作用

python - 使用 Motor AsyncIO 和 Pytest 测试 MongoDB 功能

python - pytest-nodev : automatic permutation of arguments

python - 在函数中模拟函数

python-3.x - 通过 Pytest 和 Requests 测试 Django 时 MissingSchema 错误

python - 如何使用 pytest-mock 或 magicmock 模拟导入的对象

python - Django 身份验证 : password change template customization

python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?

python - 无法使用 Python 中的现有 VPC 通过 CDK 创建 EC2