Python中函数打印语句的Unittest



我正在努力寻找一种方法,在使用assert语句的错误消息的同时对函数进行单元测试。如有任何帮助,不胜感激。

def divisible_by_five(x):
assert x % 5 == 0, "The number is not divisible by 5"
print("The number is divisible by 5")

失败的assert语句引发一个带有消息的AssertionError,可以像使用pytest.raises上下文管理器测试任何其他类型的异常实例一样进行测试。

可以这样测试打印输出和断言消息:
import pytest
from mymod import divisible_by_five

def test_divisible_by_five(capsys):
divisible_by_five(10)
out, err = capsys.readouterr()
assert out == "The number is divisible by 5n"

def test_not_divisible_by_five():
with pytest.raises(AssertionError("The number is not divisible by 5")):
divisible_by_five(11)

pytest.raises提供一个异常实例需要安装我的插件pytest-raisin。

一个不使用插件的等效测试可以这样写:

import re
def test_not_divisible_by_five():
expected_message = "The number is not divisible by 5"
with pytest.raises(AssertionError, match=f"^{re.escape(expected_message)}$"):
divisible_by_five(11)

不知道你的测试是什么样子。我决定写一个测试,也修改了你的divisible_by_five(x)返回str只是为了告诉你它是如何工作的。

import unittest

def divisible_by_five(x):
assert x % 5 == 0, "The number is not divisible by 5"
print("The number is divisible by 5")
return "The number is divisible by 5"

class TestDivisibleByFive(unittest.TestCase):
def test_divisible_by_five(self):
# Test if the function works as expected for a number divisible by 5
self.assertEqual(divisible_by_five(20), "The number is divisible by 5")
# Test if the function raises an exception for a number not divisible by 5        
with self.assertRaises(AssertionError) as err:
divisible_by_five(11)
self.assertEqual(str(err.exception), "The number is not divisible by 5")

if __name__ == "__main__":
unittest.main()

您可以使用try: ... except将错误包裹在自定义内容周围:

def test(x: float):
try:
assert x % 5 == 0
print(f"{x} is divisible by 5")
except AssertionError as err:
print(f"{x} is not divisible by 5")
raise err

test(5)
# 5 is divisible by 5
test(3)
# 4 is not divisible by 5
# Traceback (most recent call last):
#   File ..., line 11, in <module>
#     test(4)
#   File ..., line 7, in test
#     raise err
#   File ..., line 3, in test
#     assert x % 5 == 0
# AssertionError

相关内容

  • 没有找到相关文章

最新更新